Ansible debug msg in a specific format

909 views Asked by At

I have the below script, which does a ping.

    - name: Running WAN connectivty checks on WAN-01A
      cisco.ios.ios_ping:
         vrf: '{{item.vrf}}'
         dest: '{{item.destination}}'
         source: '{{item.source}}'
         count: '{{item.count}}'
         size: '{{item.size}}'
      loop: "{{ wan01avar }}"
      when: inventory_hostname ==  'WAN-01A'
      register: wan01a
      tags:
        - never
        - WAN

    - name: WAN connectivty results on WAN-01A
      debug: msg="{{ wan01a.results | json_query(jmesquery)}}"
      vars:
         jmesquery: "[*].{Source: item.source, Destination: item.destination,packetloss: packet_loss}"
      when: inventory_hostname ==  'WAN-01A'
      tags:
        - never
        - WAN


The script uses the following variables:

wan01avar:
  - vrf: 'default'
    source: 'Bundle-Ether400.682'
    destination: '10.27.251.194'
    count: '10'
    size: '1500'


  - vrf: 'CLOUD_DCI'
    source: 'Bundle-Ether400.682'
    destination: '10.27.251.194'
    count: '9'
    size: '1400'

I am using json_query (jmesquery) and printing the below output:

TASK [wan : Output from WAN-01A] *******************************************
ok: [WAN-01A] => {
    "msg": [
        {
            "Destination": "10.27.251.194",
            "Source": "Bundle-Ether400.682",
            "packetloss": "0%"
        },
        {
            "Destination": "10.27.251.194",
            "Source": "Bundle-Ether400.682",
            "packetloss": "0%"
        }
    ]
}

What I want to achieve is the following output instead:

TASK [wan : Output from WAN-01A] *******************************************
ok: [WAN-01A] => {
    "msg": [
        {
"Destination": "10.27.251.194", "Source": "Bundle-Ether400.682", "packetloss": "0%"
"Destination": "10.27.251.194","Source": "Bundle-Ether400.682","packetloss": "0%"
        }
    ]
}

how to achieve the output above? A nice one line for each section

1

There are 1 answers

0
aalbagarcia On BEST ANSWER

I have created this simple playbook that might help you get what you need:

---
- name: Format message
  hosts: localhost
  vars:
    wan01a:
      - vrf: 'default'
        source: 'Bundle-Ether400.682'
        destination: '10.27.251.194'
        count: '10'
        size: '1500'
      - vrf: 'CLOUD_DCI'
        source: 'Bundle-Ether400.682'
        destination: '10.27.251.194'
        count: '9'
        size: '1400'
  tasks:
    - debug:
        msg: "{{ wan01a }}"

    - debug:
        msg: "Destination: {{ item['destination'] }}, Source: {{ item['source'] }}, count: {{ item['count'] }}"
      with_items: "{{ wan01a }}"

    - debug:
        msg: >
          {%- for item in wan01a %}
          Destination: {{ item['destination'] }}, Source: {{ item['source'] }}, count: {{ item['count'] }}
          {%- endfor %}

I've printed the message in three different ways. The last one is the closest to what you wanted to achieve.