# How to handle dynamic inventories with playbooks

**URL:** <https://forum.ansible.com/t/how-to-handle-dynamic-inventories-with-playbooks/18407>\
**Category:** Ansible Project\
**Created:** [June 4, 2015, 4:55pm UTC](https://forum.ansible.com/t/how-to-handle-dynamic-inventories-with-playbooks/18407 "2015-06-04T16:55:42Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Sam\_S](https://avatars.discourse-cdn.com/v4/letter/s/edb3f5/32.png) [@Sam\_S](https://forum.ansible.com/u/Sam_S)\
**Post date:** [June 4, 2015, 4:55pm UTC](https://forum.ansible.com/t/how-to-handle-dynamic-inventories-with-playbooks/18407/1 "2015-06-04T16:55:42Z")

</div>

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”  
]  
},

}

---

<div class="post-metadata">

**Author:** ![benno\_joy](https://avatars.discourse-cdn.com/v4/letter/b/73ab20/32.png) [@benno\_joy](https://forum.ansible.com/u/benno_joy)\
**Post date:** [June 4, 2015, 5:17pm UTC](https://forum.ansible.com/t/how-to-handle-dynamic-inventories-with-playbooks/18407/2 "2015-06-04T17:17:28Z")

</div>

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
