CR7
CR7

Reputation: 58

Ansible user defined inventory variable calling

Hello My inventory is something like this

host1:
  machine1 
host2:
  machine1 var=x
  machine2 var=y

My playbook is something like this and doesn't work

---
- hosts: host2
  name: gather facts from host2
  tasks: []
- hosts: host1
  tasks:
    - name: Run command
      command: echo"{{ hostvars['host2']['var'] }}"


   #Also, I tried this "{{ hostvars.host2.var }}"

I need to pass x and y in the second play and Ansible gives undefined variable. How can I do this?

Upvotes: 2

Views: 147

Answers (1)

mdaniel
mdaniel

Reputation: 33203

Ironically we had this exact same question yesterday:

It's because host1 is not a host it's a group and thus will not be in hostvars. If you just ask for {{ var }} it will have the value x when that task evaluates on machine1 and y on machine2. You can, of course, ask for the value of machine1's var while on machine2 via {{ hostvars["machine1"].var }} just as you tried

Upvotes: 2

Related Questions