Escaping golang template in Jinja2 template

huangapple go评论102阅读模式
英文:

Escaping golang template in Jinja2 template

问题

我有以下任务:

- name: 为Splunk设置默认日志选项
  set_fact:
    log_options_base:
       tag: "{{ '{{' }}.ImageName{{ '}}' }}/{{ '{{' }}.Name{{ '}}' }}/{{ '{{' }}.ID{{ '}}' }}"
       splunk-token: "{{ splunk_token }}"
       splunk-url: "{{ splunk_url }}"
       splunk-format: "json"
       splunk-index: "my-dx"
       labels: "{{ env }}"
  when:
    - log_driver已定义
    - log_driver == 'splunk'
- name: 为Splunk设置扩展日志选项
  set_fact:
    log_options_ext: "{{ log_options_base | combine({ 'env': NODE_ENV }) }}"
  when:
     - log_options_base != ""

不幸的是,我遇到了以下问题:

在模板化字符串时出现模板错误:意外的'.'。字符串:{{.ImageName}}/{{.Name}}/{{.ID}}

条件检查'log_options_base != ""'失败。

问题肯定是与golang模板有关,但在我的情况下已经转义了。

有什么想法吗?

英文:

I have the following tasks:

- name: Set default log options for Splunk
  set_fact:
    log_options_base:
       tag: "{{ '{{' }}.ImageName{{ '}}' }}/{{ '{{' }}.Name{{ '}}' }}/{{ '{{' }}.ID{{ '}}' }}"
       splunk-token: "{{ splunk_token }}"
       splunk-url: "{{ splunk_url }}"
       splunk-format: "json"
       splunk-index: "my-dx"
       labels: "{{ env }}"
  when:
    - log_driver is defined
    - log_driver == 'splunk'
- name: Set extendend log options for Splunk
  set_fact:
    log_options_ext: "{{ log_options_base | combine({ 'env': NODE_ENV }) }}"
  when:
     - log_options_base != ""

Unfortunately I'm having the following issue:

template error while templating string: unexpected '.'. String: {{.ImageName}}/{{.Name}}/{{.ID}}\n\n

"The conditional check 'log_options_base != \"\"' failed.

The issue is definitely with the golang template but it is already escaped in my case.

Any idea?

答案1

得分: 2

when语句本身是一个Jinja2表达式,所以Ansible会尝试再次评估你的字符串。

在这种情况下,你可以使用!unsafe类型:

- name: 为Splunk设置默认日志选项
  set_fact:
    log_options_base:
       tag: !unsafe "{{.ImageName}}/{{.Name}}/{{.ID}}"

但我没有经常使用这种语法技巧,所以可能会有一些副作用,请在生产使用之前进行测试。

附注:为什么要将字典变量log_options_base与空字符串进行比较,使用log_options_base != ""?也许你想要使用is defined测试?

英文:

when statement is a Jinja2 expression itself, so Ansible tries to evaluate your string once again.

You should be good with !unsafe typing in this case:

- name: Set default log options for Splunk
  set_fact:
    log_options_base:
       tag: !unsafe "{{.ImageName}}/{{.Name}}/{{.ID}}"

But I haven't used this syntax trick much, so there may be some side effects, test it before production use.

P.S. why do you compare dict var log_options_base with empty string in log_options_base != ""? May be you want is defined test?

huangapple
  • 本文由 发表于 2017年8月8日 03:13:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/45554173.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定