【问题标题】:How to match inventory list elements with vars yml list in ansible如何将库存列表元素与ansible中的vars yml列表匹配
【发布时间】:2021-03-10 05:50:56
【问题描述】:

我在库存文件中有一个清单abcd@host.com list_1=['abc','def','xyz'] 我在 vars yml 文件中有列表

list_2:

abc:
  - name: abc
  - alias: a
def:
  - name: def
  - alias: b
xyz:
  - name: xyz
  - alias: b 

我想将 list_1 的元素与 list_1 的 vars yml 的属性相匹配。比如说,当从 list_1 中选择“abc”作为第一个元素时,“abc”应该与 list_2 匹配,并且应该从 list_2 中获取名称和别名。对于整个list_1,应该以类似的方式实现。如何在ansible中做到这一点?有什么想法或建议吗?

【问题讨论】:

标签: ansible ansible-inventory


【解决方案1】:

问:"list_1 中的元素...与 list_2 匹配...获取名称和别名...对于整个 list_1"

A:list_2 是这个用例的错误结构。相反,将值放入字典中,例如

    dict_2:
      abc:
        name: abc
        alias: a
      def:
        name: def
        alias: b
      xyz:
        name: xyz
        alias: b

然后,下面的任务完成工作,例如

    - debug:
        msg: "element: {{ item }}
              name: {{ dict_2[item]['name'] }}
              alias: {{ dict_2[item]['alias']  }}"
      loop: "{{ list_1 }}"

给予

  msg: 'element: abc name: abc alias: a'
  msg: 'element: def name: def alias: b'
  msg: 'element: xyz name: xyz alias: b'

如果你不能改变数据的结构,首先转换它,例如

    - set_fact:
        dict_2: "{{ dict_2|default({})|
                    combine({item.0.key: item.1}, recursive=True) }}"
      with_subelements:
        - "{{ list_2|dict2items }}"
        - value

【讨论】:

  • 您提供的解决方案有效。谢谢。
猜你喜欢
  • 2018-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-08
  • 2019-02-24
  • 2021-07-28
  • 1970-01-01
  • 2023-02-12
相关资源
最近更新 更多