How to escape the ‘#’ comment character within Ansible lineinfile module

ansibleescapingyaml

How can I escape characters in Ansible's lineinfile module?

Here's the line I want to insert on the server:

EMAIL='hi@demo.com' # Server notification email address enter only 1 address

But when I try the following, Ansible refuses to parse it due to YAML errors:

line="EMAIL='{{ email_address }}' # Server notification email address enter only 1 address"

I'm guessing it's because I have a strange combination of double quotes, single quotes, equal character and pound character.

Best Answer

The problem indeed is the # in your string - for whatever reason.

Though you can easily prevent the parsing error by using this trick:

line="EMAIL='{{ email_address }}' {{ '#' }} Server notification email address enter only 1 address"