为什么Ansible uri模块会获得带有有效credenitals的400?

问题描述

我们正在使用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命令可以正常工作,并返回状态代码为200的有效JSON内容

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

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

解决方法

使用body_format: json将设置标头Content-Type: application/json并发送body参数的值,即null

在您的情况下,您想要设置标头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