How and why I use Dynamic inventories and group vars with Ansible
I am a Senior Software Engineer interested in solving challenges involving scaling infrastructure easily and seamlessly.
The problem I wanted to solve
Since living in the cloud the belief needs to be that everything is ephemeral, in a world where things can disappear without notice how does someone maintain a list of hosts currently running?
What are Dynamic inventories and group vars ?
By leveraging dynamic inventories you can now map hosts based on groups provided by the inventory script. Without a dynamic inventory users are forced to maintain host mappings manually which can be tedious when you have many hosts that are constantly terminating and provisioning. Each time you execute Ansible, it generates a new inventory file based on the output of the dynamic inventory script. This is useful since our infrastructure is dynamic.
My experience has been with ec2.py, a dynamic inventory provided by Ansible for managing hosts in AWS. Out of the box ec2.py provides default groupings for hosts that allows us to design a variable hierarchy based on meta-data about the hosts.
The process of building Dynamic inventories and group vars
To begin download ec2.py and ec2.ini and place them in the root of your Ansible directory. Additionally download and place the Ansible configuration file in the root of you Ansible direcotry and set the inventory key to the location of ec2.py. For instance one of my favorite groups to use are the groups created by tags. Based on tags hosts are grouped together thus making our variable hierarchy more organized by placing all hosts with the same tag in a single group. We can now leverage Ansible’s group vars in unison with our tag group to apply vars to specific hosts. Say for example every host tagged with env = dev was to install a specific version of an application we could place a var
# group_vars/tag_env_dev.yml app_version: 1.0
in the group for tag_env_dev and that would be injected anywhere we referenced that variable where the host contained the env=dev. We could then have a tag for hosts in a different environment, env=prod and that would create another grouping of hosts with that specific tag. We can have the same var
# group_vars/tag_env_prod.yml app_version: 0.9
and thus when we run Ansible and target a prod server we will apply the var app_version: 0.9 instead of app_version: 1.0 since these hosts are in the group for prod servers.
Final thoughts and next steps
This is one example of how useful dynamic inventories can be there are many more groups available out of the box that can be found on Ansible's site.