首页 > 解决方案 > 使用 ansible 编辑 j2 模板

问题描述

我有一个供应商 Ansible 剧本给我们,我需要在 j2 模板中添加一个新行并为我们的 env 调整剧本,我需要使用一行 -> 保留天数编辑模板:{{ xyz }}

这是原始模板的样子:

#cat cluster.j2
apiVersion: v1
metadata:
  name: cluster
  cluster_name: {{ my_name }}
data:
  new_image: |+
      baseImage: {{ FROM_repo }}

这是我的 Ansible 剧本来添加这一行。

---
- name: mydata
  hosts: localhost
  tasks:
   - name: edit files
     lineinfile:
       dest: cluster.j2
       line: " retention_days: {{ xyz }}"
       insertafter: 'new_image'

我的最终结果,即;我的 j2 模板文件应该有这样的确切字符串

保留天数:{{ xyz }}

final - 文件应该是这样的 ->

#cat cluster.j2
apiVersion: v1
metadata:
  name: cluster
  cluster_name: {{ my_name }}
data:
  new_image: |+
      retention_days: {{ xyz }}
      baseImage: {{ FROM_repo }}

我不希望 {{ xyz }} 被 Ansible 视为变量,而是将其视为一个字符串并将它们添加到那里......我怎样才能逃避 {{ 和 }} 请让我知道。

现在.,我得到一个错误:xyz is undefined..

MSG:

***The task includes an option with an undefined variable. The error was: 'xyz' is undefined***

标签: ansiblejinja2ansible-template

解决方案


文档中所述,您可以使用{% raw %}转义块中的元素,或添加额外的花括号。

例如:

---
- name: mydata
  hosts: localhost
  tasks:
   - name: edit files
     lineinfile:
       dest: cluster.j2
       line: " retention_days: {% raw %}{{ xyz }}{% endraw %}"
       # or
       # line: " retention_days: {{ '{{ xyz }}' }}" 
       insertafter: 'new_image'

推荐阅读