我正在尝试根据另一个字典中的值替换字典中的一些变量,它在完全匹配时工作得很好,但只匹配前几个单词就足够了。
- debug:
msg: "{{OS_short}}"
loop: "{{store_os}}"
vars:
_dict: "{{ OS|dict2items }}"
query: "[?contains(value, '{{ item.os_full }}')].key"
OS_short: "{{ _dict|json_query(query) | join ('\n')}}"
when: item.inventory.os_full is defined
要匹配的字典:
OS:
ios:
- IOS
- ios
nxos:
- NX-OS
- nx-os
- Cisco NX-OS(tm)
#- Cisco NX-OS(tm) nxos.bla bla bla
我尝试同时使用“contains”和“starts_with”,但使用 starts_with 我得到的是 "expected one of: ['string'], received:\"array\""}"
使用包含我只得到一个空答案
ok: [localhost] => (item={'os_full': 'Cisco NX-OS(tm) nxos.x.x.x.x.bin, Software (nxos), Version x.y(z), RELEASE SOFTWARE Copyright (c) 2002-2019 by Cisco Systems, Inc. Compiled 3/5/2019 12:00:00'}) => {
"msg": ""
}
最佳答案
循环产品并搜索连接的模式。所有匹配项都将添加到新列表中。例如,给定删节数据
store_os:
- inventory:
os_full: 'Cisco NX-OS(tm) nxos.x.x.x.x.bin, ...'
下面的任务
- set_fact:
store_os_short: "{{ store_os_short|d([]) +
[{'inventory': item.0.inventory|
combine({'os_short': item.1.key})}] }}"
with_nested:
- "{{ store_os }}"
- "{{ OS|dict2items }}"
when: item.0.inventory.os_full is search(item.1.value|join('|'))
给予
store_os_short:
- inventory:
os_full: Cisco NX-OS(tm) nxos.x.x.x.x.bin, ...
os_short: nxos
关于dictionary - 在字典中搜索和替换部分匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69798373/