Sergiy M
Sergiy M

Reputation: 3

How to use Ansible inventory variables in templates

Is that even possible to refer to a group variable while running a play for other group?

I have a specific case like that:

/etc/ansible/hosts

[group1]
server1.test.org

[group2]
server2.test.com

[group2:vars]
foo=bar

Running a play for group1

- name: test variables...
  hosts: group1
  gather_facts: no
  tasks:
       - debug: msg="foo={{ groups[group2].foo }}" 

It is not working, I have tried other syntax variants without success.

Upvotes: 0

Views: 4800

Answers (1)

Petro026
Petro026

Reputation: 1309

The groups don't actually have variables defined for them when the inventory gets initialized. The hosts get a copy of what's defined for group variables. So to do what you want, you need to read from a host. Try this:

- name: test variables...
  hosts: group1
  gather_facts: no
  tasks:
  - debug: msg="foo={{ hostvars[groups['group2'][0]].foo }}" 

Upvotes: 1

Related Questions