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

问题描述

我有一个如下所示的 json 对象:

[{"id": "subnet-1",标签":{名称":展示柜"}},{"id": "subnet-2",标签":{"姓名": "qa"}}]

我想创建一个新字典,其中只有子网 ID,标签名称为Name"用作键,id"用作值,如下所示:

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

目前我有以下没有帮助的代码:

 - 名称:填充 SubnetIds设置事实:SubnetIds:{{ subnet_facts.subnets | map(attribute='tags.Name') | join(',') }}"
解决方案

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

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

{{% for s 在子网 %}"{{ s.tags.Name }}":"{{ s.id }}" {% if not loop.last %},{% endif %}{% 结束为 %}}

通过在你的剧本中查找来调用它:

- 名称:填充 SubnetIds设置事实:SubnetIds:{{ 查找('模板','subnets.j2')}}"变量:子网:{{ subnet_facts.subnets }}"

作为模板过程的最后一步 Ansible 尝试将 JSON 计算为对象,所以在这个例子中 SubnetIds 变成了一个普通的字典.

如果您为特定任务制作帮助模板,您可以在 j2 文件中使用 subnet_facts.subnets 而不是 subnets,因此无需传递额外的 varssubnets 值.

I have a json object which looks as follows:

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

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(',') }}"
解决方案

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.

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 }}"

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

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 提取属性并创建新字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 20:09