1
votes

I am running a Ansible Paybook using the Playbook and Inventory modules in Python. 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

This code build an Inventory module from group_vars in the ansible directory, but I would like to override some of those variable in the Inventory before passing it to the Playbook. How can I do this?

1

1 Answers

1
votes

The following works for me:

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