如何使用 Ansible 的 uri 模块通过 POST 请求向 REST API 端点提交认证请求,并获取 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。body_format(字符串):请求正文的序列化格式,如raw、json、form-urlencoded、form-multipart。body(原始):请求正文,通常用于 POST 请求。status_code(列表/整数):预期的 HTTP 状态码,如[200, 202]。headers(字典):自定义 HTTP 头,包括Content-Type。return_content(布尔值):是否返回响应正文,默认为false。timeout(整数):请求超时时间,默认为 30 秒。
示例:使用 Ansible Playbook 进行基于令牌的认证
成功登录的 Playbook 文件:post_login_correct.yml
---
- name: uri module demo
hosts: all
become: false
vars:
server: "https://reqres.in" # API 服务器地址
endpoint: "/api/login" # API 端点
tasks:
- name: 登录
ansible.builtin.uri:
url: "{{ server }}{{ endpoint }}"
method: POST
body_format: json
body: '{
"email": "eve.holt@reqres.in",
"password": "cityslicka"
}'
status_code: 200
timeout: 30
register: result
- name: 显示令牌
ansible.builtin.debug:
var: result.json.token
登录失败的 Playbook 文件:post_login_incorrect.yml
---
- name: uri module demo
hosts: all
become: false
vars:
server: "https://reqres.in" # API 服务器地址
endpoint: "/api/login" # API 端点
tasks:
- name: 登录
ansible.builtin.uri:
url: "{{ server }}{{ endpoint }}"
method: POST
body_format: json
body: '{
"email": "wronguser",
"password": "cityslicka"
}'
status_code: 200
timeout: 30
register: result
- name: 显示错误信息
ansible.builtin.debug:
var: result.json.error
执行命令
# 成功登录
$ ansible-playbook -i virtualmachines/demo/inventory interact\ webservices/post_login_correct.yml
# 登录失败
$ ansible-playbook -i virtualmachines/demo/inventory interact\ webservices/post_login_incorrect.yml
执行结果
成功登录
PLAY [uri module demo] ***************************************************
TASK [Gathering Facts] *****************************************************
ok: [demo.example.com]
TASK [登录] **************************************************************
ok: [demo.example.com]
TASK [显示令牌] ************************************************************
ok: [demo.example.com] => {
"result.json.token": "QpwL5tke4Pnpja7X4"
}
PLAY RECAP *****************************************************************
demo.example.com : ok=3 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
登录失败
PLAY [uri module demo] ***************************************************
TASK [Gathering Facts] *****************************************************
ok: [demo.example.com]
TASK [登录] **************************************************************
fatal: [demo.example.com]: FAILED! => {"access_control_allow_origin": "*", "alt_svc": "h3=\":443\"; ma=86400, h3-29=\":443\"; ma=86400, h3-28=\":443\"; ma=86400, h3-27=\":443\"; ma=86400", "cf_cache_status": "DYNAMIC", "cf_ray": "6bcf380f2d97694b-FRA", "changed": false, "connection": "close", "content_length": "26", "content_type": "application/json; charset=utf-8", "date": "Mon, 13 Dec 2021 12:33:06 GMT", "elapsed": 0, "etag": "W/\"1a-EGIcyP6BIiCXl5Gb1aph5CGf4VQ\"", "expect_ct": "max-age=604800, report-uri=\"https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct\"", "json": {"error": "user not found"}, "msg": "Status code was 400 and not [200]: HTTP Error 400: Bad Request", "nel": "{\"success_fraction\":0,\"report_to\":\"cf-nel\",\"max_age\":604800}", "redirected": false, "report_to": "{\"endpoints\":[{\"url\":\"https:\\/\\/a.nel.cloudflare.com\\/report\\/v3?s=E27%2Fk34cldTXza60OIDyqOnqo3kO6HrRmrXN7DDi8bI%2F6Rrhytd%2F2mvOFfQ1tk7lOiv2KY5fBpdnUzz2tl7l9XVxIAwp8nW0VLVSGRJFILki0iTP7LymmUfVSEQ%3D\"}],\"group\":\"cf-nel\",\"max_age\":604800}", "server": "cloudflare", "status": 400, "url": "https://reqres.in/api/login", "via": "1.1 vegur", "x_powered_by": "Express"}
PLAY RECAP *****************************************************************
demo.example.com : ok=1 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0
注意事项
- 请求正文格式:
body_format参数设置为json,确保请求正文以 JSON 格式发送。 - 状态码:
status_code参数设置为预期的 HTTP 状态码(如 200)。如果返回的状态码与预期不符,任务将失败。 - 返回内容:
return_content参数设置为true可以返回响应正文。 - 调试输出:使用
debug模块输出响应中的令牌或错误信息。
希望这个示例对您有帮助!