Ansible extracting atributes and create new dictio

2019-01-18 17:05发布

问题:

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.