Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

templates - Ansible extracting atributes and create new dictionary

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(',') }}"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...