Guozhen AIGlobal AI field notes and model intelligence

English translation

25. Developing Custom Ansible Modules

Published:

Category: Ansible Operations

Read time: 3 min

Reads: 0

Lesson #25Views are counted together with the original Chinese articleImages are preserved from the source page

AI Article Decision Snapshot

Turn the lesson into workflow, model, budget, and security checks before choosing tools.

Use this quick snapshot before leaving the article. It keeps the next search tied to practical AI software, model/API, cost, privacy, and implementation questions.

Workflow fit

Identify the real job behind the article: coding, research, document review, support, analytics, content, or internal automation.

Model or tool decision

Decide whether the next step is a software shortlist, an AI tool comparison, an API platform choice, or a model benchmark.

Budget and usage signal

Estimate seats, API calls, prompt volume, retries, review time, and fallback work before assuming the workflow is cheap.

Security and privacy review

Check whether source code, customer data, private documents, prompts, logs, or embeddings will enter the AI workflow.

In the previous article, we focused on using log files for debugging and troubleshooting—providing valuable assistance when working with Ansible. But during infrastructure automation, how can we further tailor Ansible to meet our specific operational needs—beyond relying solely on built-in modules? The answer lies in developing custom modules.

What Is a Custom Module?

Ansible modules are the fundamental building blocks that execute tasks in Ansible. A custom module enables users to implement domain-specific business logic within Ansible, allowing it to address unique requirements. By writing your own modules, you can extend Ansible’s capabilities and handle specialized tasks not covered by the default module library.

Basic Structure of a Custom Module

A typical Ansible custom module consists of the following components:

  1. Module Name: Usually ends with the .py extension.
  2. Module Docstring: Documents the module’s purpose, supported parameters, and usage.
  3. Parameter Parsing: Uses the AnsibleModule class to parse input arguments.
  4. Business Logic: Contains the core implementation code.
  5. Result Return: Returns structured output—including the changed status, descriptive messages, and other relevant data—in a format Ansible expects.

Getting Started: Creating a Custom Module

Let’s build a simple custom module that checks whether a file exists—and creates it (with optional content) if it does not.

Example Module Code: file_check.py

#!/usr/bin/python

from ansible.module_utils.basic import AnsibleModule
import os

def run_module():
    module_args = dict(
        path=dict(type='str', required=True),
        content=dict(type='str', required=False, default='')
    )

    result = dict(
        changed=False,
        message='',
        path=''
    )
    
    # Initialize the module
    module = AnsibleModule(argument_spec=module_args)

    # Extract parameters
    file_path = module.params['path']
    file_content = module.params['content']

    # Check if file exists
    if not os.path.exists(file_path):
        # Create the file and write content if it doesn't exist
        with open(file_path, 'w') as f:
            f.write(file_content)
        result['changed'] = True
        result['message'] = 'File created.'
    else:
        result['message'] = 'File already exists.'

    result['path'] = file_path

    # Return result to Ansible
    module.exit_json(**result)

if __name__ == '__main__':
    run_module()

Explanation:

  • This module uses AnsibleModule to define two parameters: path (the target file path, required) and content (optional string to write into the file).
  • os.path.exists() checks whether the specified file exists. If not, the module creates it and writes the provided content.
  • Finally, module.exit_json() returns a standardized JSON response containing the changed status and a human-readable message.

Using the Custom Module

Save your module to Ansible’s module library directory—for example, /usr/share/ansible/plugins/modules/file_check.py. Once installed, you can invoke it directly in an Ansible Playbook.

Example Playbook: file_check.yml

---
- name: Example Playbook for custom module
  hosts: localhost
  tasks:
    - name: Check and create a file
      file_check:
        path: /tmp/testfile.txt
        content: "This is a test file."
      register: result

    - debug:
        var: result

Running the Playbook

Execute the playbook using:

ansible-playbook file_check.yml

Common Issues and Debugging

During custom module development, you may encounter issues such as “module not found,” parameter parsing failures, or malformed return values. Leveraging Ansible’s logging features remains highly effective for diagnosing these problems—ensuring your result dictionary contains accurate, well-structured data.

As discussed earlier, mastering log file analysis significantly accelerates issue identification. That same skillset applies directly to custom module development: logs remain a powerful diagnostic tool throughout the process.

Summary

In this section, we learned how to develop a simple Ansible custom module and integrate it into a Playbook. With this foundational knowledge, you can now design more sophisticated, domain-specific modules aligned precisely with your operational requirements.

In the next article, we’ll explore Ansible Tower and AWX—powerful enterprise-grade platforms that further enhance your infrastructure automation capabilities.

Apply This Lesson

Turn this article into AI software, model, API, and security decisions.

English Article FAQ

Use this article as evidence before choosing AI tools

How should I use this AI Tutorials article?

Use it as the implementation or learning layer, then connect the idea to AI software buyer guides, tool comparisons, benchmarks, API choices, and security checks before making a production decision.

Is this English article different from the Chinese original?

The English edition is localized for global AI readers while preserving the original diagrams, screenshots, prompts, code examples, and source context from the Chinese article.

What should I read after 25. Developing Custom Ansible Modules?

Continue with AI Software Buyer Guides, AI Tools Workbench, Best AI Coding Agents, AI Model Benchmarks, OpenAI vs Anthropic API, or LLM Security Tools depending on the decision you need to make.

Can this article alone choose an AI product or model?

No. Treat the article as evidence and context, then validate fit with pricing, privacy requirements, integration effort, benchmark results, workflow tests, and fallback planning.

Continue

Keep reading from here

Browse English site

Reader Messages

Reader messages

Questions, corrections, extra sources, or hands-on results can be left here. No login is required.

Max 800 characters

To reduce spam, each message is checked for length, link count, and posting frequency.

0/800

Messages

0 messages
Loading messages...