【发布时间】:2021-03-14 17:45:51
【问题描述】:
我正在尝试从 ansible 中一项任务的输出中过滤变量。但挑战是我有变量的值,需要得到相反的变量。
我得到以下输出的任务。
- uri:
url: "https://*********/nics/nic1"
method: GET
force_basic_auth: true
headers:
cookie: "{{ login.cookies_string }}"
validate_certs: false
register: test
输出:-
ok: [192.168.84.203] => {
"allow": "GET, PUT",
"invocation": {
"module_args": {
"status_code": [
200
],
}
},
"json": {
"body": {
"interfaces": {
"@order": [
"ff7574025754b3df1647001"
],
"ff7574025754b3df1647001": {
"addresses": {
"1": "192.168.1.4/22",
"@order": [
"1"
]
},
"mtu": 1500,
"name": "default",
"source_based_routes": [],
"vlantag": 0
}
},
}
}
}
}
上面的输出有 1: 192.168.1.3/22 我需要从中检索“1”,我有 192.168.1.4/22 方便。 这基本上与我们经常做的相反。在此感谢您的帮助。
我尝试了以下任务,但它不起作用。
- name: find key
vars:
key_list: >-
{{
body.interfaces
| dict2items
| selectattr('value.addresses', 'defined')
| map(attribute='value.addresses')
| map('dict2items')
| flatten
| selectattr('value', 'eq', rl_ip)
| map(attribute='key')
}}
debug:
msg: "This is the key:{{ key_list }}"
最终输出:
TASK [find key] *********************************************************************************
ok: [192.168.84.203] => {
"msg": "This is the key: <generator object do_map at 0x7fe0a693fc80>"
}
【问题讨论】: