In this section, we will explore how to create custom modules in Ansible. Custom modules allow you to extend Ansible's functionality to meet specific needs that are not covered by the built-in modules.

Objectives

By the end of this section, you will:

  • Understand the structure of an Ansible module.
  • Learn how to create a simple custom module.
  • Know how to test and use your custom module in a playbook.

Key Concepts

  1. Ansible Module Structure

An Ansible module is essentially a script that Ansible runs on your managed nodes. The script can be written in any language that the managed node can execute, but Python is the most commonly used language.

  1. Module Arguments

Modules accept arguments that define their behavior. These arguments are typically passed in JSON format.

  1. Return Values

Modules return results in JSON format, which Ansible uses to determine the success or failure of the module execution.

Creating a Simple Custom Module

Step 1: Define the Module

Create a Python script for your custom module. For this example, we'll create a module that simply echoes a message.

#!/usr/bin/python

import json
import sys

def main():
    # Read arguments passed to the module
    args = json.loads(sys.stdin.read())
    
    # Extract the message argument
    message = args.get('message', 'Hello, World!')
    
    # Prepare the result
    result = {
        'changed': False,
        'message': message
    }
    
    # Print the result in JSON format
    print(json.dumps(result))

if __name__ == '__main__':
    main()

Step 2: Make the Script Executable

Ensure the script is executable by running the following command:

chmod +x my_custom_module.py

Step 3: Test the Module

You can test the module by running it directly and passing JSON input:

echo '{"message": "Hello, Ansible!"}' | ./my_custom_module.py

You should see the following output:

{
    "changed": false,
    "message": "Hello, Ansible!"
}

Step 4: Use the Module in a Playbook

To use your custom module in a playbook, you need to specify the path to the module script.

---
- name: Test custom module
  hosts: localhost
  tasks:
    - name: Run custom module
      my_custom_module:
        message: "Hello from custom module"
      register: result

    - name: Print result
      debug:
        var: result.message

Step 5: Run the Playbook

Execute the playbook to see your custom module in action:

ansible-playbook -i localhost, -c local test_custom_module.yml

You should see the message "Hello from custom module" printed in the output.

Common Mistakes and Tips

Common Mistakes

  • Incorrect JSON Handling: Ensure that your module correctly reads and writes JSON.
  • File Permissions: Make sure your module script is executable.
  • Path Issues: When specifying the path to the module in the playbook, ensure the path is correct.

Tips

  • Use AnsibleModule Helper: For more complex modules, consider using the AnsibleModule helper from the ansible.module_utils.basic library to handle argument parsing and result formatting.
  • Documentation: Document your module's arguments and return values to make it easier for others to use.

Conclusion

Creating custom modules in Ansible allows you to extend its functionality to meet your specific needs. By understanding the structure of a module, how to handle arguments and return values, and how to integrate the module into a playbook, you can create powerful custom solutions. Practice creating and testing custom modules to become proficient in extending Ansible's capabilities.

© Copyright 2024. All rights reserved