gpt4 book ai didi

loops - Ansible:遍历字典列表-循环vs.with_items

转载 作者:行者123 更新时间:2023-12-03 13:37:43 67 4
gpt4 key购买 nike

当尝试遍历字典列表时,使用循环vs with_items时得到不同的结果。

我试过使用loop | dict2items(结构不是字典,它告诉了我很多。嘿),并使用平坦过滤器进行循环。

以下是字典列表:

    "msg": [
{
"id": "id1",
"ip": "ip1",
"name": "name1"
},
{
"id": "id2",
"ip": "ip2",
"name": "name2"
},
{
"id": "id3",
"ip": "ip3",
"name": "name3"
},
{
"id": "id4",
"ip": "ip4",
"name": "name4"
}
]
}

这是剧本中的任务:
 - name: Add privateIp windows_instances to inventory
add_host:
name: "{{ item.ip }}"
aws_name: "{{ item.name }}"
groups: windows_instances
aws_instanceid: "{{ item.id }}"
ansible_user: "{{ windows_user }}"
ansible_password: "{{ windows_password }}"
ansible_port: 5985
ansible_connection: winrm
ansible_winrm_server_cert_validation: ignore
loop:
- "{{ list1 | flatten(levels=1) }}"

尝试运行上述代码时,出现“列表对象没有属性”错误。我尝试了不同的拼合水平,但无济于事。

然而...

如果我简单地将上面的循环替换为:
with_items:
- "{{ list1 }}"

一切正常。我在with_items>循环翻译中缺少某些内容...

最佳答案

不要在列表前放置-

在这里,您有一个词典列表,因此您无需将其放平。

这本剧本:

- hosts: localhost
gather_facts: no

vars:
demo_list:
- ip: 1.2.3.4
id: 1
name: demo1
- ip: 2.2.3.4
id: 2
name: demo2
- ip: 3.2.3.4
id: 3
name: demo3

tasks:

- name: the list
debug:
msg: "{{ demo_list }}"

- name: unflattened list
debug:
msg: "{{ item.id }} {{ item.ip }} {{ item.name }}"
loop:
"{{ demo_list }}"

- name: flattened list == unflattened list in this case
debug:
msg: "{{ item.id }} {{ item.ip }} {{ item.name }}"
loop:
"{{ demo_list | flatten(levels=1) }}"

给出以下结果:
PLAY [localhost] ***************************************************************************************

TASK [the list] ****************************************************************************************
ok: [localhost] => {
"msg": [
{
"id": 1,
"ip": "1.2.3.4",
"name": "demo1"
},
{
"id": 2,
"ip": "2.2.3.4",
"name": "demo2"
},
{
"id": 3,
"ip": "3.2.3.4",
"name": "demo3"
}
]
}

TASK [unflattened list] ********************************************************************************
ok: [localhost] => (item=None) => {
"msg": "1 1.2.3.4 demo1"
}
ok: [localhost] => (item=None) => {
"msg": "2 2.2.3.4 demo2"
}
ok: [localhost] => (item=None) => {
"msg": "3 3.2.3.4 demo3"
}

TASK [flattened list == unflattened list in this case] *************************************************
ok: [localhost] => (item=None) => {
"msg": "1 1.2.3.4 demo1"
}
ok: [localhost] => (item=None) => {
"msg": "2 2.2.3.4 demo2"
}
ok: [localhost] => (item=None) => {
"msg": "3 3.2.3.4 demo3"
}

PLAY RECAP *********************************************************************************************
localhost : ok=3 changed=0 unreachable=0 failed=0

关于loops - Ansible:遍历字典列表-循环vs.with_items,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55425311/

67 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com