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

Ansible AWX API调用注册主机至库存时JSON解析错误求助

问题描述

我尝试通过POST请求调用AWX API,将主机IP注册到库存中。可正常运行的curl命令如下:

curl -k -s --user "awx-user:awx-pwd" -X POST -H "Content-Type: application/json" "https://awx-api-url/api/v2/inventories/host_group_id/hosts/" --data '{ "name": "172.10.100.10", "description": "test-vm" }'

我编写的Ansible Playbook相关代码如下:

- name: Register host in AWX Inventory
  uri:
    url: "https://awx-api-url/api/v2/inventories/{{ host_group_id }}/hosts/"
    method: POST
    validate_certs: false
    user: "{{ api_awx_username }}"
    password: "{{ awx_pwd_api }}"
    return_content: true
    force_basic_auth: true
    status_code: [200, 202]
    body: '{"name": {{ guest_custom_ip }}, "description": {{ vm_hostname }}; }'
    headers:
      Content-Type: application/json
    body_format: raw
  register: reg_awx_inventory

执行时出现如下错误:

"content": "{\"detail\":\"JSON parse error - Expecting value: line 1 column 1 (char 0)\\nPossible cause: trailing comma.\"}"

已排查过提示的trailing comma问题,但未发现异常,请问可能的原因是什么?

问题原因与修复方案

核心问题

你的Playbook中body字段存在两个致命语法错误:

  1. 变量未加引号:{{ guest_custom_ip }}和{{ vm_hostname }}是字符串类型值,JSON要求字符串必须用双引号包裹,直接裸写变量会导致JSON结构断裂。
  2. 多余分号:description字段末尾多了一个分号;,完全不符合JSON语法规范。

修正后的Playbook代码

- name: Register host in AWX Inventory
  uri:
    url: "https://awx-api-url/api/v2/inventories/{{ host_group_id }}/hosts/"
    method: POST
    validate_certs: false
    user: "{{ api_awx_username }}"
    password: "{{ awx_pwd_api }}"
    return_content: true
    force_basic_auth: true
    status_code: [200, 202]
    body: '{"name": "{{ guest_custom_ip }}", "description": "{{ vm_hostname }}"}'
    headers:
      Content-Type: application/json
    body_format: raw
  register: reg_awx_inventory

额外优化建议

如果不想手动处理JSON字符串的引号问题,推荐改用body_format: json,直接传入Ansible字典,让Ansible自动转换为合法JSON,这种方式更不易出错:

- name: Register host in AWX Inventory
  uri:
    url: "https://awx-api-url/api/v2/inventories/{{ host_group_id }}/hosts/"
    method: POST
    validate_certs: false
    user: "{{ api_awx_username }}"
    password: "{{ awx_pwd_api }}"
    return_content: true
    force_basic_auth: true
    status_code: [200, 202]
    body:
      name: "{{ guest_custom_ip }}"
      description: "{{ vm_hostname }}"
    headers:
      Content-Type: application/json
    body_format: json
  register: reg_awx_inventory

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 01:55:10