如何使用 Ansible 的 uri 模块从远程 Linux 主机向 REST API 端点提交 GET 请求并检索 JSON 用户列表?以下是一个示例,展示如何通过 Ansible Playbook 实现这一目标。
Ansible 模块 uri 概述
模块名称:ansible.builtin.uri
功能:与 Web 服务交互,支持 Digest、Basic 和 WSSE HTTP 认证机制
ansible.builtin.uri 是 Ansible 核心模块的一部分,用于与 Web 服务交互。
该模块非常稳定,已经存在多年,支持多种 POSIX 操作系统。
对于 Windows 系统,建议使用 ansible.windows.win_uri 模块。
参数介绍
url(字符串):API 的 URL,格式为(http|https)://host.domain[:port]/path。method(字符串):HTTP 请求方法,如GET、POST、PUT、PATCH、DELETE。user(字符串):用户名,用于访问 API 的认证。password(字符串):密码,用于访问 API 的认证。force_basic_auth(布尔值):是否启用 Basic HTTP 认证头。status_code(列表/整数):预期的 HTTP 状态码,如[200, 202]。headers(字典):自定义 HTTP 头,包括Content-Type。body_format(字符串):请求正文的序列化格式,如raw、json、form-urlencoded、form-multipart。body(原始):请求正文。return_content(布尔值):是否返回响应正文,默认为false。timeout(整数):请求超时时间,默认为 30 秒。
示例:使用 Ansible Playbook 提交 GET 请求到 REST API 端点
Playbook 文件:get_list_users.yml
---
- name: uri module demo
hosts: all
become: false
vars:
server: "https://reqres.in" # API 服务器地址
endpoint: "/api/users?page=2" # API 端点
tasks:
- name: 获取用户列表
ansible.builtin.uri:
url: "{{ server }}{{ endpoint }}"
method: GET
status_code: 200
timeout: 30
register: result
- name: 调试输出
ansible.builtin.debug:
var: result.json.data
执行命令
$ ansible-playbook -i virtualmachines/demo/inventory interact\ webservices/list_users.yml
执行结果
PLAY [uri module demo] ***************************************************
TASK [Gathering Facts] *****************************************************
ok: [demo.example.com]
TASK [获取用户列表] ************************************************************
ok: [demo.example.com]
TASK [调试输出] **************************************************************
ok: [demo.example.com] => {
"result.json.data": [
{
"avatar": "https://reqres.in/img/faces/7-image.jpg",
"email": "michael.lawson@reqres.in",
"first_name": "Michael",
"id": 7,
"last_name": "Lawson"
},
{
"avatar": "https://reqres.in/img/faces/8-image.jpg",
"email": "lindsay.ferguson@reqres.in",
"first_name": "Lindsay",
"id": 8,
"last_name": "Ferguson"
},
{
"avatar": "https://reqres.in/img/faces/9-image.jpg",
"email": "tobias.funke@reqres.in",
"first_name": "Tobias",
"id": 9,
"last_name": "Funke"
},
{
"avatar": "https://reqres.in/img/faces/10-image.jpg",
"email": "byron.fields@reqres.in",
"first_name": "Byron",
"id": 10,
"last_name": "Fields"
},
{
"avatar": "https://reqres.in/img/faces/11-image.jpg",
"email": "george.edwards@reqres.in",
"first_name": "George",
"id": 11,
"last_name": "Edwards"
},
{
"avatar": "https://reqres.in/img/faces/12-image.jpg",
"email": "rachel.howell@reqres.in",
"first_name": "Rachel",
"id": 12,
"last_name": "Howell"
}
]
}
注意事项
- API 认证:如果需要认证,可以使用
user和password参数,并启用force_basic_auth。 - 状态码:
status_code参数用于指定预期的 HTTP 状态码。如果返回的状态码与预期不符,任务将失败。 - 返回内容:
return_content参数设置为true可以返回响应正文。 - 超时时间:可以使用
timeout参数自定义请求超时时间,默认为 30 秒。
希望这个示例对您有帮助!