【问题标题】:How to replace opening and closing curly braces {{ }} with pattern {{ '{{' }} / {{ '}}' }} in Python/Ansible如何在 Python/Ansible 中用模式 {{ '{{' }} / {{ '}}' }} 替换大括号 {{ }}
【发布时间】:2021-08-05 15:37:50
【问题描述】:

我们正在使用 Ansible 对导出为 JSON 文件的 grafana 仪表板进行模板化。仪表板 JSON 可能在 Json 的许多地方都有仪表板变量引用,例如 {{ region }}、{{ state }} 等。运行模板代码时,我们得到未为“区域”、“状态”变量定义的变量。我们希望 ansible 忽略这些变量并像花括号一样打印。我们遇到了两种解决方案

  1. 使用 {% raw %} {% endraw %}
  2. 在 json 中将 {{ 替换为 {{ '{{' }} 并将 }} 替换为 {{ '}}' }}

我们尝试了#1,但没有成功。我们的 jinja2 模板如下所示

{
  "dashboard": {{ item.json | indent(width=2) | trim }} ,{{ "\n" }}
  {%- if 'folder_uid' in item %}
  "folderUid": "{{ item.folder_uid }}",{{ "\n" }}
  {%- endif %}
  "overwrite": true
}

在上面的 item.json 变量中包含仪表盘 json 数据

我们尝试了以下所有方法

  • {% 原始 %} {{ item.json |缩进(宽度=2) |修剪 }} {% endraw %}
  • "{% raw %} {{ item.json | indent(width=2) | trim }} {% endraw %}"
  • {% 原始 %} '{{ item.json |缩进(宽度=2) |修剪 }}' {% endraw %}
  • {% raw %} "{{ item.json | indent(width=2) | trim }}" {% endraw %}

没有任何效果。 ansible 仍然尝试模板化 json 内容

所以,我们正在尝试#2。谁能帮助我们如何将 {{ 替换为 {{ '{{' }} 并将 }} 替换为 {{ '}}' }} 模式?问题是我们不能做简单的文本替换,因为替换 {{ 也会引入 }}。

【问题讨论】:

  • 没有MCVE,没有人可以帮助你,但是item 的存在让我怀疑你正在使用with_items:,因为ansible 会尝试尽可能解决 jinja2 的胡须问题,而循环使得这更难推理

标签: python ansible jinja2


【解决方案1】:

我认为您可以通过在 Ansible 模板中包含 JSON 属性来避免扩展花括号。例如,给定 “以 JSON 文件导出的 Grafana 仪表盘”

shell> cat test-152.json
{
  "dashboard": "region {{ region }} state {{ state }}"
}

在字典中包含 JSON 数据,例如

    - set_fact:
        content: "{{ lookup('file', 'test-152.json') }}"

创建字典内容

  content:
    dashboard: region {{ region }} state {{ state }}

接下来创建一个 Ansible 模板并引用 “仪表板 JSON (that) 可能有仪表板变量引用,例如 {{ region }}, {{ state }})”

shell> cat test-152.txt.j2
# Grafana dashboard created by Ansible
# Created {{ '%Y-%m-%d' | strftime }}
{{ content.dashboard }}

Ansible 任务

    - template:
        src: test-152.txt.j2
        dest: test-152.txt

创建文件

shell> cat test-152.txt
# Grafana dashboard created by Ansible
# Created 2021-08-05
region {{ region }} state {{ state }}

根据您的需要调整模板。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    • 2016-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多