Ansible Pilot

Token Based Authentication in REST API - Interact with webservice - Ansible module uri - Authentication request using the REST API token

How to retrieve a JSON token via a POST authentication request using a JSON body formed by email and password to a REST API web service HTTPS endpoint from a remote Linux host in a few lines of Ansible code.

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 demo 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

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

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.

demo

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

code successful login

---
- name: uri module demo
  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 demo] ****************************************************************************
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

---
- name: uri module demo
  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 demo] ****************************************************************************
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

Recap

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

Academy

Learn the Ansible automation technology with some real-life examples in my

Want to keep this project going? Please donate

Trustpilot
Follow me

Subscribe not to miss any new releases

December 20, 2021

FREE Top 10 Best Practices

Top 10 Best Practices of Ansible Automation: save time, reduce errors and stress