在 Ansible Jinja 模板中,如何转义双引号内的单引号?

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

在 Ansible 角色中,我使用 Jinja 模板创建一个文件,该文件从变量中获取值。

vars 文件的内容vars/main.yml,从那里在 jinja 模板中获取变量:

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

Jinja 模板文件的内容 templates/file.conf.j2:

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

调用模板模块的 tasks/main.yml 文件的内容:

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

但我收到以下错误:

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"'

我期望输出文件 mydir/server.conf 中的内容应该是:

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

我怎样才能做到这一点?

引用我最喜欢的资源Learn yaml in Y minutes

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

因为你的外引号是单引号,你应该这样写你的值:

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

题外话额外回答:你的模板中的条件看起来很奇怪。您可以简单地检查您的值是否为真,并使用 bool 过滤器添加额外的安全性:

{% if item.enabled | bool %}