为什么 Ansible uri 模块使用有效凭据获得 400?

Why does the Ansible uri module get 400 with valid credenitals?

我们正在使用 uri 模块查询 Graylog API 数据,其格式为 json。

- name: Get data
  uri:
    url: http://graylog-host:9000/api/system
    url_username: username
    url_password: password
    force_basic_auth: yes
    return_content: yes
    method: GET
    body_format: json
    validate_certs: false
  register: node_id_output

不幸的是,执行此任务时出现以下错误:

fatal: [hostname]: FAILED! => {"changed": false, "connection": "close", "content": "", "content_length": "0", "date": "Wed, 02 Sep 2020 07:21:25 GMT", "elapsed": 0, "msg": "Status code was 400 and not [200]: HTTP Error 400: Bad Request", "redirected": false, "status": 400, "url": "http://graylog-host:9000/api/system"}

虽然以下 Curl 命令工作正常并且 returns 有效 JSON 状态代码为 200 的内容:

curl -u username:password -H "Accept: application/json"  http://graylog-host:9000/api/system

错误的原因是什么?或者,我们可以使用 body_format: form-urlencoded,它不会 return 400,但不幸的是,json_query 过滤器无法解析内容。

使用 body_format: json 将设置 header Content-Type: application/json 并发送 body 参数的值 null.

在你的情况下,你想设置 header Accept: application/json 来取回 JSON 而不是其他东西(XML 我猜)。

- name: Get data
  uri:
    url: http://graylog-host:9000/api/system
    url_username: username
    url_password: password
    force_basic_auth: yes
    return_content: yes
    method: GET
    headers:
      Accept: application/json
    validate_certs: false
  register: node_id_output