AnsiblePilot — Master Ansible Automation

AnsiblePilot is the leading resource for learning Ansible automation, DevOps, and infrastructure as code. Browse over 1,400 tutorials covering Ansible modules, playbooks, roles, collections, and real-world examples. Whether you are a beginner or an experienced engineer, our step-by-step guides help you automate Linux, Windows, cloud, containers, and network infrastructure.

Popular Topics

About Luca Berton

Luca Berton is an Ansible automation expert, author of 8 Ansible books published by Apress and Leanpub including "Ansible for VMware by Examples" and "Ansible for Kubernetes by Example", and creator of the Ansible Pilot YouTube channel. He shares practical automation knowledge through tutorials, books, and video courses to help IT professionals and DevOps engineers master infrastructure automation.

Ansible Modules: Complete Guide to Built-in & Custom Modules

By Luca Berton · Published 2024-01-01 · Category: installation

Complete guide to Ansible modules. Understand built-in modules, collection modules, how to find, use, and create custom modules for automation.

Ansible modules are the foundation of Ansible's automation capabilities. They are small programs that perform specific tasks, enabling you to automate everything from software installation to cloud provisioning. This article explains what Ansible modules are, their types, and how to use them in playbooks.

What Are Ansible Modules?

Ansible modules are standalone units of code executed by Ansible to perform specific tasks on managed nodes. These tasks can range from system configuration and file manipulation to cloud infrastructure provisioning.

Modules are also referred to as "task plugins" or "library plugins" and are invoked in Ansible playbooks as tasks.

Key Features of Ansible Modules:

  • Idempotence: Modules are designed to achieve the same result regardless of how many times they are run.
  • Agentless Execution: Modules execute over SSH or WinRM without requiring agents on the target systems.
  • Extensibility: You can create custom modules to extend functionality.

Types of Ansible Modules

Ansible includes a wide variety of modules categorized by their functionality:

1. Core Modules

  • Maintained by the Ansible team and included in all installations.
  • Examples: file, user, service, package.

2. Cloud Modules

  • Manage resources in cloud platforms like AWS, Azure, and Google Cloud.
  • Examples: amazon.aws.ec2, azure.azcollection.azure_rm_vm.

3. Networking Modules

  • Automate network device configurations.
  • Examples: ios_config, junos_config, nxos_command.

4. Database Modules

  • Manage databases like MySQL, PostgreSQL, and MongoDB.
  • Examples: mysql_user, postgresql_db.

5. Custom Modules

  • User-created modules to meet specific requirements.

Anatomy of an Ansible Module Task

Here’s an example task using the apt module to install Nginx:

- name: Install Nginx
  apt:
    name: nginx
    state: present

Task Components:

  • name: A description of the task.
  • apt: The module used for the task.
  • name: The package to be installed.
  • state: Ensures the package is installed.

Commonly Used Ansible Modules

  1. File Management
  2. copy: Copy files to target machines.
  3. template: Deploy Jinja2 templates.
  4. file: Manage file and directory properties.
  1. Service Management
  2. service: Start, stop, and manage services.
  3. systemd: Interact with systemd services.
  1. Package Management
  2. yum: Manage packages on RHEL-based systems.
  3. apt: Manage packages on Debian-based systems.
  1. Cloud and Virtualization
  2. ec2: Provision AWS EC2 instances.
  3. vmware_guest: Manage VMware virtual machines.
  1. User Management
  2. user: Create, update, or delete user accounts.
  3. group: Manage user groups.

Writing Custom Ansible Modules

Custom modules can be written in Python, PowerShell, or any scripting language. A simple Python module follows this structure:

#!/usr/bin/python

from ansible.module_utils.basic import AnsibleModule

def main():
    module = AnsibleModule(
        argument_spec=dict(
            name=dict(type='str', required=True)
        )
    )
    response = {"message": f"Hello {module.params['name']}!"}
    module.exit_json(changed=False, **response)

if __name__ == '__main__':
    main()

See also: Automating Jenkins Installation with Ansible

Using Modules in Playbooks

Modules are called in tasks within a playbook. Example playbook to ensure a service is running:

- hosts: webservers
  tasks:
    - name: Ensure Nginx is running
      service:
        name: nginx
        state: started

Conclusion

Ansible modules are the essential building blocks of Ansible automation. Whether you're managing servers, deploying applications, or provisioning cloud resources, modules enable you to perform tasks efficiently and consistently.

Explore More About Ansible Modules in the Official Documentation

See also: Ansible 2.17.0-rc1: Elevating Automation with ‘Gallows Pole’

Module Categories

CategoryExamplesUse Case
Systemuser, group, service, cronOS configuration
Filescopy, template, file, lineinfileFile management
Packagesapt, yum, pip, snapSoftware installation
Cloudec2_instance, azure_rm_virtualmachineCloud resources
Networkios_config, nxos_commandNetwork devices
Databasemysql_db, postgresql_userDatabase management
Windowswin_copy, win_service, win_userWindows automation

Using Modules

# In playbooks
- name: Install nginx
  ansible.builtin.apt:
    name: nginx
    state: present
  become: true

# Ad-hoc commands
# ansible all -m ping
# ansible all -m shell -a "uptime"
# ansible all -m copy -a "src=file.txt dest=/tmp/file.txt"

FQCN (Fully Qualified Collection Name)

# Recommended: use FQCN
- ansible.builtin.copy:
    src: config.yml
    dest: /etc/app/config.yml

