Ansible Pilot

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.

September 14, 2023
Access the Complete Video Course and Learn Quick Ansible by 200+ Practical Lessons

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.

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:
  1. Here’s an example of a simple custom lookup plugin:
# 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:
        raise AnsibleError('There was an error getting a token. The lookup API returned %s', response.status_code)
      except Exception as e:
        raise AnsibleError('Unhandled exception is lookup plugin. Origin: %s', e)

      return [ret]
  1. Install Dependencies (if required): If your custom lookup plugin has external dependencies, make sure they are installed on the system where you plan to run your Ansible playbook.

  2. Create an Ansible Playbook: Create an Ansible playbook or role that uses your custom lookup plugin. You can define variables and tasks within your playbook that utilize the plugin.

---
- name: Exec the lookup plugin
  hosts: all
  tasks:
    - name: Use Custom Lookup Plugin
      debug:
        msg: "{{ lookup('token') }}"
  1. Publish the code in a GitOps repository (for example, GitHub or Gitlab).

Note: We can also manually test and execute the Playbook using the ansible-playbook command. Make sure to specify the inventory file and the playbook file.

ansible-playbook -i inventory.ini exec.yml

Replace inventory.ini with your actual inventory file.

  1. Create a Project in Ansible Controller fetching the GitOps repository as shown in the following Figure:

Project

  1. Create a Job Template to execute the “exec.yml” Ansible playbook

Job Template

Replace the inventory with your actual inventory. 8. Launch the Job Template to execute the Custom Lookup Plugin

Job Template Launch

  1. View the Output: Ansible will execute your playbook, including the custom lookup plugin. The plugin’s output will be displayed in the playbook’s output, as shown in the debug task in the example playbook above.

Job

That’s it! You’ve successfully executed a custom Ansible lookup plugin in the Ansible Automation Platform. You can extend the functionality of your custom lookup plugin as needed to suit your automation requirements.

Conclusion

In conclusion, this article has provided a comprehensive guide on creating and executing custom Ansible Lookup Plugins within the Ansible Automation Platform. We began by understanding the essential role of Lookup Plugins in dynamically fetching data for Ansible tasks and then detailed a step-by-step process for creating, installing, and utilizing these custom plugins. By following these instructions, users can harness the full potential of Ansible to tailor their automation workflows, efficiently manage infrastructure, and seamlessly integrate external data sources, ultimately enhancing the versatility and effectiveness of their Ansible automation efforts.

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

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

Access the Complete Video Course and Learn Quick Ansible by 200+ Practical Lessons
Follow me

Subscribe not to miss any new releases