You may have a look into debug – Print statements during execution, Using Variables and Return Values.

Copy---
- hosts: localhost
  become: true
  gather_facts: false

  vars:
    RESULT:
      STDOUT_LINES:
        - "# name admin@shrrah.esquimail.com"
        - "zimbraIsDelegatedAdminAccount: FALSE"
        - ""
        - "# name prueba5@prueba5.com"
        - ""
        - "# name prueba7@prueba7.com"
        - "zimbraIsDelegatedAdminAccount: TRUE"
        - ""
        - "# name prueba9@prueba9.com"

  tasks:

  - name: Show STDOUT_LINES
    debug:
      msg: "{{ RESULT.STDOUT_LINES }}"

resulting into an output only of

CopyTASK [Show STDOUT_LINES] *****************
ok: [localhost] =>
  msg:
  - '# name admin@shrrah.esquimail.com'
  - 'zimbraIsDelegatedAdminAccount: FALSE'
  - ''
  - '# name prueba5@prueba5.com'
  - ''
  - '# name prueba7@prueba7.com'
  - 'zimbraIsDelegatedAdminAccount: TRUE'
  - ''
  - '# name prueba9@prueba9.com'

and if Ansible Callback plugin is configured to YAML instead of JSON.

To get lines containing certain strings only you may Loop over the list based on a Condition

Copy  - name: Show lines with TRUE only
    debug:
      msg: "{{ item }}"
    when: "'TRUE' in item"
    loop: "{{ RESULT.STDOUT_LINES }}"

resulting into an output of

CopyTASK [Show lines with TRUE only] *******************************
ok: [localhost] => (item=zimbraIsDelegatedAdminAccount: TRUE) =>
  msg: 'zimbraIsDelegatedAdminAccount: TRUE'

Further Documenation

  • Index of all Callback Plugins

If you like to have the line before included, you could use an approach like

Copy  - name: Show lines with TRUE and line before
    debug:
      msg: "{{ RESULT.STDOUT_LINES[ansible_loop.index0 - 1] }}\n{{ item }}"
    when: "'TRUE' in item"
    loop: "{{ RESULT.STDOUT_LINES }}"
    loop_control:
      extended: true
      label: "{{ ansible_loop.index0 }}"

resulting into an output of

CopyTASK [Show lines with TRUE and line before] *************************************************************************************************************************************
ok: [localhost] => (item=6) =>
  msg: |-
    # name prueba7@prueba7.com
    zimbraIsDelegatedAdminAccount: TRUE

Further Documentation

  • Extended loop variables

Since you are using the shell module, you could use also an approach like

Copy- name: DELEGATED ADMIN ACCOUNTS - check, get and send to the file domain.list
  shell: 
    cmd: /opt/zimbra/bin/zmprov -l gaaa -v zimbraIsDelegatedAdminAccount | grep -B 1 TRUE

and gather only result lines which are true an the line before.

Further Q&A

  • grep a file, but show several surrounding lines?

Regarding

... send it to the file.txt

you may have a look into

  • Ansible - Save registered variable to file
  • Ansible: Save registered variables to file
  • ...
Answer from U880D on Stack Overflow
🌐
Ansible
docs.ansible.com › projects › ansible › latest › reference_appendices › common_return_values.html
Return Values — Ansible Community Documentation
Some modules execute command line ... the normal output of these utilities. ... When stdout is returned, Ansible always provides a list of strings, each containing one item per line from the original output....
Top answer
1 of 2
4

You may have a look into debug – Print statements during execution, Using Variables and Return Values.

Copy---
- hosts: localhost
  become: true
  gather_facts: false

  vars:
    RESULT:
      STDOUT_LINES:
        - "# name admin@shrrah.esquimail.com"
        - "zimbraIsDelegatedAdminAccount: FALSE"
        - ""
        - "# name prueba5@prueba5.com"
        - ""
        - "# name prueba7@prueba7.com"
        - "zimbraIsDelegatedAdminAccount: TRUE"
        - ""
        - "# name prueba9@prueba9.com"

  tasks:

  - name: Show STDOUT_LINES
    debug:
      msg: "{{ RESULT.STDOUT_LINES }}"

resulting into an output only of

CopyTASK [Show STDOUT_LINES] *****************
ok: [localhost] =>
  msg:
  - '# name admin@shrrah.esquimail.com'
  - 'zimbraIsDelegatedAdminAccount: FALSE'
  - ''
  - '# name prueba5@prueba5.com'
  - ''
  - '# name prueba7@prueba7.com'
  - 'zimbraIsDelegatedAdminAccount: TRUE'
  - ''
  - '# name prueba9@prueba9.com'

