Introduction to AnsibleANSIBLE Course Material · Practical Exercises · BONUS
BONUS · Python + Ansible

Creating a Custom Ansible Module

Ansible ships with many built-in modules, but you can also develop your own modules in Python. This bonus exercise connects introductory Python programming with the Ansible concepts you have already learnt.

Learning objectives: create a Python-based Ansible module, pass arguments from YAML, return structured results, use register, and extend the module with basic Python operations.

1. What is a custom module?

A custom Ansible module is a program that Ansible can invoke as a task. It receives parameters, performs an operation and returns structured data. Custom modules do not become part of the reserved ansible.builtin namespace.

Our example, my_message, will accept a message and return its uppercase version. It will not modify the managed host.

2. Prerequisites and project structure

Work on the Ansible control node (deb-ctrl). You need Ansible installed, SSH access to your managed hosts, and a compatible Python 3 interpreter on each managed host. Use the existing inventory.ini from your lab.

cd ~/ansible-lab
mkdir -p library

The project should look like this:

ansible-lab/
├── inventory.ini
├── custom_module.yml
└── library/
    └── my_message.py
Why library/? Ansible automatically searches a library directory alongside the playbook for local custom modules.

3. Write the Python module

Create the module file:

nano library/my_message.py

Enter the following Python code:

#!/usr/bin/python3

from ansible.module_utils.basic import AnsibleModule


def main():
    module = AnsibleModule(
        argument_spec=dict(
            message=dict(type='str', required=True)
        ),
        supports_check_mode=True
    )

    message = module.params['message']
    result = message.upper()

    module.exit_json(
        changed=False,
        original=message,
        uppercase=result
    )


if __name__ == '__main__':
    main()

4. Understand the Python code

Import the Ansible API

from ansible.module_utils.basic import AnsibleModule

The AnsibleModule class handles argument validation and communicates results back to Ansible.

Define an entry point

def main():
    ...

if __name__ == '__main__':
    main()

Python runs main() when this file is executed as a program.

Declare the input parameter

module = AnsibleModule(
    argument_spec=dict(
        message=dict(type='str', required=True)
    ),
    supports_check_mode=True
)

The module accepts a mandatory string argument called message. The supports_check_mode=True flag declares support for Ansible check mode. Since this example only transforms text, it is safe to execute in check mode.

Read the parameter and process it

message = module.params['message']
result = message.upper()

The first line reads the argument supplied by the playbook. The second uses the standard Python str.upper() method.

Return structured data

module.exit_json(
    changed=False,
    original=message,
    uppercase=result
)

exit_json() reports a successful result. changed=False tells Ansible that the managed host was not modified. The other fields can be accessed through register.

5. Call the custom module from a playbook

Create custom_module.yml:

---
- name: Test our custom Python module
  hosts: all
  gather_facts: false

  tasks:
    - name: Execute our custom module
      my_message:
        message: "Hello from Python and Ansible"
      register: result

    - name: Display original message
      ansible.builtin.debug:
        msg: "{{ result.original }}"

    - name: Display uppercase message
      ansible.builtin.debug:
        msg: "{{ result.uppercase }}"

Notice that my_message is called directly as an Ansible module. You do not have to call python3 explicitly. Ansible transfers and runs the module on each managed host.

6. Run the playbook and inspect the result

ansible-playbook -i inventory.ini custom_module.yml

Expected output (extract):

TASK [Execute our custom module]
ok: [node1]
ok: [node2]

TASK [Display original message]
ok: [node1] => {
    "msg": "Hello from Python and Ansible"
}

TASK [Display uppercase message]
ok: [node1] => {
    "msg": "HELLO FROM PYTHON AND ANSIBLE"
}

To display the entire registered result, add this task:

- name: Display complete result
  ansible.builtin.debug:
    var: result

Among the returned fields, you should find:

{
    "changed": false,
    "original": "Hello from Python and Ansible",
    "uppercase": "HELLO FROM PYTHON AND ANSIBLE"
}

The actual registered dictionary will also contain Ansible metadata. The key idea is that the Python module returns named fields that subsequent YAML tasks can access.

7. Practical exercise: extend the module

Modify the Python module so that it also returns the number of characters, the lowercase message and the reversed message.

Step A: add three Python operations

length = len(message)
lowercase = message.lower()
reversed_message = message[::-1]

Step B: extend the result

module.exit_json(
    changed=False,
    original=message,
    uppercase=result,
    lowercase=lowercase,
    length=length,
    reversed=reversed_message
)
Important: place the three new calculations before module.exit_json(). That function ends the module execution.

Step C: display the new fields in the playbook

- name: Display Python results
  ansible.builtin.debug:
    msg:
      - "Original: {{ result.original }}"
      - "Uppercase: {{ result.uppercase }}"
      - "Lowercase: {{ result.lowercase }}"
      - "Length: {{ result.length }}"
      - "Reversed: {{ result.reversed }}"

Run the playbook again and compare the results. All three operations use standard Python, but the values are now available to Ansible tasks.

8. Python concepts covered

Python conceptPurpose
importImport a library or class
defDefine a function
VariablesStore values for later use
dictDefine structured arguments
len()Count characters
.upper()Convert text to uppercase
.lower()Convert text to lowercase
[::-1]Reverse a string
if __name__ == '__main__'Define the program entry point

9. Going further: real-world custom modules

A custom module can also inspect disk space, check whether a user exists, inspect a Linux service, manage configuration files or communicate with an API. A production-quality module should handle errors, report changes accurately, support idempotence where appropriate and implement check mode correctly.

Possible modulePurpose
my_messageTransform text
my_diskcheckInspect free disk space
my_usercheckCheck whether a user exists
my_servicecheckInspect a Linux service
my_configRead or manage a configuration file
my_apiInteract with an API

10. Knowledge check

1) Where can Ansible find a local custom module?
  • A. In a library/ directory beside the playbook
  • B. Only in /usr/bin/
  • C. Only on Ansible Galaxy
2) What does changed=False indicate?
  • A. The task failed
  • B. No managed-host state was changed
  • C. Python was not executed
3) Which keyword captures the module result for later tasks?
  • A. serial
  • B. become
  • C. register
Answer key
1) A · 2) B · 3) C
Key takeaway: Python extends Ansible. A custom module receives parameters from a YAML task, performs Python operations and returns structured data that Ansible can reuse.