AnsiblePilot — Master Ansible Automation

AnsiblePilot is the leading resource for learning Ansible automation, DevOps, and infrastructure as code. Browse over 1,400 tutorials covering Ansible modules, playbooks, roles, collections, and real-world examples. Whether you are a beginner or an experienced engineer, our step-by-step guides help you automate Linux, Windows, cloud, containers, and network infrastructure.

Popular Topics

About Luca Berton

Luca Berton is an Ansible automation expert, author of 8 Ansible books published by Apress and Leanpub including "Ansible for VMware by Examples" and "Ansible for Kubernetes by Example", and creator of the Ansible Pilot YouTube channel. He shares practical automation knowledge through tutorials, books, and video courses to help IT professionals and DevOps engineers master infrastructure automation.

Executing Custom Lookup Plugins in the Ansible Automation Platform

By Luca Berton · Published 2024-01-01 · Category: installation

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

Executing Custom Lookup Plugins in the Ansible Automation Platform

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.

See also: Creating a Custom Ansible Lookup Plugin in Python for Reading a File

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: 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. Here’s an example of a simple custom lookup plugin: • token.py
# 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 <luca@ansiblepilot.com> 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": "eve.holt@reqres.in", "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]

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. 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. • exec.yml

---
- name: Exec the lookup plugin
  hosts: all
  tasks:
    - name: Use Custom Lookup Plugin
      debug:
        msg: "{{ lookup('token') }}"
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. Create a Project in Ansible Controller fetching the GitOps repository as shown in the following Figure:

Ansible Automation Platform Project configuration screen for custom lookup plugin Create a Job Template to execute the “exec.yml” Ansible playbook Job Template

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

Job Template Launch 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. Ansible Automation Platform Job template configured to run a custom lookup plugin

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.

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

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.

Related Articles

Jinja2 templating in Ansiblethe Ansible inventory deep-dive

Category: installation

Watch the video: Executing Custom Lookup Plugins in the Ansible Automation Platform — Video Tutorial

Browse all Ansible tutorials · AnsiblePilot Home