You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ansible如何在JSON请求体中插入来自外部文件的原始转义JSON

根因说明

错误由两点导致:

  1. lookup('file')仅读取文件原始文本,不会处理Jinja2的{% raw %}语法,同时未做JSON转义就直接拼接进JSON结构,换行、引号等特殊字符直接破坏了JSON格式规范。
  2. 手动拼接JSON字符串和body_format: json特性冲突:body_format: json的设计是自动将传入的YAML字典转换为合法JSON,手动拼接JSON字符串会触发二次转义,进一步破坏格式。

解决方案

推荐方案:使用YAML字典定义body + template lookup

无需修改你现有的外部模板template1.j2内容,仅调整任务写法即可:

  1. 将uri模块的body从手动拼接的JSON字符串改为YAML字典格式,交由Ansible自动完成JSON序列化和转义。
  2. 用lookup('template')替代lookup('file'),正确解析Jinja2模板中的{% raw %}语法。

示例代码:

外部模板 template1.j2(内容不变)

{% raw %}
{
  "class": "ABC",
  "param": {{param1::integer}}
}
{% endraw %}

调整后的任务

- name: Create a template with external template
  uri:
    url: https://{{ ip }}/api/v1/templates
    method: POST
    headers:
      Authorization: "{{ token }}"
      Content-Type: application/json
    body:
      name: "{{ template_name }}"
      type: "v1"
      description: "{{ template_name }}"
      content: "template: | {{ lookup('template', 'template1.j2') }}"
    body_format: json
    timeout: 60
    status_code: 202
    validate_certs: false
  register: json_response

备选方案:手动拼接JSON时增加转义

如果有特殊需求必须手动编写JSON字符串,可通过to_json过滤器对模板内容做JSON转义后再拼接:

body: |
  {
    "name": "{{ template_name }}",
    "type": "v1",
    "description": "{{ template_name }}",
    "content": {{ ("template: | " ~ lookup('template', 'template1.j2')) | to_json }}
  }

内容的提问来源于stack exchange,提问作者Romain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 19:12:00