6

How would one specify the multiline strings that have leading spaces on some lines?

If I define a variable as

multiline_str: |
    foo
      bar
        baz

And then write it to a file using

- name: write multiline string
  copy: content="{{ multiline_str }}" dest="/path/to/file"

Then the target file contents is

foo
bar
baz

What is the trick here?

2

4 Answers 4

11

Try this.

- name: write multiline string
  copy:
    content: "{{ multiline_str }}"
    dest: /path/to/file
2
  • That's amazing, thanks. Why does it change the behaviour so much?
    – zerkms
    Aug 28, 2015 at 4:14
  • 2
    I'm not sure, but you would often have trouble with Ansible parsing quoted key=values in a single string, and you could avoid it by passing params as an YAML collection. Thanks for providing a concise example to encourage this style of writing tasks. You can also see a discussion in the past on this topic.
    – yaegashi
    Aug 28, 2015 at 5:13
1

Had the same problem combined with local_action.

This works:

- name: write multiline string
  local_action:
    module: copy
    content: "{{ multiline_str }}"
    dest: /path/to/file
1

You may be able to use \n (newline) and \s (space) \t (tab)

1
  • I get \s also in output of lineinfile, i.e. doesn't work.
    – jan
    Dec 12, 2022 at 19:04
0

You can use the escape notation to keep the leading spaces:

multiline_str: |
  \  foo
  \    bar
  \      baz
1
  • this is visible in output if used with lineinfile, where is this working?!
    – jan
    Dec 12, 2022 at 19:03

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.