Interview Prep/Ansible/Modules, Idempotency and Handlers

`uri` fails with `Status code was 401 and not [200]: HTTP Error 401: Unauthorized`

IntermediateTroubleshootingModules, Idempotency and Handlers
Answer

Likely causes → No credentials were sent, the token is wrong or expired, or the server expects preemptive Basic auth and uri waits for a 401 challenge that never comes.

Fix →

- ansible.builtin.uri:
    url: https://api.internal/v1/deploy
    method: POST
    url_username: "{{ api_user }}"
    url_password: "{{ api_pass }}"
    force_basic_auth: true
    body_format: json
    body: {version: "{{ app_version }}"}
    status_code: [200, 201]
  no_log: true

For bearer tokens, use headers: {Authorization: "Bearer {{ token }}"}.

Prevent → List every acceptable status_code explicitly, and keep tokens in Vault with no_log.

All Ansible questions Roadmap: Ansible

More on Modules, Idempotency and Handlers