and if Ansible Callback plugin is configured to YAML instead of JSON.

To get lines containing certain strings only you may Loop over the list based on a Condition

Copy  - name: Show lines with TRUE only
    debug:
      msg: "{{ item }}"
    when: "'TRUE' in item"
    loop: "{{ RESULT.STDOUT_LINES }}"

resulting into an output of

CopyTASK [Show lines with TRUE only] *******************************
ok: [localhost] => (item=zimbraIsDelegatedAdminAccount: TRUE) =>
  msg: 'zimbraIsDelegatedAdminAccount: TRUE'

Further Documenation

  • Index of all Callback Plugins

If you like to have the line before included, you could use an approach like

Copy  - name: Show lines with TRUE and line before
    debug:
      msg: "{{ RESULT.STDOUT_LINES[ansible_loop.index0 - 1] }}\n{{ item }}"
    when: "'TRUE' in item"
    loop: "{{ RESULT.STDOUT_LINES }}"
    loop_control:
      extended: true
      label: "{{ ansible_loop.index0 }}"

resulting into an output of

CopyTASK [Show lines with TRUE and line before] *************************************************************************************************************************************
ok: [localhost] => (item=6) =>
  msg: |-
    # name prueba7@prueba7.com
    zimbraIsDelegatedAdminAccount: TRUE

Further Documentation

  • Extended loop variables

Since you are using the shell module, you could use also an approach like

Copy- name: DELEGATED ADMIN ACCOUNTS - check, get and send to the file domain.list
  shell: 
    cmd: /opt/zimbra/bin/zmprov -l gaaa -v zimbraIsDelegatedAdminAccount | grep -B 1 TRUE

and gather only result lines which are true an the line before.

Further Q&A

  • grep a file, but show several surrounding lines?

Regarding

... send it to the file.txt

you may have a look into

  • Ansible - Save registered variable to file
  • Ansible: Save registered variables to file
  • ...
2 of 2
2

Create a dictionary

Copy    - set_fact:
        info: "{{ info|d({})|combine({_key: _val}) }}"
      loop: "{{ stdout.split('#')[1:] }}"
      vars:
        _list: "{{ item.split('\n')|map('trim') }}"
        _key: "{{ _list.0.split(' ')|last }}"
        _val: "{{ _list[1:]|select()|map('from_yaml')|combine }}"

gives

Copy  info:
    admin@shrrah.esquimail.com:
      zimbraIsDelegatedAdminAccount: false
    prueba5@prueba5.com: {}
    prueba7@prueba7.com:
      zimbraIsDelegatedAdminAccount: true
    prueba9@prueba9.com: {}

Then, the template is trivial. Either print all items

Copy    - copy:
        content: |-
          {% for k,v in info.items() %}
          {{ k }}
          {{ v|to_nice_yaml }}
          {% endfor %}
        dest: file.txt

gives

Copyshell> cat file.txt 
admin@shrrah.esquimail.com
zimbraIsDelegatedAdminAccount: false

prueba5@prueba5.com
{}

prueba7@prueba7.com
zimbraIsDelegatedAdminAccount: true

prueba9@prueba9.com
{}

, or explicitly select item(s)

Copy    - copy:
        content: |-
          prueba7@prueba7.com
          {{ info['prueba7@prueba7.com']|to_nice_yaml }}
        dest: file.txt

gives

Copyshell> cat file.txt 
prueba7@prueba7.com
zimbraIsDelegatedAdminAccount: true

Note

Additional attributes will be parsed too, e.g.

Copy    stdout_lines: [
      "# name admin@shrrah.esquimail.com",
      "zimbraIsDelegatedAdminAccount: FALSE",
      "",
      "# name prueba5@prueba5.com",
      "",
      "# name prueba7@prueba7.com",
      "zimbraIsDelegatedAdminAccount: TRUE",
      "zimbraIsDelegatedRootAccount: TRUE",
      "",
      "# name prueba9@prueba9.com"
    ]

will give

Copy  info:
    admin@shrrah.esquimail.com:
      zimbraIsDelegatedAdminAccount: false
    prueba5@prueba5.com: {}
    prueba7@prueba7.com:
      zimbraIsDelegatedAdminAccount: true
      zimbraIsDelegatedRootAccount: true
    prueba9@prueba9.com: {}

