pythonregexansible

How to extract or capture the value from stdout_lines of an Ansible playbook?


I am looking for help to extract or capture the free MB value from the stdout_lines of an Ansible playbook execution and use that value as a criteria to proceed further in the playbook.

My task output is :

ok: [Host1] => {
    "changed": false,
    "invocation": {
        "module_args": {
            "commands": [
                "show file systems | inc flash:"
            ],
            "interval": 1,
            "match": "all",
            "retries": 10,
            "wait_for": null
        }
    },
    "stdout": [
        "*     1707192   (1.6 GB)        603744 (589.6 MB)      flash     rw  flash:"
    ],
    "stdout_lines": [
        [
            "*     1707192   (1.6 GB)        603744 (589.6 MB)      flash     rw  flash:"
        ]
    ]
}

I tried to use

- set_fact:
    my_var: "{{ disk_space.stdout_lines | regex_findall('\\b([0-9]{1,4}\\.\\d+)\\s+MB.*flash:$') }}"

But I always get an empty output:

ok: [Host1] => {
    "ansible_facts": {
        "my_var": []
    },
    "changed": false
}

I would like to capture 589.6 value from the output and assign it to variable to be used in my further play.


Solution

  • An other possible approach is shown in the following minimal example playbook

    ---
    - name: Cisco 'show file systems'
      hosts: localhost
      become: false
      gather_facts: false
    
      vars:
    
        disk_space:
          stdout: "*     1707192   (1.6 GB)        603744 (589.6 MB)      flash     rw  flash:"
          stdout_lines:
            - "*     1707192   (1.6 GB)        603744 (589.6 MB)      flash     rw  flash:"
    
      tasks:
    
      - name: Show stdout with data cleansing
        debug:
          msg: "{{ disk_space.stdout | regex_replace('  *', ' ') }}"
    
      - name: Show value of 4th column in KB
        debug:
          msg: "{{ ( disk_space.stdout | regex_replace('  *', ' ') | split(' ') )[4] }} KB"
    
      - name: Show value of 4th column in MB
        debug:
          msg: "{{ ( disk_space.stdout | regex_replace('  *', ' ') | split(' ') )[4] | int / 1024 }} MB"
    

    resulting into an output of

    TASK [Show stdout with data cleansing] **********************
    ok: [localhost] =>
      msg: '* 1707192 (1.6 GB) 603744 (589.6 MB) flash rw flash:'
    
    TASK [Show value of 4th column in KB] ***********************
    ok: [localhost] =>
      msg: 603744 KB
    
    TASK [Show value of 4th column in MB] ***********************
    ok: [localhost] =>
      msg: 589.59375 MB
    

    Or even

      - name: Show value of 5th column after cleansing
        debug:
          msg: "{{ ( result.stdout | regex_replace('  *', ' ') | replace('(', '') | replace(')', '') | split(' ') )[5] }}"
    

    with result of

    TASK [Show value of 5th column] ****************************
    ok: [localhost] =>
      msg: '589.6'