Ansible: How to use inventory variables in ad-hoc commands

Viewed 7343

I want to run an ad-hoc command over a host file, in the host file I have defined a variable for each host, How can I use that variable while executing an ad-hoc command.

For example:

ansible -i /home/bob/hosts_file -m shell -a "$VAR/project run"

I have defined the $VAR for each host in "hosts_file", the $VAR is different for every host in the inventory file. How can I use that variable in my ad-hoc command replacing for each host when executing.

2 Answers

With Ansible ad-hoc commands ansible can make use of all the same variables regardless.

Examples

#1. group_names
$ ansible -i inventory/lab -m debug -a "var=group_names" all | head -10
es-master-01.mydom.local | SUCCESS => {
    "group_names": [
        "elasticsearch",
        "engineering",
        "lab",
        "lab-es-master"
    ]
}

Here I'm querying the servers in an inventory to find out what groups the server is assigned to in the inventory file. This variable group_names shows this from my inventory file.

#2. inventory_hostnames

Here's another example where I'm using the variable inventory_hostnames and accessing it using Jinja notation:

$ ansible -i inventory/nyc1 -l ocp-app* all -c local -m shell -a "echo {{ inventory_hostname }}"
ocp-app-01e.nyc1.dom.us | CHANGED | rc=0 >>
ocp-app-01e.nyc1.dom.us

ocp-app-01c.nyc1.dom.us | CHANGED | rc=0 >>
ocp-app-01c.nyc1.dom.us

ocp-app-01d.nyc1.dom.us | CHANGED | rc=0 >>
ocp-app-01d.nyc1.dom.us

ocp-app-01a.nyc1.dom.us | CHANGED | rc=0 >>
ocp-app-01a.nyc1.dom.us

ocp-app-01b.nyc1.dom.us | CHANGED | rc=0 >>
ocp-app-01b.nyc1.dom.us

ocp-app-01f.nyc1.dom.us | CHANGED | rc=0 >>
ocp-app-01f.nyc1.dom.us
Related