Skip to content

Customizing Ansible: Ansible Module Creation

Avatar photo

https://www.linkedin.com/in/kumar-nikhil811/

Ansible: is an open-source software for configuration management, provisioning and application deployment, it comes under the Infrastructure as a code, which means by writing a code we can create or deploy our infrastructure on any of the platforms whether its Cloud-like AWS, Azure or hypervisors etc.

Ansible Modules: is reusable & standalone code, its main thing is to perform a certain task on the managed node or target node. Ansible module can be written in any language which can output JSON to standard output but the most used and recommended way to create a custom module using python. Because Ansible is written in python have great support working with JSON data.

Steps to be involved in module creation using Python:

  1. Create a library directory in your environment.
  2. Create your module file in the library directory, library/custom_module.py
  3. You can use ansible.module_utils library for custom module creation
  4. Define the module inputs which we need to take from the users i.e. username, package_name etc.
  5. Write a logic for a module what action needs to be performed by the module and how it returns the output.
  6. Test the module with every test case to ensure it worked as expected by giving different sets of inputs & verify whether the output is correct or not.

Let’s have a look at an example.

In this example, I have created a custom module to install the packages on Linux OS which uses yum as a package installer.

#!/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(cmd, check_rc=True)
    return stdout

def main():
    module = AnsibleModule(
        argument_spec=dict(
            package_name=dict(required=True, type='str'),
        )
    )

    package_name = module.params['package_name']

    if package_name is None:
       module.fail_json(msg='Please provide package name')
    result = install_package(module, package_name)

    module.exit_json(changed=True, msg=result)
if __name__ == '__main__':
    main()
  • The module_utils the library is imported to provide access to the AnsibleModule class & it uses to handle module arguments, inputs, outputs, and errors
  • The install_package the function takes in the module object and the name of the package to install as arguments. It uses the run_command method to execute the yum command and install the package.
  • In the main function, an AnsibleModule object is created with the required input parameters. The install_package function is called with the package name, and the output is returned in the result variable.
  • fail_json is used to handle module failures, when fail_json is called it throws an error in JSON format & exits the module. Like in the above example, we are checking whether the package name is present or not. If the user doesn’t provide the package name it will throw an error.
  • Finally, the exit_json the method is called to return the result of the module execution.

For example, use the above module to install the httpd package, you would include the following task in your playbook:

- hosts: localhost
  tasks:
  - name: install httpd
    yum_install:
       package_name: httpd

Best Practices for custom ansible module creation:

  1. Use the ansible.module_utils library.
  2. Using a clear and concise module name means the module name can clearly indicate what the module does.
  3. Use a consistent and well-documented input format.
  4. Make sure that your module handles errors in a well-maintained manner and error messages should be helpful and informative.
  5. Most important is to test the module thoroughly.

Creating custom ansible modules rewarding and powerful way to automate your infrastructure & is the most powerful way to extend ansible functionality and automate more complex tasks in this way we can also contribute to open source as for some of the tasks there are no such modules are present. By following best practices of module creation you can create high-quality and easy-to-use ansible modules. With the right approach you can unlock the full potential of ansible & so go ahead and give it a try to create your own custom ansible modules.

Thank you for taking the time to read this blog till the end and learn more about creating custom Ansible modules. I hope that you found this information helpful and that it inspires you to explore the possibilities of Ansible automation. Don’t hesitate to reach out if you have any questions or feedback, and be sure to share your experiences and insights with the community.

Thanks again, and happy automating!

Disclaimer:

The views expressed and the content shared in all published articles on this website are solely those of the respective authors, and they do not necessarily reflect the views of the author’s employer or the techbeatly platform. We strive to ensure the accuracy and validity of the content published on our website. However, we cannot guarantee the absolute correctness or completeness of the information provided. It is the responsibility of the readers and users of this website to verify the accuracy and appropriateness of any information or opinions expressed within the articles. If you come across any content that you believe to be incorrect or invalid, please contact us immediately so that we can address the issue promptly.

Avatar photo


https://www.linkedin.com/in/kumar-nikhil811/
Nikhil Kumar is a DevOps Engineer with 5years of experience in the field. Alongside a successful career in technology, he has also cultivated a passion for writing, having authored several articles and blogs on the subjects of DevOps and the Cloud. With a keen interest in exploring the intersection of technology and the written word, he brings a unique perspective to the conversation.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.