In Ansible Jinja template, How to escape single quote which is inside the double quote

ansibleansible-templatejinja2

In Ansible role, I'm using Jinja template to create a file with fetching value from a variable.

Contents of vars file vars/main.yml from where variables are being fetched in jinja template:

Header:
 - key: a-b-c
   action: xxx
   option: '"xyz 'ZZZ' abc.de *.abc.de"'
   enabled: true

Contents of Jinja templet file templates/file.conf.j2:

{% for item in Header %}
{% if item.enabled is sameas true %}
Header {{ item.action }} {{ item.key }} {{ item.option }}
{% endif %}
{% endfor %}

Contents of tasks/main.yml file from where it is calling template module:

- name: create server.conf
  template:
   src: file.conf.j2
   dest: 'mydir/server.conf'
   owner: root
   group: root
   mode: '0644'

But I'm getting following error:

The offending line appears to be:

   action: xxx
   option: '"xyz 'ZZZ' abc.de *.abc.de"'
                  ^ here
We could be wrong, but this one looks like it might be an issue with
unbalanced quotes. If starting a value with a quote, make sure the
line ends with the same set of quotes. For instance this arbitrary
example:

    foo: "bad" "wolf"

Could be written as:

    foo: '"bad" "wolf"'

I'm expecting contents in output file mydir/server.conf should be:

Header xxx a-b-c "xyz 'ZZZ' abc.de *.abc.de"

How can I achieve this ?

Best Answer

Quoting my favorite resource Learn yaml in Y minutes

#... (in yaml)
single quotes: 'have ''one'' escape pattern'
double quotes: "have many: \", \0, \t, \u263A, \x0d\x0a == \r\n, and >more."

Since your outer quoting is single, you should write your value like this:

option: '"xyz ''ZZZ'' abc.de *.abc.de"'

Off topic extra answer: your condition in your template seems rather strange. You can simply check if your value is true and add extra security with the bool filter:

{% if item.enabled | bool %}
Related Topic