简体   繁体   中英

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.

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 }}" 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM