Original author: [Nikhil Kumar](https://www.linkedin.com/in/kumar-nikhil811/) in [Customizing Ansible: Ansible Module Creation](https://www.techbeatly.com/customizing-ansible-ansible-module-creation/)

Introduction

Ansible is a powerful open-source software used for configuration management, provisioning, and application deployment. It belongs to the realm of Infrastructure as Code (IaC), where infrastructure is defined and managed through code. Ansible enables you to create and deploy infrastructure on various platforms, including cloud services like AWS and Azure, as well as hypervisors.

One of the key components that makes Ansible so versatile and extensible is the concept of Ansible Modules. These modules are reusable, standalone units of code designed to perform specific tasks on managed or target nodes. While Ansible modules can be written in any language capable of producing JSON output, Python is the most popular and recommended choice. This is because Ansible itself is written in Python, which makes it seamlessly integrate with JSON data.

In this article, we will explore the steps involved in creating custom Ansible modules using Python. We’ll also provide an example to illustrate the process.

Creating Custom Ansible Modules in Python

To create a custom Ansible module in Python, follow these steps:

1. Set Up Your Environment: Begin by creating a library directory in your working environment where you will store your custom modules. This directory will contain the Python files for your modules. Let’s call it library.

2. Create Your Module File: Inside the library directory, create your custom module file, e.g., custom_module.py. This is where you'll write the code for your module.

3. Utilize Ansible Module Utils: Ansible provides a module_utils library that can be used for creating custom modules. Import this library in your module to access the AnsibleModule class, which is used for handling module arguments, inputs, outputs, and errors.

4. Define Module Inputs: Define the module inputs that you want to take from the users. This can include parameters like username, package_name, or any other input required for your module.

5. Write Module Logic: Within your module file, write the logic for the module. This logic should specify what actions the module will perform on the target node and how it will return the output.

6. Testing: Test your module rigorously with various test cases to ensure it functions as expected. Provide different sets of inputs and verify whether the module produces the correct output.

Example: Installing Packages on Linux with a Custom Module

Here’s an example of a custom Ansible module written in Python. This module installs packages on a Linux system using the yum package manager:

```python

#!/usr/bin/python

from ansible.module_utils.basic import AnsibleModule

def install_package(module, package_name):

cmd = "yum install -y " + package_name

rc, stdout, stderr = module.run_command(c