Ansible Custom Modules
Thousands of modules exist, and some jobs still lack a ready-made tool. A company may need to talk to an internal inventory service or check a proprietary device. A custom module fills the gap. Imagine ordering a custom key at a locksmith: the standard keys do not fit, so a new one is cut to the exact shape. Ansible modules can use any language that handles JSON, and Python is the standard choice.
How a Module Works
Control Node Managed Node
┌───────────┐ 1. copy module ┌─────────────────┐
│ Playbook │──────────────────▶│ temp folder │
│ task │ 2. send args │ │
│ │──────────────────▶│ run module │
│ │ │ │ do the job │
│ │◀──────────────────│ ▼ │
└───────────┘ 3. JSON result │ print JSON │
└─────────────────┘
A module receives arguments, performs a job, and prints a JSON result that states whether anything changed or failed.
Where to Place the File
Store project modules in a folder named library beside the playbook. Roles can ship modules in library inside the role folder. Ansible discovers them automatically.
project/
├── site.yml
└── library/
└── file_checksum.py
A Simple Python Module
This module calculates the SHA256 checksum of a file and reports the result.
#!/usr/bin/python
from ansible.module_utils.basic import AnsibleModule
import hashlib
import os
def main():
module = AnsibleModule(
argument_spec=dict(
path=dict(type='path', required=True),
),
supports_check_mode=True,
)
path = module.params['path']
if not os.path.isfile(path):
module.fail_json(msg="File not found: " + path)
sha = hashlib.sha256()
with open(path, 'rb') as handle:
for block in iter(lambda: handle.read(65536), b''):
sha.update(block)
module.exit_json(changed=False, path=path, checksum=sha.hexdigest())
if __name__ == '__main__':
main()
Understand Each Part
- AnsibleModule handles argument parsing, validation, and JSON output
- argument_spec lists accepted options, their types, and defaults
- exit_json reports success and returns data
- fail_json reports failure with a message
- supports_check_mode allows dry runs with
--check
Call the Module
- name: Verify the release file
hosts: webservers
tasks:
- name: Calculate checksum
file_checksum:
path: /opt/shop/release.tar.gz
register: result
- name: Show the checksum
ansible.builtin.debug:
msg: "{{ result.checksum }}"
Test Without a Playbook
Create a JSON file with arguments and run the module directly.
echo '{"ANSIBLE_MODULE_ARGS": {"path": "/etc/hostname"}}' > args.json
python3 library/file_checksum.py args.json
The ad-hoc form ansible localhost -m file_checksum -a "path=/etc/hostname" works too.
Report Changes Correctly
A good module reports changed=True only when it altered the system. The module should compare the current state with the requested state and act only on a difference. This habit delivers idempotency, which keeps repeated runs safe.
if current_value == wanted_value:
module.exit_json(changed=False)
else:
set_value(wanted_value)
module.exit_json(changed=True)
Document the Module
Add DOCUMENTATION, EXAMPLES, and RETURN strings in YAML at the top of the file. The ansible-doc command reads them and shows help text for teammates.
Alternatives to Writing a Module
- A role with
commandtasks suits one-time jobs - A filter or lookup plugin suits data handling
- The
urimodule suits web service calls
Write a module when the logic repeats across many playbooks or needs careful state checking.
Try This
Copy the checksum module into a library folder. Run it against two different files and compare the results. Edit the module to accept an algorithm option that chooses between sha256 and md5.
Summary
Custom modules extend Ansible when no existing module fits. A Python module uses the AnsibleModule helper to parse arguments and return JSON. Files placed in a library folder load automatically. Accurate change reporting, check mode support, and documentation turn a script into a trustworthy automation tool.
