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

Ansible用uri模块推送ios_facts至GitLab时大变量报错求助

解决Ansible uri模块推送ansible_net_config到GitLab时的JSON格式错误问题

你遇到的问题确实是因为ansible_net_config包含大量换行符、双引号等特殊字符,直接将其插入JSON字符串会破坏JSON的语法结构,导致GitLab API返回400 Bad Request。下面是两种简单有效的解决方案:

方案1:使用to_json过滤器(推荐)

to_json过滤器会自动将输入转换为合法的JSON值,包括添加必要的双引号、转义所有特殊字符(比如换行\n、双引号"等)。修改后的Playbook片段如下:

- name: get ios facts
  ios_facts:
    gather_subset: all
  register: ios_facts

- name: commit to gitlab
  delegate_to: localhost
  uri:
    url: http://gitlab/api/v4/projects/2/repository/commits
    method: POST
    body_format: json
    status_code: 201
    headers:
      PRIVATE-TOKEN: "xxxxxxxxxxxxxx"
      Content-Type: "application/json"
    body: |
      {
        "branch": "master",
        "commit_message": "{{ ansible_net_hostname }} update",
        "actions": [
          {
            "action": "update",
            "file_path": "conf/{{ ansible_net_hostname }}",
            "content": {{ ansible_net_config | to_json }}
          }
        ]
      }

注意这里content字段后面不需要再套双引号,因为to_json已经为字符串添加了正确的双引号并完成转义。

方案2:使用json_escape过滤器

如果你更习惯保留字段的双引号,可以用json_escape过滤器仅转义字符串内部的特殊字符,写法如下:

"content": "{{ ansible_net_config | json_escape }}"

这个过滤器会把字符串里的换行、双引号等转义成JSON可识别的格式(比如\n、\"),同时保留外层的双引号,同样能生成合法的JSON。

验证方法

在执行uri任务前,可以先添加一个debug任务检查生成的JSON是否合法:

- name: debug generated JSON body
  delegate_to: localhost
  debug:
    msg: |
      {
        "branch": "master",
        "commit_message": "{{ ansible_net_hostname }} update",
        "actions": [
          {
            "action": "update",
            "file_path": "conf/{{ ansible_net_hostname }}",
            "content": {{ ansible_net_config | to_json }}
          }
        ]
      }

查看debug输出的内容,确认没有语法错误(比如未闭合的引号、乱码的换行),再执行uri任务即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:20:36