# Short name (works but deprecated for non-builtin)
- copy:
    src: config.yml
    dest: /etc/app/config.yml

# Collection modules
- community.general.ufw:
    rule: allow
    port: 22

- amazon.aws.ec2_instance:
    name: web-server
    instance_type: t3.micro

See also: Can Ansible Be Used to Manage Windows Systems?

Module Return Values

- name: Create user
  ansible.builtin.user:
    name: deploy
  register: user_result

- debug:
    msg: |
      Changed: {{ user_result.changed }}
      UID: {{ user_result.uid }}
      Home: {{ user_result.home }}

Find and Explore Modules

# List all available modules
ansible-doc -l

# Search modules
ansible-doc -l | grep docker

# Module documentation
ansible-doc ansible.builtin.copy

# Show module parameters (short)
ansible-doc -s ansible.builtin.copy

Key Built-in Modules

ModulePurpose
copyCopy files to remote
templateRender Jinja2 templates
fileManage files/dirs/links
lineinfileEdit lines in files
apt / yumPackage management
serviceManage services
user / groupUser management
command / shellRun commands
uriHTTP requests
debugPrint messages
set_factSet variables
assertValidate conditions

Install Collection Modules

ansible-galaxy collection install community.general
ansible-galaxy collection install amazon.aws
ansible-galaxy collection install community.docker

Write a Custom Module

#!/usr/bin/python
# library/hello.py
from ansible.module_utils.basic import AnsibleModule

def main():
    module = AnsibleModule(
        argument_spec=dict(
            name=dict(type='str', required=True),
        )
    )
    module.exit_json(changed=False, msg=f"Hello, {module.params['name']}!")

if __name__ == '__main__':
    main()
- hello:
    name: World
  register: result
- debug: var=result.msg  # "Hello, World!"

FAQ

Modules vs Plugins?

Modules are a type of plugin that execute tasks on remote hosts. Other plugins (callback, lookup, filter) extend Ansible's core functionality.

How do modules execute?

Ansible copies the module to the remote host, executes it with Python, captures JSON output, then removes the module. Exception: raw module runs without Python.

What's the difference between command and shell?

command runs without a shell (no pipes, redirects). shell runs through /bin/sh (supports |, >, &&). Prefer command for security; use shell when you need shell features.

What Are Modules?

Modules are discrete units of code that Ansible executes on managed nodes. Each module handles a specific task:

# Each task uses one module
- ansible.builtin.apt:        # Package management
    name: nginx
- ansible.builtin.service:     # Service management
    name: nginx
    state: started
- ansible.builtin.template:    # File templating
    src: config.j2
    dest: /etc/app.conf

Find Modules

# List all available modules
ansible-doc -l

# Search for modules
ansible-doc -l | grep docker

# View module documentation
ansible-doc ansible.builtin.copy

# List modules in a collection
ansible-doc -l community.general

Common Module Categories

Files

- ansible.builtin.copy:       # Copy files
- ansible.builtin.template:   # Jinja2 templates
- ansible.builtin.file:       # File properties
- ansible.builtin.lineinfile: # Edit lines
- ansible.builtin.get_url:    # Download files
- ansible.builtin.unarchive:  # Extract archives

Packages

- ansible.builtin.apt:        # Debian/Ubuntu
- ansible.builtin.yum:        # RHEL/CentOS
- ansible.builtin.dnf:        # Fedora
- ansible.builtin.pip:        # Python packages
- ansible.builtin.package:    # OS-agnostic

System

- ansible.builtin.service:    # Manage services
- ansible.builtin.systemd:    # systemd specific
- ansible.builtin.user:       # User accounts
- ansible.builtin.group:      # Groups
- ansible.builtin.cron:       # Cron jobs
- ansible.builtin.hostname:   # Set hostname

Commands

- ansible.builtin.command:    # Run commands (no shell)
- ansible.builtin.shell:      # Run through shell
- ansible.builtin.raw:        # Raw SSH command
- ansible.builtin.script:     # Run local script remotely
- ansible.builtin.expect:     # Interactive commands

Networking & Cloud

- amazon.aws.ec2_instance:    # AWS EC2
- azure.azcollection.*:       # Azure resources
- community.docker.*:         # Docker containers
- ansible.netcommon.*:        # Network devices

Module Return Values

- copy:
    src: file.txt
    dest: /tmp/file.txt
  register: result

# result contains:
# .changed — whether the task made changes
# .failed — whether it failed
# .dest — destination path
# .checksum — file checksum
# .size — file size

Module Parameters

# Required vs optional
- apt:
    name: nginx          # Required
    state: present       # Optional (default: present)
    update_cache: true   # Optional

# Free-form (shorthand)
- command: /opt/script.sh
# Equivalent to:
- command:
    cmd: /opt/script.sh

Collections vs Built-in

# Built-in (always available)
- ansible.builtin.copy:

# Collection (must install first)
- community.docker.docker_container:
- amazon.aws.ec2_instance:

# Install collections
# ansible-galaxy collection install community.docker

FAQ

How many modules are there?

Thousands — ansible.builtin has ~70 core modules. Collections add thousands more for cloud, networking, databases, etc.

Can I use modules without a playbook?

Yes — ad-hoc commands: ansible all -m ping or ansible web1 -m apt -a "name=nginx" -b

What language are modules written in?

Mostly Python, but modules can be any executable (Bash, Go, Ruby, etc.).

Category: installation

Browse all Ansible tutorials · AnsiblePilot Home