Ansible Custom Module
A module is a reusable, standalone script that Ansible runs. They are small pieces of python code that can be triggered from the yaml in a playbook.
Why create a custom module?
If you need functionality that is not available in any of the thousands of Ansible modules found in collections, you can easily write your own custom module using any programming language.
After you create a module, you must add it locally to the appropriate directory so that Ansible can find and execute it.
Creating a custom module
In this guide, we will create a simple custom module that will add a person’s name and age to a file which resides on webserver1.
For this task, we will have below playbook:
- name: Test Jinja2 Templating hosts: webserver1 tasks: - userdata: name=Gaurav age=18
Inside tasks, userdata will be the custom module which we will define in python language as userdata.py which takes arguments name and age. The name of the custom module and the filename should be the same.
Let’s have a look at the userdata.py script:
#!/usr/bin/python import json from ansible.module_utils.basic import AnsibleModule import sys def main(): module = AnsibleModule( argument_spec = dict( name = dict(required=True, type='str'), age = dict(required=True, type='str'), ) ) name = module.params['name'] age = module.params['age'] data = dict( output="your data has stored successfully :-) ", ) try: file = open("/tmp/userdata.txt","r") file.write(name+ "," + age + "\n") module.exit_json(changed=True, success=data,msg=data) except Exception as e: module.fail_json(msg='something went wrong. :-(') if __name__ == '__main__': main()
In this script, we have to import AnsibleModule. And we need to define the variables name and age.
The output of this file on successful execution has to be defined in JSON format.
This python script will -
Open the “/tmp/userdata.txt” file in write mode
Write name and age in it
And will throw an exception in case of any error
Running the playbook with Custom module
By default, Ansible uses the modules from its default location. To make it use the custom module that you created, set the path of the module script by exporting it using below command:
export ANSIBLE_LIBRARY=</path/to/module script>
Once the custom module path is set, run the playbook using below command:
Verifying the same:
You can check more in detail about the custom modules in Ansible Documentation. There is much more that can be done with custom modules.