Sam
Sam

Reputation: 107

ansible filter specific line stdout_line

I have below playbook that generates stdout_lines which has multi line output.

    - name: Execute
      command: cbstats db-host:db-port -u User -p Password -b orders all
      register: count

    - name: Print
      debug:
        msg: "{{ item }}"
      with_items: "{{ count.stdout_lines }}"

Output of stdout_lines:

TASK [Print] **************************************************************************************************ok: [localhost] => {
    "msg": [
        " accepting_conns:                                       1",
        " auth_cmds:                                             0",
        " auth_errors:                                           0",
        " bytes:                                                 3756475864",
        " bytes_read:                                            2015848580",
        " bytes_subdoc_lookup_extracted:                         0",

Now I want to get only bytes from stdout_lines. Any idea how this can be achieved ?

Upvotes: 1

Views: 755

Answers (2)

Zeitounator
Zeitounator

Reputation: 44615

Your command outputs yaml. You can simply load that yaml and address the key your looking for. Using your above example data, the following task

- name: debug bytes from output
  debug:
    var: (count.stdout | from_yaml).bytes

Gives:

TASK [debug bytes from output] *********************************************************************************************************************************************************************************************************
ok: [localhost] => {
    "(count.stdout | from_yaml).bytes": "3756475864"
}

Upvotes: 2

Kevin C
Kevin C

Reputation: 5740

It's very unclear to what you exactly want, since there are 3 values with bytes in the output.
As I said in the comments, you can already solve this by adding | grep bytes to your command.

To achieve what you want by using Ansible, you can use the search_regex filter.

- debug:
    msg: "{{ count.stdout | regex_search('.*bytes:.*')  }}"

This should give:

        " bytes:                                                 3756475864",

If you want to go the extra mile, and make the value of bytes workable in Ansible as an integer, you can do the following:

- set_fact:
    the_bytes_int: >-
      {{ 
          me.stdout_lines[3].split(':')[1] |
          trim |
          replace('"','') |
          replace(',','') |
          int 
      }}

the_bytes_int is now an integer w value: 3756475864.
But again, it's easier to solve this on the command line instead of Ansible.

Upvotes: 1

Related Questions