how to convert this data format using regex_replace in ansible

Viewed 63
- hosts: localhost
  connection: local
  gather_facts: no
  vars:
   input: |-
      404135 ARP requests sent
      6762 ARP replies sent
      6762 ARP requests received
      0 ARP requests ignored
  tasks:
    - debug: var=input

    - set_fact:
        var2: "{{ '404135 ARP requests sent' | map('regex_replace','(\\d+)ARP requests sent','ARPRequestsSent: \\1') }}"

I'm looking to manipulate and convert to JSON format using the regex replace plugin we can manipulate the data and how can we change string positions and get into the desired format of the output

{
"ARP_Requests_Sent": "404135",
"ARP_replies_sent": "6762",
"ARP_requests_received": "6762",
"ARP_requests_ignored": "0"
}

Any leads are helpful

1 Answers

The task below does the job

    - set_fact:
        var2: "{{ dict(my_keys|zip(my_vals)) }}"
      vars:
        my_lines: "{{ input.splitlines() }}"
        my_regex: '^(.*?) (.*)$'
        replace_val: '\1'
        replace_key: '\2'
        my_keys: "{{ my_lines|
                     map('regex_replace', my_regex, replace_key)|
                     list }}"
        my_vals: "{{ my_lines|
                     map('regex_replace', my_regex, replace_val)|
                     list }}"
    - debug:
        var: var2|to_nice_json

gives

  var2|to_nice_json: |-
    {
        "ARP replies sent": "6762",
        "ARP requests ignored": "0",
        "ARP requests received": "6762",
        "ARP requests sent": "404135"
    }
Related