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

Ansible uri模块如何获取API返回的内容?

问题

目标API应返回一个10位字符串,用curl访问该API URL能得到正确结果,但使用Ansible的uri模块时,返回的是包含状态信息的完整响应对象而非目标字符串。

Playbook代码如下:

- name: Get variable output from api 
  uri:
    url: "http://apiurl"
  register: my_variable

- name: Print my_variable
  debug:
    msg: "Value of the variable is {{ my_variable }}"

调试输出信息:

"msg": "Value of the variable is {'redirected': False, 'url': 'http://apiurl', 'status': 200, 'server': 'nginx/1.10.3', 'date': 'Thu, 27 Oct 2022 17:47:49 GMT', 'content_type': 'text/plain; charset=utf-8', 'content_length': '23', 'connection': 'close', 'cookies_string': '', 'cookies': {}, 'msg': 'OK (23 bytes)', 'elapsed': 0, 'changed': False, 'failed': False}"

原因与解决方法

原因

Ansible的uri模块默认会将整个HTTP响应的元数据和内容打包成一个字典对象返回,而非直接返回响应体内容。你看到的调试输出就是这个完整响应对象,其中包含状态码、响应头、请求时长等信息,API返回的10位字符串实际存储在该对象的content字段中。

解决方法

要获取API返回的字符串内容,只需在调试时调用my_variable.content即可。修改后的Playbook如下:

- name: Get variable output from api 
  uri:
    url: "http://apiurl"
  register: my_variable

- name: Print API response content
  debug:
    msg: "Value of the variable is {{ my_variable.content }}"

如果API返回内容存在编码问题,可添加return_content: yes参数显式指定返回响应体,确保内容正确解析:

- name: Get variable output from api 
  uri:
    url: "http://apiurl"
    return_content: yes
  register: my_variable

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 16:50:38