Karthik
Karthik

Reputation: 137

Whats the difference between the outputs when directly using the variable and hostvars in ansible

I have ansible inventory with below entries in it.

[local]
localhost port=80

[apacheweb]
kputtegowda2c.mylabserver.com

[appserver]
kputtegowda3c.mylabserver.com

Now, if I want to access the host variable "port" of the local group. I have a simple playbook to display the variable value.

- hosts: local 
  gather_facts: yes
  tasks:
  - debug: var={{ port }}

the above sample produces the output.

TASK [debug] *************
ok: [localhost] => {
"80": "VARIABLE IS NOT DEFINED!"
}

instead of directly accessing the port variable if I use hostvars[inventory_hostname].port I get the output as below.

TASK [debug] ****************
ok: [localhost] => {
"hostvars[inventory_hostname].port": "80"
}

Upvotes: 0

Views: 39

Answers (1)

mdaniel
mdaniel

Reputation: 33203

It's because you have used mustaches when you should not have; if you switch var= to msg= it will work as expected, but what you wrote is equivalent to:

  tasks:
  - debug: var=80

which is exactly what ansible runs, explaining the "80": "VARIABLE IS NOT DEFINED" text

Upvotes: 1

Related Questions