Loading...

Watch: Executing Custom Lookup Plugins in the Ansible Automation Platform

How to execute two custom Ansible Lookup Plugins to interact with API and read the contents of files in the local Ansible Controller.

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 needs. In this article, we’ll explore the creation of a custom Ansible lookup plugin in Python and execute it in Ansible Controller (part of Ansible Automation Platform).

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

To execute a custom Ansible lookup plugin in the Ansible Automation Platform, you’ll need to follow these steps:

1. Create the Custom Lookup Plugin:

  • Write your custom lookup plugin in Python. You can create a Python script file with the plugin code.
  • Save the plugin file in a directory named lookup_plugins in your Ansible project directory, or you can create a Python package for it.
  • Ensure that the plugin file has the .py extension.

2. Here’s an example of a simple custom lookup plugin:

  • token.py

```python

python 3 headers, required if submitting to Ansible

from __future__ import (absolute_import, division, print_function)

__metaclass__ = type

DOCUMENTATION = r"""

name: test

author: Luca Berton <[email protected]>

version_added: "0.1" # same as collection version

short_description: read API token

description:

- This lookup returns the token from the provided API.

"""

from ansible.errors import AnsibleError, AnsibleParserError

from ansible.plugins.lookup import LookupBase

from ansible.utils.display import Display

import requests

display = Display()

class LookupModule(LookupBase):

_URL_ = "https://reqres.in/api/login"

def run(self, terms, variables=None, **kwargs):

payload = {

"email": "[email protected]",

"password": "cityslicka"

}

try:

res = requests.post(self._URL_, data=payload)

res.raise_for_status()

ret = res.json()['token']

except requests.exceptions.HTTPError as e:

Read the full tutorial: Executing Custom Lookup Plugins in the Ansible Automation Platform