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_pluginsin your Ansible project directory, or you can create a Python package for it.
- Ensure that the plugin file has the
.pyextension.
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:
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]
``
3. 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.
4. Create an Ansible Playbook: Create an Ansible playbook or role that