stringansiblemultilineansible-facts

How to make Ansible 'debug' module print a string containing many '\n' as a multiline string?


One of my Ansible variable is defined as

- name: prepare the multiline message
  set_fact: 
    report_string: |
      THIS IS A TEST

      state of the machines
      ---------------------

      state of machines of level1: {{ machineslv1_state }}

      state of machines of level2: {{ machineslv2_state }}

      ...


      connection errors
      ---------------------

      connection errors of machines of level1: {{ machineslv1_errconn }}

      connection errors of machines of level2: {{ machineslv2_errconn }}

      ...
      ...
      ...

      END OF THE MESSAGE

I would like to print the value of this variable during the playbook execution, so I did this task

- name: show the report_string
  debug:
    msg: |
     "{{ report_string }}"

However, Ansible prints this as a single-line string having lines joined by '\n'.

Is it possible to print it as multiline string?


Solution

  • Keep in mind that the debug module is just that...a module for printing information to help you debug things. It's not meant to produce nicely formatted output (write your data to a file using the template module if you want that).

    That said, you can probably get something closer to what you want if you print a list of lines by splitting the data on \n:

    - hosts: localhost
      gather_facts: false
      tasks:
      - name: prepare the multiline message
        set_fact:
          report_string: |
            THIS IS A TEST
    
            state of the machines
            ---------------------
    
            state of machines of level1: ...
            state of machines of level2: ...
    
            END OF THE MESSAGE
    
      - debug:
          msg: "{{ report_string.splitlines() }}"
    

    This produces:

    TASK [debug] ********************************************************************************************
    ok: [localhost] => {
        "msg": [
            "THIS IS A TEST",
            "",
            "state of the machines",
            "---------------------",
            "",
            "state of machines of level1: ...",
            "state of machines of level2: ...",
            "",
            "END OF THE MESSAGE"
        ]
    }