Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Using Ad-hoc Inventories in Ansible

In case you want to run ansible (or ansible-playbook) command against a set of hosts that makes sense only for one run, you can don't bother to create one-time inventory file, but simply define a comma-separated list of hosts as argument of --invertory option (or its short form that's simply -i) as follows:

ansible --inventory=myhost1,myhost2,myhost3 all -m setup -a 'filter=*name*'

(note that all in this command line stands for the target hostname)

If you have only one host to run your playbook against, your inventory string must ends with , (because otherwise Ansible would interpret it as a name of inventory file, not a hosts' list) for example:

ansible-playbook -i myhost, all -a 'uname -a'

Additionally you can dynamically generate names and then put them together as comma seperated lists. For eg:

$ echo idm-01{a,b}.{atl1,lab1,rdu1}.somedom.local | tr ' ' '\n' | paste -s -d"," -

Using this you can pass this list to ansible as an adhoc command like so:

$ ansible -i "$(echo idm-01{a,b}.{atl1,lab1,rdu1}.somedom.local | tr ' ' '\n' | paste -s -d"," -)," \
   -m shell -a uptime --forks 30 -b all

NOTE: Be sure to include a trailing , to the list.

And if you've gotten this far, if you go a little further you can do this all with a printf command like this:

$ printf "%s," idm-01{a,b}.{atl1,lab1,rdu1}.somedom.local

which becomes this with Ansible:

$ ansible -i "$(printf "%s," idm-01{a,b}.{atl1,lab1,rdu1}.somedom.local)" -m shell -a "grep ca.crl.MasterCRL.enableCRLUpdates /etc/pki/pki-tomcat/ca/CS.cfg" --forks 30 -b all

An example of this:

$ ansible -i "$(printf "%s," idm-01{a,b}.{atl1,lab1,rdu1}.somedom.local)" -m shell \
   -a "grep ca.crl.MasterCRL.enableCRLUpdates /etc/pki/pki-tomcat/ca/CS.cfg" --forks 30 -b all
idm-01a.rdu1.somedom.local | CHANGED | rc=0 >>

idm-01a.atl1.somedom.local | CHANGED | rc=0 >>

idm-01b.atl1.somedom.local | CHANGED | rc=0 >>

idm-01b.rdu1.somedom.local | CHANGED | rc=0 >>

idm-01a.lab1.somedom.local | FAILED | rc=2 >>

idm-01b.lab1.somedom.local | CHANGED | rc=0 >>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.