使用 Ansible set_fact 从寄存器结果创建字典 [英] Using Ansible set_fact to create a dictionary from register results
问题描述
在 Ansible 中,我使用 register
将任务的结果保存在变量 people
中.省略我不需要的东西,它有这样的结构:
In Ansible I've used register
to save the results of a task in the variable people
. Omitting the stuff I don't need, it has this structure:
{
"results": [
{
"item": {
"name": "Bob"
},
"stdout": "male"
},
{
"item": {
"name": "Thelma"
},
"stdout": "female"
}
]
}
我想使用后续的 set_fact
任务来生成一个带有字典的新变量,如下所示:
I'd like to use a subsequent set_fact
task to generate a new variable with a dictionary like this:
{
"Bob": "male",
"Thelma": "female"
}
我想这可能是可能的,但到目前为止我还没有走运.
I guess this might be possible but I'm going round in circles with no luck so far.
推荐答案
我想我最终做到了.
任务是这样的:
- name: Populate genders
set_fact:
genders: "{{ genders|default({}) | combine( {item.item.name: item.stdout} ) }}"
with_items: "{{ people.results }}"
它循环遍历 people.results
数组中的每个 dicts (item
),每次创建一个新的 dict,如 {Bob: "male"}
和 combine()
是 genders
数组中的新字典,结果如下:
It loops through each of the dicts (item
) in the people.results
array, each time creating a new dict like {Bob: "male"}
, and combine()
s that new dict in the genders
array, which ends up like:
{
"Bob": "male",
"Thelma": "female"
}
它假定键(在本例中为 name
)将是唯一的.
It assumes the keys (the name
in this case) will be unique.
然后我意识到我实际上想要一个字典列表,因为使用 with_items
循环似乎更容易:
I then realised I actually wanted a list of dictionaries, as it seems much easier to loop through using with_items
:
- name: Populate genders
set_fact:
genders: "{{ genders|default([]) + [ {'name': item.item.name, 'gender': item.stdout} ] }}"
with_items: "{{ people.results }}"
这会不断将现有列表与包含单个字典的列表组合在一起.我们最终得到一个 genders
数组,如下所示:
This keeps combining the existing list with a list containing a single dict. We end up with a genders
array like this:
[
{'name': 'Bob', 'gender': 'male'},
{'name': 'Thelma', 'gender': 'female'}
]
这篇关于使用 Ansible set_fact 从寄存器结果创建字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!