and consequently

Copyshell> cat file.txt 
prueba7@prueba7.com
zimbraIsDelegatedAdminAccount: true
zimbraIsDelegatedRootAccount: true
Discussions

ansible - Take shell cmd stdout_lines and create dict from output - DevOps Stack Exchange
I am using needrestart -b to get the following example output NEEDRESTART-VER: 3.6 NEEDRESTART-KCUR: 5.14.0-362.24.1.el9_3.0.1.x86_64 NEEDRESTART-KEXP: 5.14.0-362.24.1.el9_3.0.1.x86_64 NEEDRESTART-... More on devops.stackexchange.com
🌐 devops.stackexchange.com
How to save ansible stdout.lines to a file is in list format - Unix & Linux Stack Exchange
Need to save std.out lines to a file in delegated host using below playbook. I am able to save the data, but the saved data is in json format. I need this data as list format as like command output... More on unix.stackexchange.com
🌐 unix.stackexchange.com
linux - Filter line from Ansible stdout_lines result - Stack Overflow
I am trying to filter out a line out of Ansible stdout_lines result. The ansible playbook task I ran was the following shell argument: - name: VERIFY | Confirm that queue exists properly shell: ... More on stackoverflow.com
🌐 stackoverflow.com
Ansible: Use stdout_lines from registered variable which uses loop in shell module - Stack Overflow
Wondering if anyone here can help... I'm running Ansible 2.10.7 - The below Ansible task is responsible for checking whether or not any JBOSS deployments exist from a previous Ansible run or not. If More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 1
2

A: The value of command_results.stdout_lines is the YAML list. Nothing happens to the list when you filter it from_yaml. Use command_results.stdout instead

- set_fact:
    needrestart: "{{ command_results.stdout | from_yaml }}"

Details: Given the below file for testing

shell> cat needrestart.txt 
NEEDRESTART-VER: 3.6
NEEDRESTART-KCUR: 5.14.0-362.24.1.el9_3.0.1.x86_64
NEEDRESTART-KEXP: 5.14.0-362.24.1.el9_3.0.1.x86_64
NEEDRESTART-KSTA: 2
NEEDRESTART-UCSTA: 0

Please read it

    - command: cat needrestart.txt
      register: command_results

You can see that next to the YAML list in the attribute stdout_lines

  command_results.stdout_lines:
  - 'NEEDRESTART-VER: 3.6'
  - 'NEEDRESTART-KCUR: 5.14.0-362.24.1.el9_3.0.1.x86_64'
  - 'NEEDRESTART-KEXP: 5.14.0-362.24.1.el9_3.0.1.x86_64'
  - 'NEEDRESTART-KSTA: 2'
  - 'NEEDRESTART-UCSTA: 0'

there is also the YAML text bloc in the attribute stdout

  command_results.stdout: |-
    NEEDRESTART-VER: 3.6
    NEEDRESTART-KCUR: 5.14.0-362.24.1.el9_3.0.1.x86_64
    NEEDRESTART-KEXP: 5.14.0-362.24.1.el9_3.0.1.x86_64
    NEEDRESTART-KSTA: 2
    NEEDRESTART-UCSTA: 0

Now, you can use from_yaml to (quote):

Converts a YAML string representation into an equivalent structured Ansible variable.

For example,

  needrestart: "{{ command_results.stdout | from_yaml }}"

gives what you want

  needrestart:
    NEEDRESTART-KCUR: 5.14.0-362.24.1.el9_3.0.1.x86_64
    NEEDRESTART-KEXP: 5.14.0-362.24.1.el9_3.0.1.x86_64
    NEEDRESTART-KSTA: 2
    NEEDRESTART-UCSTA: 0
    NEEDRESTART-VER: 3.6

  needrestart['NEEDRESTART-VER']: '3.6'

Notes:

  • If you have a list only there are more options. You can convert the items to YAML dictionaries and combine them
  n3: "{{ command_results.stdout_lines | map('from_yaml') | combine }}"

gives the same result

  n3:
    NEEDRESTART-KCUR: 5.14.0-362.24.1.el9_3.0.1.x86_64
    NEEDRESTART-KEXP: 5.14.0-362.24.1.el9_3.0.1.x86_64
    NEEDRESTART-KSTA: 2
    NEEDRESTART-UCSTA: 0
    NEEDRESTART-VER: 3.6

  n3['NEEDRESTART-VER']: '3.6'
  • The next option is using the function dict on the split items. The below declaration also gives the same result
    n4: "{{ dict(command_results.stdout_lines | map('split', ':')) }}"
  • Example of a complete playbook for testing
