Ansible传递变量到API请求时出现JSON序列化错误
Ansible URI模块JSON序列化错误解决办法
问题场景
用户定义了如下Ansible列表变量array1:
- name: List set_fact: array1: - param1: "efg" param2: "abdc" param3: "nsdadsd" param4: "dadas dsadasda"
变量结构为:
"array1": [ { "param1": "efg", "param2": "abdc", "param3": "nsdadsd", "param4": "dadas dsadasda" } ]
随后尝试将该变量放入URI模块的API请求Body中,编写的任务如下:
- name: API call delegate_to: localhost uri: url: https://some_url/abcd/ validate_certs: false method: POST body_format: json headers: X-some-APIKey: "{{api_token}}" body: '{ "{{array1}}" }' register: api_output
错误信息
执行任务时触发如下报错:
"msg": "Unable to pass options to module, they must be JSON serializable: Object of type 'set' is not JSON serializable"
根因分析
- 缺少必要请求头:API请求未携带
Content-Type: application/json头,导致模块处理JSON数据时出现序列化异常 - 数据格式不匹配:目标API不接受数组格式的请求Body,而
array1是包含单个字典的列表结构 - Body写法错误:在设置
body_format: json的情况下,无需手动拼接JSON字符串,直接传递Python数据结构即可,手动拼接会导致变量解析出错
修复方案
调整URI模块任务,添加Content-Type头,并将Body改为API接受的单个字典格式:
- name: API call delegate_to: localhost uri: url: https://some_url/abcd/ validate_certs: false method: POST body_format: json headers: X-some-APIKey: "{{api_token}}" Content-Type: "application/json" body: "{{ array1[0] }}" register: api_output
如果API需要将数据包装在特定键名下(比如data),可以调整Body为:
body: data: "{{ array1[0] }}"
内容的提问来源于stack exchange,提问作者LJS
相关产品推荐
相关产品推荐

