Ansible:如何遍历字典

时间:2020-08-11 02:40:25

标签: loops dictionary ansible ansible-2.x

这是输出。

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

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我可以这样解决

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