DDStackoverflow
DDStackoverflow

Reputation: 643

How to print a list of items in a multiline string output in ansible

I have a list in ansible and want to print the contents in a block, if I do loop like below:

- test_list
    - one
    - two
    - three
- debug:
    msg: "{{ item }}"
  loop: "{{ test_list }}"

it will produce output something like:

{ msg: "one" }
{ msg: "two" }
{ msg: "three" }

here I have multiple msg values, I want output like:

msg:"one
two
three"

where list items are broken won into multiple lines. Can anyone direct me to the correct path or provide a hint.

Any help would be appreciated.

Upvotes: 0

Views: 6684

Answers (1)

P....
P....

Reputation: 18371

You can achieve the desired result by the following steps :

  1. Set callback plugin to debug using the following command:

export ANSIBLE_STDOUT_CALLBACK=debug

  1. Replace loop with for loop on jinja2:

Example:

The desired output could be obtained using the following playbook:

---

- name: Sample playbook
  connection: local
  gather_facts: no
  hosts: localhost
  vars:
    test_list:
    - one
    - two
    - three

  tasks:
    - debug:
        msg: "{% for item in test_list %}{{ item + '\n'}}{% endfor %}"
         

The above playbook would result in:

PLAY [Sample playbook] ***************************************************************************************************************

TASK [Gathering Facts] ***************************************************************************************************************
ok: [localhost]

TASK [debug] *************************************************************************************************************************
ok: [localhost] => {}

MSG:

one
two
three

PLAY RECAP ***************************************************************************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0

if you need starting/ending double quotes:

msg: "\"{% for item in test_list %}{{ item + '\n'}}{% endfor %}\""

Upvotes: 4

Related Questions