Ansible extracting atributes and create new dictionary

前端 未结 1 1096
無奈伤痛
無奈伤痛 2020-12-10 09:46

I have a json object which looks as follows:

  [
     {
        \"id\": \"subnet-1\",
        \"tags\": {
            \"Name\": \"showcase\"
        }
     }         


        
相关标签:
1条回答
  • 2020-12-10 10:09

    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.

    0 讨论(0)
提交回复
热议问题