New Line in an Ansible String

Viewed 10267

I am running this Ansible playbook:

- name: Set String
  set_fact:
    string: item
  loop: "{{some_var|filter()}}"
  register: output

- name : Create a File
  copy:
    content: "{{string}}"
    dest: Path/test.txt

some_var is a JSON that comes from a previous task.

The variable item from the loop (executed only one time) contains this:

'test test\ntest test'

So test.txt file contains this:

test test\ntest test

I would like to get this content in the test.txt file:

test test 
test test

I believe I should modify the value that the filter returns. I don't know how. Thanks

1 Answers

Use the literal block operator, |, like this:

- hosts: localhost
  gather_facts: false
  tasks:
    - name: Set String
      set_fact:
        string: |
          test test
          test test
      register: output

    - name : Create a File
      copy:
        content: "{{string}}"
        dest: test.txt

This results in:

$ cat test.txt
test test
test test

If the problem is that your variable contains the literal string \n and you want to turn that into a newline, just use the replace method:

- hosts: localhost
  gather_facts: false
  vars:
    string: 'this is\na test'

  tasks:
    - copy:
        content: "{{ string }}"
        dest: file-without-newline.txt

    - copy:
        content: "{{ string.replace('\\n', '\n') }}"
        dest: file-with-newline.txt
Related