How to handle dynamic inventories with playbooks

We pull our server inventory from a Netscaler. Servers that are binded to a specific LB group is considered active and we deploy code and/or restart services at when needed. I’ve written a Python script that outputs the hosts into JSON format for Ansible to work with. This works fine except I’m at a lost as to how I can handle multiple environments.

It could be the way I output the JSON because I query for ALL servers across the three environments we have (stagec, stagef and prod). Do I need a separate script for each environment in order to generate a “web” group for a particular environment? In my “restart.yml” file, you’ll notice I intend to run the task against the server group called “webs.”

A simple task to restart Apache on just the web servers:

restart.yml

  • name: Graceful restarts on web servers
    hosts: webs
    remote_user: deployment
    sudo_user: deployment
    gather_facts: no

roles:

  • { role: restarts }

roles/restarts/tasks/main.yml

  • name: Restart web servers
    command: sudo /usr/local/apache/bin/apachectl restart

Here’s the JSON output from my inventory script:

{
“stagec-webs”: {
“hosts”: [
“webstage3”,
“webstage4”
]
},

“stagec-perl”: {
“hosts”: [
“perlstage3”,
“perlstage4”
]
},

“stagef-webs”: {
“hosts”: [
“webstage9”,
“webstage5”,
“webstage1”,
“webstage2”
]
},

}

you could just have - hosts: all and call the playbook via --limit stagec-webs,
or let your script read a parameter from a file or environement variable which specifies the environment you want the inventory to be generated and only generate the inventory for that specific environment.

  • Benno