Debug print list nicely

maybe a stupid question, but how to print nicely a list

Ideally, i would like to print :

  • all
  • first
  • second

But i’m not able to do it, please see 4 examples made :

  • hosts: localhost
    gather_facts: no
    vars:
    found:

  • all

  • first

  • second
    tasks:

  • name: test1
    debug:
    var: found

  • name: test2
    debug:
    var: item
    loop: “{{ found }}”

  • name: test3
    debug:
    msg: “{{ found | to_nice_yaml }}”

  • name: test4
    debug:
    msg: “{{ found | to_nice_yaml | indent(2, False) }}”

Result :

PLAY [localhost] *******************************************************************************************************************

TASK [test1] ***********************************************************************************************************************
ok: [localhost] => {
“found”: [
“all”,
“first”,
“second”
]
}

TASK [test2] ***********************************************************************************************************************
ok: [localhost] => (item=all) => {
“ansible_loop_var”: “item”,
“item”: “all”
}
ok: [localhost] => (item=first) => {
“ansible_loop_var”: “item”,
“item”: “first”
}
ok: [localhost] => (item=second) => {
“ansible_loop_var”: “item”,
“item”: “second”
}

TASK [test3] ***********************************************************************************************************************
ok: [localhost] => {
“msg”: “- all\n- first\n- second\n”
}

TASK [test4] ***********************************************************************************************************************
ok: [localhost] => {
“msg”: “- all\n - first\n - second\n”
}

The test3 is the nearest solution but ‘\n’ is not interpreted by the debug …

It's possible to *split* the lines. For example

  - debug:
      msg: "{{ msg.split('\n') }}"
    vars:
      msg: "{{ found | to_nice_yaml }}"

Cheers,

  -vlado

Tkx vlado for the tips

But it’s not 'perfect : it’s create a empty line :

ok: [localhost] => {
“msg”: [
“- all”,
“- first”,
“- second”,
“”
]
}

Empty line has been created because of the trailing '\n'. Get rid of it if
you want to.

    - debug:
        msg: "{{ msg[:-1].split('\n') }}"
      vars:
        msg: "{{ found | to_nice_yaml }}"

Cheers,

  -vlado

One alternative to trying to format things in the task - you can set the stdout_callback value to yaml in ansible.cfg. It will take your tasks and make it more human-readable.

Got the tip from geerlingguy’s blog: https://jeffgeerling.com/blog/2018/use-ansibles-yaml-callback-plugin-better-cli-experience

I prefer to set the stdout callback plugin to debug, though yaml is also pretty good. That should make the output more readable.

In the config:
[defaults]
stdout_callback = debug

As an environment variable:
ANSIBLE_STDOUT_CALLBACK=debug