使用Ansible set_fact从寄存器结果创建字典 [英] Using Ansible set_fact to create a dictionary from register results

查看:327
本文介绍了使用Ansible set_fact从寄存器结果创建字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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数组中的每个dict(item),每次创建一个新的dict如{Bob: "male"},并且combine() s在genders数组中该新的dict结束像这样:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