Search code examples
ansible

Show Ansible Debug MSG as a list when looping through


How can I show ansible register debug logs as a list when using debug. Right now when it loops through it returns "msg" as separate but I want a list as show below.

  - name: Show created VM's
    debug:
      msg: "Created VM - {{ item.invocation.module_args.tags.hostname }}"
    with_items: "{{ azure_nic.results }}"
    loop_control:
      label: "{{ item.invocation.module_args.tags.hostname }}"

Creates the following output:

TASK [Show created VM's] *****************************************************************************************************************************************************************************************************************************************************
task path: /home/ansible/azure_ansible/azure_playbook.yaml:120
ok: [localhost] => (item=image-201) => {
    "msg": "Created VM - image-201"
}
ok: [localhost] => (item=image-202) => {
    "msg": "Created VM - image-202"
}

But I want the output to be in a list like below:

"msg": 
 - "Created VM - image-201"
 - "Created VM - image-202"

Solution

  • Use Jinja template, e.g.

      - name: Show created VM's
        debug:
          msg: |
            {% for item in azure_nic.results %}
            - Created VM - {{ item.invocation.module_args.tags.hostname }}
            {% endfor %}
    

    Q: "Is there a way I can make ansible interpret \n as a new line and display it in the output?"

    A: Yes. There is. Use a callback that interprets the new lines, e.g.

    shell> ANSIBLE_STDOUT_CALLBACK=yaml ansible-playbook playbook.yml
    
      msg: |-
        - Created VM - image-201
        - Created VM - image-202
    

    Note: The callback community.general.yaml is deprecated and will be removed from the community.general collection version 13.0.0. Use result_format=yaml instead.


    What you see is JSON, probably the result of the default callback

    shell> ANSIBLE_STDOUT_CALLBACK=default ansible-playbook playbook.yml
    
    {
        "msg": "- Created VM - image-201\n- Created VM - image-202\n"
    }
    

    As a side note. It's possible to use Python format, e.g

        - name: Show created VM's
          debug:
            msg: "{{ '{}'.format(_msg) }}"
          vars:
            _msg: |
              {% for item in azure_nic.results %}
              - Created VM - {{ item.invocation.module_args.tags.hostname }}
              {% endfor %}