Introduction

Ansible, a powerful automation tool, offers a wide range of built-in modules and plugins that simplify infrastructure management. However, there are scenarios where you may need to extend Ansible’s capabilities by creating custom plugins tailored to your specific needs. In this article, we will explore creating and using a custom Ansible file lookup plugin, which allows you to retrieve file contents from your Ansible controller’s file system during playbook execution.

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

Unveiling the Custom File Lookup Plugin

Before delving into the details of the plugin, let’s take a closer look at the Python script provided at the beginning of this article. This script serves as an example of a custom Ansible file lookup plugin and consists of several essential 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: file

author: Luca Berton <[email protected]>

version_added: "0.1"

short_description: read file contents

description:

- This lookup returns the contents from a file on the Ansible controller's file system.

options:

_terms:

description: path(s) of files to read

required: True

option1:

description:

- Sample option that could modify plugin behaviour.

- This one can be set directly option1='x' or in ansible.cfg, but can also use vars or environment.

type: string

ini:

- section: file_lookup

key: option1

notes:

- if read in variable context, the file can be interpreted as YAML if the content is valid to the parser.

- this lookup does not understand globbing --- use the fileglob lookup instead.

`

This documentation block provides metadata about the plugin, including its name, author, version, a short description, and additional options. This information is crucial for documenting and understanding the plugin’s purpose and behavior.

3. Imports

`python

from ansible.errors import AnsibleError, AnsibleParserError

from ansible.plugins.lookup import LookupBase

from ansible.utils.display import Display

``

The script imports modules and classes from Ansible, allowing it to handle errors, utilize Ansible utilities, and provide display output.

4.