One of the ways I’ve been trying to use Ansible is to keep the same play books and abstract all the environment specific configuration into YAML files. This works well, but you run into the problem that you might have several environments in (for example) AWS. You could tag each object with the name of its environment, but then when executing the playbook, you have to take the name of the environment and use it as a “filter” to only return the environment specific objects.
One of the ways to do this is to make use of dynamic inventory, which is a method that Ansible has to allow a program to return an inventory instead of just reading it from a flat file. However, dynamic inventory (at the moment) doesn’t allow passing of any variables.
I worked out a way to get around this, basically by writing an Ansible dynamic inventory that checks the name (and arguments) of its parent process, looking for an “environment” label. Then, it returns an inventory based on this value.
How does it actually work? First we need to install the ‘psutil’ Python module:
sudo pip install psutil
Then we need to write up our dynamic inventory script (python) and include a method to get the environment as follows:
import psutil ... def get_environment(self): me = psutil.Process() parent = psutil.Process(me.ppid()) self.environment = "" for cmd in parent.cmdline(): if "environ=" in cmd: self.environment = cmd.split("=",1) break
and this would be how you would call it:
ansible-playbook -e environ=devtestproduat -i inventory.py site.yml