Skip to main content

Working with Plugin Types

1. Understanding Plugin Types

Plugin Type Description Use Case Example
Action Plugins Control how tasks are executed on the target host Execute commands, manage files, run scripts ansible.builtin.command
Callback Plugins Handle output and logging during playbook execution Customize output format, send notifications ansible.builtin.default
Connection Plugins Define how Ansible connects to managed nodes SSH, local, Docker, network devices ansible.netcommon.network_cli
Inventory Plugins Define how Ansible discovers and retrieves inventory data Dynamic inventory from cloud providers, databases ansible.builtin.aws_ec2
Lookup Plugins Retrieve data from external sources during playbook execution Fetch secrets, API responses, file contents ansible.builtin.uri
Module Plugins Define the actions that can be performed on managed nodes Manage packages, services, users, files ansible.builtin.file
Vars Plugins Define how variables are loaded and processed Load variables from external sources ansible.builtin.yaml
Filter Plugins Modify data in templates or conditionals Transform variables, format output ansible.builtin.json_query
Test Plugins Provide custom test conditions for conditionals Validate variable values or states ansible.builtin.failed
Cache Plugins Store and retrieve data from a cache backend Speed up inventory lookups, reduce API calls ansible.builtin.memory

Example: Using a Custom Action Plugin

from ansible.plugins.action import ActionBase

class ActionModule(ActionBase):
    def run(self, tmp=None, task_vars=None):
        return {"changed": False, "msg": "Custom action executed"}
Note: Plugin types can be extended or overridden in custom Ansible installations.

2. Using Filter Plugins

Filter Description Example
upper Converts a string to uppercase "hello world" | upper
lower Converts a string to lowercase "HELLO WORLD" | lower
title Converts a string to title case "hello world" | title
capitalize Capitalizes the first letter of a string "hello world" | capitalize
reverse Reverses a string or list "hello" | reverse
join Joins a list with a delimiter [1, 2, 3] | join(',')
split Splits a string into a list "a,b,c" | split(',')
regex_replace Replaces a regex pattern with a string "hello world" | regex_replace('world', 'universe')
regex_escape Escapes regex special characters in a string "hello (world)" | regex_escape
quote Quotes a string for shell usage "hello world" | quote

Example: Using filter plugins in a task

- name: Set a variable with uppercase string
  set_fact:
    message: "hello world" | upper

- name: Join list elements with a comma
  set_fact:
    joined_list: "[1, 2, 3]" | join(",")

Example: Using regex_replace filter

- name: Replace a word in a string
  set_fact:
    new_message: "Hello world, welcome to the world of Ansible" | regex_replace("world", "universe")

3. Using Test Plugins

Plugin Type Description Usage Notes
test Verifies the state of a system or data Used in playbooks to assert conditions Part of Ansible's assertion framework

Example: Using test plugins in a playbook

- name: Verify system is running
  hosts: all
  tasks:
    - name: Check if service is running
      command: systemctl is-active nginx
      register: result
    - name: Assert service status
      assert:
        that:
          - "result.rc == 0"
        fail_msg: "Nginx is not running"
        success_msg: "Nginx is running correctly"
Note: Test plugins are typically used in combination with assert tasks to validate system states during playbook execution.

Key Features of Test Plugins

  • Can be used in assert tasks to validate conditions
  • Supports complex conditional logic with that clause
  • Can be used for validation in CI/CD pipelines

4. Using Action Plugins

Property Description Example
action Specifies the action plugin to use for executing a task action: copy
module Alias for action, used to specify the module or plugin module: command

Example: Using the copy action plugin

---
- name: Copy a file using the copy action plugin
  hosts: all
  tasks:
    - name: Copy local file to remote
      copy:
        src: /local/file.txt
        dest: /remote/file.txt

Example: Using the command action plugin

---
- name: Execute a command using the command action plugin
  hosts: all
  tasks:
    - name: Run a shell command
      command: ls -l /etc
Note: Action plugins can be used to extend Ansible's functionality by defining custom behavior for task execution. They are invoked when a task specifies an action or module.
Warning: Be cautious when using action plugins that execute commands or modify system state, as they can potentially be unsafe if not properly validated.

5. Using Connection Plugins

Plugin Type Description Default Notes
connection Controls how Ansible connects to managed nodes ssh Used for remote execution on nodes

Example: Using connection plugins in a playbook

---
- hosts: all
  connection: local
  tasks:
    - name: Check system info
      command: uname -a

Common Connection Plugins

  • ssh – Standard SSH connection to remote hosts
  • local – Execute tasks on the Ansible control node
  • winrm – Connect to Windows hosts via WinRM
  • httpapi – For network devices using HTTP APIs
