Ansible提取属性并创建新字典 [英] Ansible extracting atributes and create new dictionary

查看:200
本文介绍了Ansible提取属性并创建新字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来如下的json对象:

I have a json object which looks as follows:

  [
     {
        "id": "subnet-1",
        "tags": {
            "Name": "showcase"
        }
     },
    {
        "id": "subnet-2",
        "tags": {
            "Name": "qa"
        }
    }
   ]

我想创建一个新的字典,其中只有subnetIds,其标签名"Name"用作键,而"id"用作值,如下所示:

and i would like to create a new dictionary with only subnetIds with tag name 'Name' used as key and 'id' used as value as follows:

   {
    "showcase": "subnet-1",
    "qa": "subnet-2",
   }

当前我有以下代码无济于事:

currently i have following code which does not help:

 - name: Populate SubnetIds
      set_fact:
        SubnetIds: "{{ subnet_facts.subnets | map(attribute='tags.Name') | join(',') }}"

推荐答案

重新整理复杂数据结构的最简单方法是template查找.
知道这一事实,即Ansible在模板化后会评估JSON数据,我们可以执行以下操作.

The easiest way to reshuffle complex data structure is a template lookup.
Knowing the fact, that Ansible evaluates JSON data after templating, we can do the following.

创建一个形成所需对象的帮助器 subnets.j2 :

Create a helper subnets.j2 that forms a desired object:

{
 {% for s in subnets %}
 "{{ s.tags.Name }}":"{{ s.id }}" {% if not loop.last %},{% endif %}
 {% endfor %}
}

通过您的剧本中的查找进行调用:

Call it via lookup in your playbook:

- name: Populate SubnetIds
  set_fact:
    SubnetIds: "{{ lookup('template', 'subnets.j2') }}"
  vars:
    subnets: "{{ subnet_facts.subnets }}"

作为模板过程的最后一步,Ansible尝试将JSON评估为对象,因此本示例中的SubnetIds成为普通的字典.

As the last step of templating procedure Ansible tries to evaluate JSON into object, so SubnetIds in this example becomes an ordinary dictionary.

如果您为特定任务设计助手模板,则可以在j2-file中使用subnet_facts.subnets代替subnets,因此无需传递带有subnets值的其他vars.

If you craft helper template for specific task, you can use subnet_facts.subnets instead of subnets inside j2-file, so there is no need to pass additional vars with subnets value.

这篇关于Ansible提取属性并创建新字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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