Search code examples
ansibleansible-inventory

Ansible access same group vars different children host groups


I am trying to run a role which loops based on a parent group (or parent of parent group) with two or more child groups with certain number of hosts. The two child groups have same group_vars so I tried to define the group_vars separately for each child group but executing the role only inherits group_vars from either of the child group. I understand about the Ansible variable merging but my specific use case (want to run same role at different hierarchies of host groups) needs to load the group_vars for each child group when I try to run the role in loop based on the parent group or parent of parent group. Please help in this regard.

Inventory File:

    [test1]
    server1
    server2

    [test2]
    server3
    server4

    [test:children]
    test1
    test2

    [test0:children]
    test

/group_vars/test1.yml:

   param1: 1234
   param2: 3456

/group_vars/test2.yml:

   param1: 7867
   param2: 0987

role/tasks/main.yml:

- uri:
    url: http://{{ item }}:{{ hostvars[groups['test'][0]]['param1'] }}/{{ hostvars[groups['test'][0]]['param2'] }}/
    return_content: yes 
  register: response
  ignore_errors: true
  loop: "{{ groups['test'] }}"

Solution

  • Change

    hostvars[groups['test'][0]]['param1']
    

    to

    hostvars[item].param1
    

    With the Inventory File and group_vars from the question the play below

    - hosts: localhost
      tasks:
        - debug:
            msg: "{{ item }}: {{ hostvars[item].param1 }} {{ hostvars[item].param2 }}"
          loop: "{{ groups['test'] }}"
    

    gives:

    PLAY [localhost] *****************************************************
    
    TASK [debug] *********************************************************
    ok: [localhost] => (item=server1) => {
        "msg": "server1: 1234 3456"
    }
    ok: [localhost] => (item=server2) => {
        "msg": "server2: 1234 3456"
    }
    ok: [localhost] => (item=server3) => {
        "msg": "server3: 7867 0987"
    }
    ok: [localhost] => (item=server4) => {
        "msg": "server4: 7867 0987"
    }
    
    PLAY RECAP *************************************************************************
    localhost                  : ok=1    changed=0    unreachable=0    failed=0   
    

    Next option is the play below which prints the same messages.

    - hosts: test
      tasks:
        - debug:
            msg: "{{ inventory_hostname }}: {{ param1 }} {{ param2 }}"