How to authenticate requests using the REST API token with Ansible? Also called Token Based Authentication in REST API.

I’m going to show you a live Playbook and some simple Ansible code. I’m Luca Berton and welcome to today’s episode of Ansible Pilot.

Ansible Token Based Authentication in REST API

  • ansible.builtin.uri
  • Interacts with webservices supports Digest, Basic, and WSSE HTTP authentication mechanisms

Today we’re talking about the Ansible module uri. The full name is ansible.builtin.uri, which means that is part of the collection of modules “builtin” with ansible and shipped with it. It’s a module pretty stable and out for years and it works in a different variety of POSIX operating systems. It interacts with web services and supports Digest, Basic, and WSSE HTTP authentication mechanisms. If you need to download content, use the Ansible ansible.builtin.get_url module. For Windows targets, use the ansible.windows.win_uri module instead.

Parameters

  • url string - (http|https)://host.domain[:port]/path
  • method string - “GET”, “POST”, “PUT”, “PATCH”, “DELETE”
  • user (url_username), password (url_password) string - username, password
  • force_basic_auth boolean - no,yes - Basic authentication header
  • status_code list/integer - [200, 202]
  • headers dictionary - custom HTTP headers, Content-Type
  • body_format string - raw, json, form-urlencoded, form-multipart
  • body raw
  • return_content boolean - no/yes - return the body of the response
  • timeout integer - 30

This module has some parameters to perform any tasks. The only required is “url”, where you specify the API URL. The parameter “method” specifies the HTTP method of the request: “GET”, “POST”, “PUT”, “PATCH”, “DELETE”. The parameters “user” and “password” specify the credentials to access the API. Several authentications methods are supported, for the simplest is the Basic HTTP authentication remember to enable the “force_basic_auth” boolean. The parameter “status_code” sets the expected single or list of expected HTTP status codes. The most commons are okay is 200, not fount is 404, and so on… If Please note that Ansible is going to return an error if the status code is different. The parameter “headers” set the custom HTTP headers and HTTP Content-Type. The parameter “body_format” sets the serialization format of the body content. Default is raw, but you could customize it to send an image for example. There are some restrictions with Content-Type and some serializations. The parameter “return_content” is very important to return the body of the response as a “content” key in the dictionary result. The default timeout is set to 30 seconds, but you could customize it with the “timeout” parameter.

Join 50+ hours of courses in our exclusive community

Playbook

Let’s jump into a real-life playbook on how to Token Based Authentication in REST API with Ansible.

code successful login

  • post_login_correct.yml
---
- name: uri module Playbook
  hosts: all
  become: false
  vars:
    server: "https://reqres.in"
    endpoint: "/api/login"
  tasks:
    - name: login
      ansible.builtin.uri:
        url: "{{ server }}{{ endpoint }}"
        method: POST
        body_format: json
        body: '{
          "email": "[email protected]",
          "password": "cityslicka"
        }'
        status_code: 200
        timeout: 30
      register: result
    - name: token
      ansible.builtin.debug:
        var: result.json.token

execution successful login

$ ansible-playbook -i virtualmachines/demo/inventory interract\ webservices/post_login.yml
PLAY [uri module Playbook] ****************************************************************************
TASK [Gathering Facts] ****************************************************************************
ok: [demo.example.com]
TASK [login] **************************************************************************************
ok: [demo.example.com]
TASK [token] **************************************************************************************
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

code insuccessful login

  • post_login_incorrect.yml
---
- name: uri module Playbook
  hosts: all
  become: false
  vars:
    server: "https://reqres.in"
    endpoint: "/api/login"
  tasks:
    - name: login
      ansible.builtin.uri:
        url: "{{ server }}{{ endpoint }}"
        method: POST
        body_format: json
        body: '{
          "email": "wronguser",
          "password": "cityslicka"
        }'
        status_code: 200
        timeout: 30
      register: result
    - name: token
      ansible.builtin.debug:
        var: result.json.token

execution unsuccessful login

$ ansible-playbook -i virtualmachines/demo/inventory interract\ webservices/post_login_incorrect.yml
PLAY [uri module Playbook] ****************************************************************************
TASK [Gathering Facts] ****************************************************************************
ok: [demo.example.com]
TASK [login] **************************************************************************************
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

code with ❤️ in GitHub

Conclusion

Now you know how to Token Based Authentication in REST API with Ansible. Subscribe to the YouTube channel, Medium, and Website, X (formerly Twitter) to not miss the next episode of the Ansible Pilot.

Academy

Learn the Ansible automation technology with some real-life examples in my Udemy 300+ Lessons Video Course.

BUY the Complete Udemy 300+ Lessons Video Course

My book Ansible By Examples: 200+ Automation Examples For Linux and Windows System Administrator and DevOps

BUY the Complete PDF BOOK to easily Copy and Paste the 250+ Ansible code

Want to keep this project going? Please donate

Patreon Buy me a Pizza