Loading...

Watch: Ansible Playbook: POST Request and Token Retrieval Demo

Use Ansible to send a POST request and retrieve a token from a server. Learn to automate login processes with Ansible's URI module.

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](/articles/download-a-file-ansible-module-get-url).

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 r

Read the full tutorial: Ansible Playbook: POST Request and Token Retrieval Demo