ansible (2.5.0) 字典搜索列表(哈希)生成器表达式
ansible (2.5.0) search list of dictionaries (hashses) generator expression
我有一个字典列表,我想要一个特定的值。队列端口的 node_port.
[
{
"name": "queue-port",
"node_port": 32614,
"port": 5672,
"protocol": "TCP",
"target_port": 5672
},
{
"name": "cluster-port",
"node_port": 31018,
"port": 4369,
"protocol": "TCP",
"target_port": 4369
},
{
"name": "dist-port",
"node_port": 30732,
"port": 25672,
"protocol": "TCP",
"target_port": 25672
}
]
我知道如何在 python 中使用 lambda 或生成器表达式执行此操作,当涉及到 ansible 完成相同的结果时,我被卡住了。它是从 openshift_raw 模块生成的一个对象,所以我可能对 python/ansible 太菜鸟了,所以使它变得比必要的更复杂。
register: opnshft_raw
{{ opnshft_raw.results[0]['result']['spec']['ports'] }}
是我要搜索的列表。
>>> (item for item in results if item["name"] == "queue-port").next()['node_port']
32614
需要用set_fact模块循环解析list变量,满足条件时设置一个新的变量为该值
示例:
tasks:
- name: parse and find value
set_fact:
my_variable: "{{ item.node_port }}"
when: item.name == "queue-port"
with_items: "{{ your_list_variable_name }}"
- name: print results
debug:
var: my_variable
我有一个字典列表,我想要一个特定的值。队列端口的 node_port.
[
{
"name": "queue-port",
"node_port": 32614,
"port": 5672,
"protocol": "TCP",
"target_port": 5672
},
{
"name": "cluster-port",
"node_port": 31018,
"port": 4369,
"protocol": "TCP",
"target_port": 4369
},
{
"name": "dist-port",
"node_port": 30732,
"port": 25672,
"protocol": "TCP",
"target_port": 25672
}
]
我知道如何在 python 中使用 lambda 或生成器表达式执行此操作,当涉及到 ansible 完成相同的结果时,我被卡住了。它是从 openshift_raw 模块生成的一个对象,所以我可能对 python/ansible 太菜鸟了,所以使它变得比必要的更复杂。
register: opnshft_raw
{{ opnshft_raw.results[0]['result']['spec']['ports'] }}
是我要搜索的列表。
>>> (item for item in results if item["name"] == "queue-port").next()['node_port']
32614
需要用set_fact模块循环解析list变量,满足条件时设置一个新的变量为该值
示例:
tasks:
- name: parse and find value
set_fact:
my_variable: "{{ item.node_port }}"
when: item.name == "queue-port"
with_items: "{{ your_list_variable_name }}"
- name: print results
debug:
var: my_variable