Xenia Ioannidou
Xenia Ioannidou

Reputation: 87

Combining the output of multiple loops in Ansible

I am working with Ansible and in my playbook I am running the following task, in which I have multiple loops so as to retrieve different tags from a specific xml:

- name: Retrieve multiple xml tags valuei
  xml:
    xmlstring: "{{ item.string }}"
    xpath: "{{ item.path }}"
    content: text
  loop:
    - { path: "/rpc-reply/vlan-instance-information/vlan-instance-group/vlan-member/vlan-tag", string: "{{topology.xml}}" }
    - { path: "/rpc-reply/vlan-instance-information/vlan-instance-group/vlan-member/vlan-member-interface", string: "{{topology.xml}}" }
  register: tags_value

- debug:
    msg: "{{ item.matches }}"
  loop: "{{ tags_value.results }}"
  loop_control:
    label: "{{ item.matches }}"

So I am getting the following:

ok: [sss-sd1-02] => (item=[{u'vlan-member-interface': u'et-0/0/0.0*'}, {u'vlan-member-interface': u'et-0/0/1.0*'}]) => {
"msg": [
    {
        "vlan-member-interface": "et-0/0/0.0*"
    }, 
    {
        "vlan-member-interface": "et-0/0/1.0*"
    }
]

}

and this

ok: [sss-sd1-02] => (item=[{u'vlan-tag': u'4071'}, {u'vlan-tag': u'4072'}]) => {
"msg": [
    {
        "vlan-tag": "4071"
    }, 
    {
        "vlan-tag": "4072"
    }
]

}

Is there a way to group "vlan-member-interface": "et-0/0/0.0*" and "vlan-tag": "4071" in 1 result , either in this task or in a different one ? And also is there a way to create a list with only {4071, 4072} ? Because i cannot handle it as it is right now !!!

Upvotes: 2

Views: 1124

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68004

The question can be simplified. Let's have the data

    results:
      - [A: a1, A: a2]
      - [B: b1, B: b2]

Q1: "Group "A:a1" and "B:b1" in 1 result"

A: Use zip function. For example

    - set_fact:
        my_groups: "{{ results.0|zip(results.1)|list }}"
    - debug:
        var: my_groups

gives

    "my_groups": [
        [
            {
                "A": "a1"
            }, 
            {
                "B": "b1"
            }
        ], 
        [
            {
                "A": "a2"
            }, 
            {
                "B": "b2"
            }
        ]
    ]
}

Q2: "Create a list with only [b1, b2]"

A: Use dict2items and json_query functions. For example

   - set_fact:
        my_values: "{{ results.1|map('dict2items')|list|json_query('[].value') }}"
    - debug:
        var: my_values

gives

    "my_values": [
        "b1", 
        "b2"
    ]


Question 1 is substitution of: Group "vlan-member-interface": "et-0/0/0.0*" and "vlan-tag": "4071" in 1 result
Question 2 is substitution of: Create a list with only {4071, 4072}
Variable results is substitution of tags_value.results

Upvotes: 1

Related Questions