Loading...

Watch: Creating a Custom Ansible Lookup Plugin in Python for retrieving API token

Learn how to create an Ansible lookup plugin to fetch API tokens, with a complete example of the token.py plugin code and step-by-step explanations.

Introduction

Ansible, an open-source automation tool, offers a wide range of built-in modules and plugins to simplify infrastructure management. However, sometimes, you may need to extend its functionality by creating custom plugins tailored to your specific needs. In this article, we’ll explore the creation of a custom Ansible lookup plugin in Python.

What is a Lookup Plugin?

Ansible lookup plugins are used to retrieve data dynamically during playbook execution. They allow you to fetch information from various sources, such as databases, APIs, or external files, and use that data in your Ansible tasks.

Links

  • https://docs.ansible.com/ansible/latest/dev_guide/developing_plugins.html#lookup-plugins
  • https://docs.ansible.com/ansible/latest/plugins/lookup.html#lookup-plugins
  • https://docs.ansible.com/ansible/latest/reference_appendices/config.html#default-lookup-plugin-path

Step by Step

The following steps explain how to create a custom Ansible lookup plugin in Python. It begins by introducing lookup plugins in Ansible, which are used to fetch data dynamically during playbook execution. The provided Python script is an example of a plugin designed to retrieve an API token from a specific URL. The following steps break down the script into its components: Python headers, documentation, imports, initialization, and the custom lookup module with its ‘run’ method.

Setting the Stage

Let’s consider the example of retrieving a token via an API request with a POST specifying email and password. This is a common behavior. In the following example, we are using the following endpoint https://reqres.in/api/login with the credentials: “email”: “[email protected] and “password”: “cityslicka”. A successful connection to the API returns the token QpwL5tke4Pnpja7X4.

You can find the full code at the end of the article. Let’s take a closer look at the Python script provided at the beginning of this article. This script is an example of a custom Ansible token.py lookup plugin designed to fetch an API token from a specific URL. Here’s a breakdown of its components:

1. Python 3 Headers

``python

from __future__ import (absolute_import, division, print_function)

__metaclass__ = type

`

These lines specify Python 3 headers required for compatibility when submitting this plugin to Ansible.

2. Documentation

``python

DOCUMENTATION = r"""

name: test

author: Luca Berton <[email protected]>

version_added: "0.1" # same as

Read the full tutorial: Creating a Custom Ansible Lookup Plugin in Python for retrieving API token