Ansible extracting atributes and create new dictionary

别来无恙 提交于 2019-11-27 03:41:06

问题


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(',') }}"

回答1:


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.



来源:https://stackoverflow.com/questions/40034175/ansible-extracting-atributes-and-create-new-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!