Note: The connection parameter can be set at the playbook, group, or host level.

6. Using Cache Plugins

Plugin Type Description Configuration Key Default
cache Cache plugin to use for storing facts and other data fact_caching_plugin memory

Example: Configuring Redis Cache Plugin

ansible_config:
  fact_caching_plugin: redis
  fact_caching_connection: redis://localhost:6379/0
  fact_caching_timeout: 86400

Example: Using Cache in Playbook

- name: Use cached facts
  hosts: all
  tasks:
    - name: Get host facts from cache
      setup:
        fact_path: ansible_facts
      delegate_to: "{{ inventory_hostname }}"
      cacheable: true
Note: Cache plugins can significantly improve performance in large environments by avoiding repeated fact gathering.

Cache Plugin Types

  • memory: In-memory cache (default, non-persistent)
  • redis: Redis-based persistent cache
  • memcached: Memcached-based cache
  • jsonfile: JSON file-based cache (for debugging)

7. Configuring Plugin Paths

Configuration Option Values Description
ansible_plugins ~/.ansible/plugins Default directory for user-defined plugins
ansible_plugins /etc/ansible/plugins System-wide directory for plugins

Example: Setting plugin paths in ansible.cfg

[defaults]
plugins = /custom/plugins/path
Note: Plugin paths can be specified in ansible.cfg or via the ANSIBLE_PLUGINS environment variable.

8. Creating Custom Plugins

Creating custom Ansible plugins allows you to extend Ansible's functionality for specific use cases. Plugins are Python modules that implement a specific interface and can be used to add new capabilities or modify existing behavior.

Plugin Type Description Directory Location Base Class
Action Executes tasks on the managed nodes plugins/action/ BaseAction
Callback Handles task and play events for logging or reporting plugins/callback/ BaseCallback
Inventory Provides inventory sources for dynamic host discovery plugins/inventory/ BaseInventory
Lookup Retrieves data from external sources during playbook execution plugins/lookup/ BaseLookup
Filter Modifies data in templates or variables plugins/filter/ BaseFilter
Test Provides test functions for Jinja2 templates plugins/test/ BaseTest

Example: Creating a Custom Filter Plugin

# plugins/filter/my_filter.py

def my_upper(value):
    return value.upper()

class FilterModule:
    def filters(self):
        return {
            'my_upper': my_upper
        }

Example: Using the Custom Filter in a Playbook

# playbook.yml

- hosts: all
  tasks:
    - name: Use custom filter
      debug:
        msg: "{{ 'hello world' | my_upper }}"
Note: Custom plugins must be placed in the correct directory structure under your Ansible project or in a collection. The plugin's base class determines its interface and behavior.
Warning: Ensure that custom plugins are compatible with the Ansible version you're using. Plugin interfaces may change between major versions.

9. Using Inventory Plugins

Plugin Type Description Configuration Notes
ini INI-style inventory files with groups and hosts inventory.ini file format Default inventory plugin if no other specified
yaml YAML-based inventory with structured data inventory.yaml or inventory.yml More readable and maintainable than INI format
ec2 Dynamic inventory from AWS EC2 instances Requires boto3 and credentials Supports tags, regions, and filters
gcp_compute Dynamic inventory from Google Cloud Platform Compute Engine Requires google-cloud-compute and service account Supports project filtering and zones
azure_rm Dynamic inventory from Azure Resource Manager Requires azure-mgmt-compute and credentials Supports subscription filtering and resource groups
vmware_vm Dynamic inventory from VMware vSphere VMs Requires pyvmomi and connection details Supports tags, folders, and clusters

Example: YAML Inventory with Groups

all:
  hosts:
    web01:
      ansible_host: 192.168.1.10
    web02:
      ansible_host: 192.168.1.11
  children:
    webservers:
      hosts:
        web01:
        web02:
    databases:
      hosts:
        db01:
          ansible_host: 192.168.1.20

Example: EC2 Inventory Plugin Configuration

[inventory]
plugin = aws_ec2
regions = us-east-1,us-west-2
filters = tag:Environment=prod
Note: Inventory plugins can be combined with group_by and host_grouping to dynamically organize hosts.
Warning: Ensure credentials and permissions are correctly set for dynamic inventory plugins like ec2 or gcp_compute.

10. Using Vars Plugins

Plugin Type Description Usage Notes
vars Loads variables for use in playbooks and templates Defined in vars/ directory or via vars_plugins Can be used to inject variables from external sources like databases or APIs

Example: Using vars plugin to load from YAML file

---
- hosts: all
  vars_plugins:
    - yaml_file
  vars:
    my_var: "value"
Note: Vars plugins are executed before the playbook runs and can influence variable precedence.

Was this article helpful?