Escape or differentiate between jinja template variables in Ansible and <service>.

送分小仙女□ 提交于 2019-12-02 07:43:29

This works fine for me:

template.j2:

foo {{ ansible_var }}
bar {{ '{{' }} other_var {{ '}}' }}
zzz {%raw%}{{ another_var }}{%endraw%}

output:

foo val
bar {{ other_var }}
zzz {{ another_var }}
brian-brazil

AlertManager is also using jinja template variables in it's own configuration file

The alertmanager uses Go templates.

See the escaping section of the Jinja docs:

key={{ '{{' }}the_var{{ '}}' }}

Will be rendered as:

key={{the_var}}

Brian-Brazil is correct. (As to be expected, google his name)

We use this technique a lot here and have .j2.j2 files in our Ansible templates that translate to .j2 files in dockers who are parsed on container start.
Here is an example more specific to your use-case. The alertmanager indeed uses Go templates but this might look confusing on first sight when mixed in a jinja template, I agree.

Say you have a file called alertmanager.yml.j2 of which the following lines are an extract.

receivers:
- name: '{{ name_of_receiver_group }}'
  opsgenie_configs:
  - api_key: 123-123-123-123-123
    send_resolved: false
    {% raw %}
    # protecting the go templates inside the raw section.
    details: { details: "{{ .CommonAnnotations.SortedPairs.Values | join \" \" }}" }
    {% endraw %}

You'll have an Ansible task that looks similar like this.

- name: copy helper scripts
  template: src={{ item }}.j2 dest={{ container_dir }}/{{ item }} mode=0755
  with_items:
    - alertmanager.yml
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!