Search code examples
ansible

ansible 401 error in uri module but shell curl work


I have tried uri module in ansible, but I have still 401 authentication errors. In shell module when I am using curl all works. Can somebody please try to translate to uri code ?

- name: Get authentication token
  uri:
    url: https://myIPcontrol.com:8443/inc-rest/api/v1/login
    method: POST
    timeout: 30
    validate_certs: no
    headers:
        Content-Type: application/x-www-form-urlencoded
        Accept: application/json
    body:
      username: admin
      password: mypsw
    body_format: json
    return_content: yes
  register: authtoken
  
  
- name: Get authentication token
  shell: "curl -k  --header 'Content-Type: application/x-www-form-urlencoded' --header 'Accept: 
      application/json' -d 'username=admin&password=mypsw' -X POST  
      https://myIPcontrol.com:8443/inc-rest/api/v1/login"
  register: authtoken

Solution

  • When executing via the shell, your body (-d) is passed as username=admin&password=mypsw. This structure is form-urlencoded but you are passing body_format: json so Ansible is passing the body as {"user":"admin","password":"mypsw"} in conflict with the Content-Type header you set.

    Instead use

    body:
      username: admin
      password: mypsw
    body_format: form-urlencoded
    

    The rest looks correct to me. https://docs.ansible.com/ansible/latest/collections/ansible/builtin/uri_module.html