Ansible

Ansible Custom Modules

Ansible is one of the most powerful automation tools of the modern age. It comes packed with many tools and modules out of the box, allowing you to configure a wide variety of devices and automate many tasks.

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:

ansible_project/
├── 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:

#!/usr/bin/python3
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:

$ ansible-playbook playbook.yml

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:

TASK [Display response] *************************<em>***</em>*
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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list