How to do multiline shell script in Ansible?


right now I am using a shell script in ansible that would be much more readable if it was on multiple lines

Just not sure how to allow multiline script in Ansible shell module


Ansible uses YAML syntax in its playbooks. YAML has a number of block operators:

  • The > is a folding block operator. That is, it joins multiple lines together by spaces. The following syntax:

    Would assign the value This text has multiple lines\n to key.
  • The | character is a literal block operator. This is probably what you want for multi-line shell scripts. The following syntax:

    Would assign the value This text\nhas multiple\nlines\n to key.

You can use this for multiline shell scripts like this:

There is one caveat: Ansible does some janky manipulation of arguments to the shell command, so while the above will generally work as expected, the following won’t:

Ansible will actually render that text with leading spaces, which means the shell will never find the string EOF at the beginning of a line. You can avoid Ansible’s unhelpful heuristics by using the cmd parameter like this:

Leave a Reply