Search code examples
ansibleansible-inventory

Accessing group variable in template file of role belonging to another group


Inventory file:

[1]
IP

[2]
IP

[1:vars]
foo=test

How can I access variable foo in role which will be executed on group [2]?


Solution

  • Firstly, you cannot name host groups with a single digit, so fix the inventory file:

    [group1]
    IP1
    
    [group2]
    IP2
    
    [group1:vars]
    foo=test
    

    Then when running against group2, to access the variable defined for group1, use the following construct:

    - debug:
        var: hostvars[groups['group1'][0]]['foo']
    

    Generally, I would try to avoid such references though.