Ansible Inventory模块在Python中覆盖组变量

时间:2015-08-07 01:19:45

标签: python ansible ansible-playbook

我使用Python中的Playbook和Inventory模块运行Ansible Paybook。 E.g。

import ansible.inventory as ai

inventory = make_inventory(hosts,basedir="ansible")
playbook = PlayBook(
    playbook = "ansible/site.yml",
    private_key_file = "key.pem",
    remote_user = "ec2-user",
    remote_pass = None,
    become = True,   
    callbacks = playbook_cb,
    runner_callbacks = runner_cb,   
    stats = stats,
    inventory = inventory,   
    check=False 
)
playbook.run()

def make_inventory(hosts,basedir):
    inventory = ai.Inventory()
    myGroup = ai.group.Group(name="mygroup")
    allGroup = inventory.get_group("all")    
    for h in hosts:
        host = ai.host.Host(name=h.ip_address,port=22)            
        mygroup.add_host(host) 
        allGroup.add_host(host)        
    inventory.add_group(mygroup)      
    inventory.set_playbook_basedir(basedir) 
    return inventory

此代码在ansible目录中的group_vars中构建一个Inventory模块,但我想在将它传递给Playbook之前覆盖Inventory中的一些变量。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

以下适用于我:

class TestInventory(ai.Inventory):
    def __init__(self,*args,**kwargs):
        self.usecache = False
        super(self.__class__, self).__init__(*args,**kwargs)        

    def get_group_variables(self, groupname, update_cached=False, vault_password=None):
        if not self.usecache:
            super(self.__class__, self).get_group_variables(groupname,update_cached=True)
        return self._vars_per_group.get(groupname,{})

    def get_group_vars(self, group, new_pb_basedir=False):
        if not self.usecache:
            return super(self.__class__, self).get_group_vars(group, new_pb_basedir=new_pb_basedir)
        return self._vars_per_group.get(group.name,{})

def make_inventory(hosts,basedir):
    inventory = TestInventory()
    myGroup = ai.group.Group(name="mygroup")
    allGroup = inventory.get_group("all")    
    for h in hosts:
        host = ai.host.Host(name=h.ip_address,port=22)            
        mygroup.add_host(host) 
        allGroup.add_host(host)        
    inventory.add_group(mygroup)      
    inventory.set_playbook_basedir(basedir) 
    update_vars(inventory)
    return inventory

def update_vars(inventory):
    # Load variables into the cache
    inventory.get_group_variables("mygroup")
    inventory.get_group_variables("all")

    # Update the group vars in the cache
    av = inventory._vars_per_group['all']
    av['somevar'] = "something"
    av['password'] = "qaz"
    mv = inventory._vars_per_group['mygroup']
    mv['groupvar'] = "foo"

    inventory.usecache = True # dont reload vars from file from now on   
    basedir = inventory._playbook_basedir    
    inventory._playbook_basedir = "" # trick set_playbook_basedir into action
    inventory.set_playbook_basedir(basedir) # repopulate groups vars from cache