Ansible 访问同一组变量不同的子主机组 [英] Ansible access same group vars different children host groups

查看:23
本文介绍了Ansible 访问同一组变量不同的子主机组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试运行一个基于父组(或父组的父组)循环的角色,该角色具有两个或多个具有一定数量主机的子组.两个子组具有相同的 group_vars,因此我尝试为每个子组分别定义 group_vars,但执行角色仅从任一子组继承 group_vars.我了解 Ansible 变量合并,但我的特定用例(想要在主机组的不同层次结构中运行相同的角色)需要在我尝试基于父组或父组在循环中运行角色时为每个子组加载 group_vars的父组.请在这方面提供帮助.

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.

库存文件:

    [test1]
    server1
    server2

    [test2]
    server3
    server4

    [test:children]
    test1
    test2

    [test0:children]
    test

/group_vars/test1.yml:

/group_vars/test1.yml:

   param1: 1234
   param2: 3456

/group_vars/test2.yml:

/group_vars/test2.yml:

   param1: 7867
   param2: 0987

role/tasks/main.yml:

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

推荐答案

更改

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

hostvars[item].param1

使用 Inventory Filegroup_vars 下面的问题

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

给出:

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

这篇关于Ansible 访问同一组变量不同的子主机组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