Ansible access same group vars different children host groups

血红的双手。 提交于 2021-01-29 05:32:41

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/56512970/ansible-access-same-group-vars-different-children-host-groups

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!