- hosts: localhost

  vars:

    n1: "{{ command_results.stdout_lines | from_yaml }}"
    n2: "{{ command_results.stdout | from_yaml }}"
    n3: "{{ command_results.stdout_lines | map('from_yaml') | combine }}"
    n4: "{{ dict(command_results.stdout_lines | map('split', ':')) }}"

  tasks:

    - command: cat needrestart.txt
      register: command_results

    - debug:
        var: command_results.stdout_lines
    - debug:
        var: command_results.stdout

    - debug:
        var: n1
    - debug:
        var: n2
    - debug:
        var: n2['NEEDRESTART-VER']
    - debug:
        var: n3
    - debug:
        var: n3['NEEDRESTART-VER']
    - debug:
        var: n4
    - debug:
        var: n4['NEEDRESTART-VER']
🌐
Linux Hint
linuxhint.com › print-command-output-ansible
How to print command output in Ansible? – Linux Hint
--- - hosts: staging name: Check ... debug: var: command_output.stdout_lines · When executed, the uptime details are printed to the terminal as shown. ... This guide demonstrates how you can print the command’s output to standard out in Ansible....
Find elsewhere
🌐
Ansible
forum.ansible.com › archives › ansible project
Need help on formating stdout_lines output - Ansible Project - Ansible
April 29, 2020 - Hi All, Would anyone please help me formatting mountchk.result. I am able to get the required output with item.stdout_lines[0],item.stdout_lines[1],item.stdout_lines[2] but host3 has 6 entries. So, please help me in fil…
🌐
Stack Exchange
unix.stackexchange.com › questions › 668332 › how-to-get-only-stdout-lines-with-ansible-using-mail-module
linux - How to get only stdout_lines with Ansible using mail module - Unix & Linux Stack Exchange
Is there a way to accomplish getting only stdout_lines in my report? I tried with grep in the shell command but failed ... From your debug, result is a registered var from a shell task where run clamav looping on a list of paths. As described in the ansible loop documentation, the registered var is modified to contain a results list where each element is an individual result from running the module with the current iterated item (e.g.
🌐
Networkgalaxy
networkgalaxy.org › 2021 › 03 › ansible-playbook-to-display-output-of.html
Ansible-Playbook to display output of multiple show commands (using stdout_lines with Loop)
January 23, 2022 - We can make use of loops (or with_items) for submitting multiple commands, but debug output with stdout_lines does not gives the formatted result as it would give for single command. So in case of multiple commands, we can debug the output of each command separately in stdout_lines format. #Ansible...
🌐
Reddit
reddit.com › r/ansible › how do i get each stdout line into a new variable
r/ansible on Reddit: How do I get each stdout line into a new variable
September 21, 2022 -

Hi everyone

I am running a command to get a username, get very specific account attributes. that part works great. Now i need to get those attributes into variables that I can use in a different portion of the playbook. How would I do that?

Here is what I have so far:

    - name: Lookup account
      win_shell: get-aduser -Identity {{prompt_win_user_name}} -Properties * |Select-Object cn, gecos, gidNumber, unixHomeDirectory, loginShell, mail, shadowMax, uid, uidNumber
      delegate_to: DOMAINCONTROLLER
      vars:
        ansible_become: yes
        ansible_become_method: runas
        ansible_become_user: SYSTEM

when I run the above I get this back:

cn                : I get the correct info I need here
gecos             : I get the correct info I need here
gidNumber         : I get the correct info I need here
unixHomeDirectory : I get the correct info I need here
loginShell        : I get the correct info I need here
mail              : I get the correct info I need here
shadowMax         : I get the correct info I need here
uid               : I get the correct info I need here
uidNumber         : I get the correct info I need here

How Do i translate those results back into variables I can feed into a script later on in the process?

Any help would be greatly appreciated

thanks

app

🌐
Reddit
reddit.com › r/ansible › stdout_lines parsing
r/ansible on Reddit: stdout_lines parsing
January 22, 2019 -

i am trying to compare the output of a script which get the IP of a server with ansible_default_ipv4.address to make sure that the IP of the server is the same

i run ip a command in a script and then call the script module to call it.
this is the script I am calling:

/usr/bin/env bash

a_iplist_ip=$( ip a | grep -w inet | grep -v "lo$" | cut -f1 -d/ | sed "s/inet//g")

echo $a_iplist_ip

then I create a playbook as this:

---

- hosts: all

tasks:

- name: register IP

script: ip.sh

register: command_output

- set_fact:

a_iplist_ip={{ command_output.stdout_lines }}

somehoe the contents of the varilable is not the ip which is what is returned in the script above there are other things in stdout_lines so when I compare to ansible_default_ipv4.address they do not match

this confirms that the two values are not equal altough they should..

- fail:

msg: " {{ a_iplist_ip }} not equal to {{ ansible_default_ipv4.address }}

when: a_iplist_ip != ansible_default_ipv4.address

thanks

Top answer
1 of 3
3

Is there a way to do so without creating a particular playbook with debug or any other modules just by adding an option or piping the output to a grep?

I'm quite sure my above proposition in comment fulfills your expectation. The only requirement is to have a tool installed on the controller to parse json so that you can pipe Ansible output result in your shell.

For the below example, I use jq which is widely used and available in most Linux distribution repos.

The trick here is to:

  1. enable loading callbacks for ad-hoc commands.
  2. change the stdout callback plugin to use json for ad-hoc commands.

Since you seem to look for a one liner and non "destructive" solution, I used environment variables set directly on the same command line.

Long story short, typing in your shell:

CopyANSIBLE_LOAD_CALLBACK_PLUGINS=1 \
ANSIBLE_STDOUT_CALLBACK=json \
ansible localhost -a "echo toto" | jq -r ".plays[].tasks[].hosts[].stdout"

gives

toto
2 of 3
1

In my point of view, the in the original question tried approach to gather service statuses should be avoided since that example seems to be an anti-pattern for Ansible. However, there are options to fulfill the requirement for a report.

A simpler solution is either

ansible test -m systemd -a 'name=cntlm enabled=true'
test.example.com | SUCCESS => {
    "changed": false,
    "enabled": true,
    "name": "cntlm",
    "status": {
<a lot of output>
    }
}

or

Copyansible test -m shell -a 'systemctl status cntlm'
test.example.com | CHANGED | rc=0 >>
● cntlm.service - CNTLM HTTP Accelerator For NTLM Secured Proxies Authenticator
   Loaded: loaded (/usr/lib/systemd/system/cntlm.service; enabled; vendor preset: disabled)
   Active: active (running) since Thu 2022-09-01 09:00:00 CEST; 1 weeks 4 days ago
 Main PID: 234567 (cntlm)
   CGroup: /system.slice/cntlm.service
           └─234567 /usr/sbin/cntlm -c /etc/cntlm.conf -U cntlm -P /run/cntlm/cntlmd.pid

or almost the requested, after enabling callback plugin for ad hoc commands

Copyansible test -m shell -a 'systemctl status cntlm'

PLAY [Ansible Ad-Hoc] **************************************************************************************************
Monday 01 September 2022  09:00:00 +0200 (0:00:00.071)       0:00:00.071 ******

TASK [shell] ***********************************************************************************************************
changed: [test.example.com]

PLAY RECAP *************************************************************************************************************
test.example.com  : ok=1    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Monday 01 September 2022  09:00:00 +0200 (0:00:02.171)       0:00:02.243 ******
===============================================================================
shell ----------------------------------------------------------------------------------------------------------- 2.17s
Playbook run took 0 days, 0 hours, 0 minutes, 2 seconds

Config

Copy[defaults]
bin_ansible_callbacks   = True

Further Q&A

  • How can I get the output of Ansible ad-hoc command in JSON, CSV or other format?

Finally, If you are now are interested in customizing the output more, you'll probably need to start Developing plugins and creating your own Callback plugin. The source of lib/ansible/plugins/callback/default.py can be a good start.

🌐
Ansible
forum.ansible.com › archives › ansible project
Ansible register stdout_lines - Ansible Project - Ansible
December 19, 2022 - Hi team Need your support I’m looking out for put loop on register stdout _lines my stdout_lines output is this “stdout_lines”: [ “NAME READY STATUS RESTARTS AGE”, “kafka-0 1/1 Running 3 (3h1m ago) 3d”, “kafka-1 1/1 Running 3 (3h1m ago) 3d”, “kafka-zookeeper-0 1/1 Running 1 (3h2m ago) 3d” ] My playbook task is this name: List of {{release_name}} pods shell: kubectl get pods -l ‘app.kubernetes.io/component in (zookeeper,kafka)’ register: pod_output when: pod_status is succeeded debu...