在 Ansible 中为 false 时添加'undefined'条目的列表创建



我有以下剧本,它基本上是有效的 -

vars:
ansible_network_os: ios
IOSserials: []
tasks:
- name: Get all facts from ios devices
register: all_facts
ios_facts:
gather_subset: hardware
- name: Create list Serials
set_fact:
IOSserials: "{{IOSserials|default([]) +  [{ 'name': all_facts.ansible_facts.ansible_net_hostname, 'IOS_serial': all_facts.ansible_facts.ansible_net_serialnum }] }}"
when: hostvars[inventory_hostname].serial !=  all_facts.ansible_facts.ansible_net_serialnum 
- name: Display list
debug:
msg: "These switches have a difference in serial number {{ ansible_play_hosts_all|map('extract', hostvars, 'IOSserials')|list }}"
run_once: true

结果如下(我在交换机中有一个"不等于"的情况):

TASK [Create list Serials] *****************************************************
skipping: [lab3650s1] => {"changed": false, "skip_reason": "Conditional result was False"}
skipping: [lab4500s1] => {"changed": false, "skip_reason": "Conditional result was False"}
ok: [lab3650s2] => 
{"ansible_facts": {"IOSserials": [{"IOS_serial": "FDO201XXXXD", "name": "lab3650s2"}]}, "changed": false}
TASK [Display list] ************************************************************
ok: [lab3650s1] => {
"msg": "These switches have a difference in serial number [Undefined, [{'name': 'lab3650s2', 'IOS_serial': 'FDO201XXXXD'}], Undefined]"
}
PLAY RECAP *********************************************************************
lab3650s1 : ok=2    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   
lab3650s2 : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
lab4500s1 : ok=1    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   

我不想要输出列表中的"未定义"条目,我还想了解为什么 Ansible 在跳过这些条目的set_fact时将其插入列表中。

map管道缺少过滤掉extract没有产生有意义值的管道的select;您可以看到它很容易重现:

- set_fact:
thingy:
one:
apple: is red
two:
banana: is yellow
three:
apple: is green
- debug:
msg: >
{{ ["one", "two", "three"] | map("extract", thingy, "banana") | list }}
- debug:
msg: >
{{ ["one", "two", "three"]
| map("extract", thingy, "banana")
| select
| list }}

最新更新