Ring Ring - 1 month ago 20
YAML Question

Ansible echo into file

I'm struggling with some Ansible/YAML syntax here. How do I echo multiple lines (in append mode) in to a file? I also can't use the copy module (with the content arg) because it has to be appended.

This code:

- name: Write backup script for each app
shell: echo | '
line one
line two
line three
' >> /manager/backup.sh


errors out with nonsensical:

"stderr": "/bin/sh: line one line two line three : command not found"


I'm using the pipe because I think it's how you tell Ansible you want multiple lines (with preserved formatting), but maybe it's being used as a shell pipe.

Answer

You want something like this:

- name: Write backup script for each app
  shell: |
    echo 'line one
    line two
    line three' >> /manager/backup.sh

or explicitly specifying newline with printf:

- name: Write backup script for each app
  shell: printf 'line one\n
    line two\n
    line three\n' >> /manager/backup.sh

The error message you get makes perfect sense: you tried to pipe (|) the output of the echo command to the line one line two line three command. As shell does not find the latter, it reports the command not existing. It's the same if you executed the following directly in shell:

echo | "line one line two line three" >> /manager/backup.sh

YAML uses | to indicate multi-line value, but when used directly after the key, not anywhere in the value field.

Comments