【问题标题】:Ansible: how to iterate over a dictionariesAnsible:如何遍历字典
【发布时间】:2020-08-11 02:40:25
【问题描述】:

这是输出。

ok: [vm1.nodekite.com] => {
"containerdict": {
    "webproxy": "customer1",
    "egacustomer": "webproxy",
    "platform": "opshop-app"
}

}

如何使用循环将字典的第一个键传递给组。

  - add_host:
      name: "{{ inventory_hostname }}"
      groups: "{{ item.key }}"
    loop: "{{ containerdict }}"

我的代码出错了

`"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'key'`

我需要如下输出:

    "add_host": {
    "groups": [
        "webproxy"
    ],
    "host_name": "vm1.nodekite.com",

任何帮助将不胜感激。

【问题讨论】:

    标签: loops dictionary ansible ansible-2.x


    【解决方案1】:

    我可以这样解决

    - add_host:
        name: "{{ inventory_hostname }}"
        groups: "{{ item.key }}"
      loop: "{{ containerdict|dict2items }}"
    

    【讨论】:

    • 一个很好的解决方案;另一种可能更常见的方式是with_dict:
    • 小心!没有“字典的第一把钥匙”这样的东西。处理字典时,不能保证哪个键是第一个。
    • 谢谢你,vladimir 和 mdaniel...记住这一点!:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-04
    • 1970-01-01
    • 1970-01-01
    • 2021-06-11
    • 2017-01-18
    相关资源
    最近更新 更多