Tuesday, August 27, 2019

Working with dynamic inventories in Ansible using PHP (part 1)

As you probably know, Ansible has a great group inheritance mechanism. If you build the inventory file carefully, the benefits of inheritance are significant.

If you have a host belonging to group 'childgroup' and this group is a child of 'parentgroup' the variables set in the 'parentgroup' are inherited by the 'childgroup'. This way you avoid setting variables in multiple places, which is considered a best practice when writing playbooks.

Having to maintain a text file with few groups and hosts works quite well, but when you want to scale, you probably want to keep a database with your groups, hosts and the respective membership. The choice of database is a matter of personal preference, in my case I chose PostgreSQL.

There are several ways to do that and Ansible accepts several types of dynamic inventories. Instead of giving a filename as inventory in the command line, you specify an executable file written in any language you like, that returns json encoded data. I'm more familiar with PHP so I decided to use it instead of Python or another language. The command line looks like the following

ansible-playbook -i get_inventory.php my_sample_playbook.yml 

The data that is returned by the script must be in the format shown below and is documented at Developing dynamic inventory
{
    "group001": {
        "hosts": ["host001", "host002"],
        "vars": {
            "var1": true
        },
        "children": ["group002"]
    },
    "group002": {
        "hosts": ["host003","host004"],
        "vars": {
            "var2": 500
        },
        "children":[]
    }

}
Keep in mind that you don't have to return the 'vars' and 'children' sections if you don't actually utilize them. Ansible will accept the data structure, without any complain, even with just the 'hosts' section.

Well.. it's quite easy to say it.. but not so easy to develop such a script that will return this kind of structure.. We'll see that in part 2 of this story!






No comments:

Post a Comment