However, while Ansible has a rich collection of modules to perform a wide range of tasks, sometimes the need arises to write a custom module that is tailored to specific needs.
In this tutorial, we will walk you through the process of building a custom Ansible module in Python.
What Is an Ansible Custom Module?
A custom module in Ansible is a script that can be executed directly to perform a task. Ansible allows us to write the script in any supported language. However, since Ansible natively supports it, Python is an excellent choice.
Prerequisites:
- Basic knowledge of Python programming
- Installed Ansible on your machine
- An Ansible playbook or ad-hoc command environment to test the module
Step 1: Environment Setup
The first step is to ensure that we have Ansible installed and functional. Next, create a directory to store the modules as follows:
├── library
└── playbook.yml
1 directory, 1 file
Step 2: Create a Custom Module
The next step is to create the file for our module. Inside the library/directory, create a new file with the module’s name. In our case, we call the module as “hello.py”.
Edit the file and add the source code for your module. In our case, we have a simple module that prints “hello”. The source code is as follows:
from ansible.module_utils.basic import AnsibleModule
def run_module():
# module specs
module_args = dict(
name=dict(type='str', required=True)
)
# init ansible module
module = AnsibleModule(
argument_spec=module_args,
supports_check_mode=True
)
# Get the input arguments
name = module.params['name']
# print hello
result = f"Hello, {name}!"
# end module and return
module.exit_json(changed=True, message=result)
def main():
run_module()
if __name__ == '__main__':
main()
Step 3: Using the Custom Module in a Playbook
Once we defined and finished the module’s source code, we can use it in a playbook.
Edit the “playbook.yml” file and add the definitions that call the module that we defined in the previous section.
- hosts: localhost
tasks:
- name: Use my custom module
hello:
name: "Linuxhint"
register: response
- name: Display response
debug:
var: response.message
In the previous playbook, we define a task that uses our custom module (hello) and passes a parameter (name) to it. The result of this module is registered to a variable response which we display in the next task.
We can then run the resulting playbook as follows:
This should import the “hello” module and perform the defined instructions. In this case, we display a hello message as shown in the following output:
ok: [localhost] => {
"response.message": "Hello, Linuxhint!"
}
Conclusion
This post explored the fundamentals of working with Ansible and Python capabilities to define the custom Ansible modules. Custom modules are an excellent feature for extending Ansible’s power to meet any specific requirement that we might have.