Skip to content
All posts

Ansible Modules: Complete Guide to Every Module Type

Ansible modules are reusable scripts that execute specific tasks on remote systems — from installing packages and managing users to configuring cloud infrastructure and network devices. With over 1,300 modules organized into categories like cloud, system, file, networking, and database, Ansible provides purpose-built automation for nearly every IT operation. This guide breaks down each module type, shows when to use it, and includes working code examples you can test in your own lab environment.

If you're in DevOps, system administration, or cloud infrastructure, mastering Ansible modules will save you time, reduce errors, and improve operational efficiency. This guide covers what Ansible modules are, how they work, every major module category, and troubleshooting tips to help you get the most out of them.

You'll also learn how to set up your own practice environment on CloudMyLab to get hands-on experience.

In this guide:

Ready to automate your network but don't know where to start? Moving from manual network management to Infrastructure as Code feels overwhelming when you're starting from zero. CloudMyLab provides pre-built Ansible playbooks, real-world use case templates, and integrated testing environments that connect directly to EVE-NG or Cisco CML for immediate validation. Get enterprise-grade NetDevOps tools without the learning curve. Contact us to explore automation environments that teach while you build.

What Are Ansible Modules?

Ansible modules are scripts that execute specific tasks on remote systems. These tasks include installing software, managing users, configuring networks, and handling databases.

What makes Ansible modules powerful is their idempotency. Running the same module multiple times won't create unwanted changes. If the system is already in the desired state, nothing happens. This ensures that infrastructure remains consistent and error-free.

Instead of relying on existing Ansible modules, you may define your own logic using Python and write Ansible custom modules.

How Ansible Modules Work

Ansible modules work by executing predefined commands across remote machines. Here's how:

  1. Define the task. Example: Install a package or update a configuration file.
  2. Run the Ansible playbook. The playbook sends commands to the remote machine.
  3. Check idempotency. If the change isn't needed, Ansible skips it.

Here's an example of an Ansible playbook using the user module to create a user:

- name: Create a new user
  hosts: servers
  tasks:
    - name: Add a user named "devops"
      ansible.builtin.user:
        name: devops
        state: present

This playbook ensures that the devops user exists. If the user is already present, no changes are made.

Quick Reference: Ansible Module Types at a Glance

Before diving into each category, here's a comparison table showing all major Ansible module types, their purpose, and common examples:

Module Category Purpose Popular Modules Best For
Cloud Manage AWS, Azure, GCP resources ec2_instance, azure_rm_virtualmachine, gcp_compute_instance Infrastructure as Code (IaC)
System User, service, and cron management user, service, cron, setup Server provisioning
File Copy, template, and manage files copy, template, lineinfile, stat Configuration management
Networking Configure routers, switches, firewalls ios_config, junos_config, iptables Network automation
Database Manage MySQL, PostgreSQL, MongoDB mysql_db, postgresql_user, mongodb_user Database administration
Container Docker, Kubernetes, Podman orchestration docker_container, k8s, podman_container Microservices deployment
Windows Windows services, features, updates win_feature, win_service, win_updates Windows server management
Source Control Git and Subversion automation git CI/CD pipelines
Package Management Install, update, remove packages yum, apt, dnf Software lifecycle
Command Execution Run ad-hoc commands on hosts command, shell Custom operations

Types of Ansible Modules and Their Use Cases

Ansible offers over 1,300 modules, each designed for different IT tasks. Below, we'll go through the most commonly used categories, their use cases, and how they make IT automation easier.

Ansible Cloud Modules

Cloud modules allow you to interact with major cloud providers like AWS, Google Cloud Platform (GCP), Microsoft Azure, and OpenStack. These modules make it easy to automate the provisioning and management of cloud resources, such as launching virtual machines (VMs), creating storage instances, and setting up networks.

Use Case: Automating the provisioning and scaling of cloud infrastructure across multiple platforms like AWS, Google Cloud Platform (GCP), Microsoft Azure, and OpenStack.

These modules help DevOps teams streamline cloud management by automating infrastructure as code (IaC). Instead of manually setting up instances, you can use Ansible to define, deploy, and maintain cloud environments automatically.

Popular modules:

  • amazon.aws.ec2_instance manages AWS EC2 instances.
  • azure.azcollection.azure_rm_virtualmachine creates and manages Azure VMs.
  • google.cloud.gcp_compute_instance manages Google Cloud virtual machines.

Learn more about implementing bare metal services for optimal cloud automation performance.

Scenario: You need to provision virtual machines in AWS without manually clicking through the AWS console.

Solution: Use the EC2 module to automate instance creation.

- name: Launch an AWS EC2 instance
  hosts: localhost
  tasks:
    - name: Create an EC2 instance
      amazon.aws.ec2_instance:
        name: my-instance
        key_name: my-key
        instance_type: t2.micro
        image_id: ami-12345678
        region: us-east-1
        state: present

Ansible System Modules

System modules handle core operating system tasks, such as service management, user creation, and package installation.

Use Case: Managing user accounts, system services, and package installations across multiple Linux or Windows servers.

These modules ensure consistent system setup across thousands of hosts, reducing manual configuration errors.

Ansible user Module

ansible.builtin.user module manages user accounts on managed hosts. It can create, modify, or delete users, set passwords, assign groups, and manage SSH keys. It's essential for automating user management across your infrastructure.

Ansible group Module

ansible.builtin.group module is very similar to the user module, but it works on groups instead of users. It can create, modify, or delete groups on managed hosts.

Ansible service Module

ansible.builtin.service module manages services on managed hosts. It can start, stop, restart, reload, and check the status of services. It's crucial for automating service management, ensuring your applications are running as expected.

Ansible cron Module

The ansible.builtin.cron module allows you to manage cron jobs on managed hosts. You can create, modify, or delete cron jobs, automating the scheduling of tasks.

Ansible setup Module

The setup module gathers facts about managed hosts. These facts include information about the operating system, network interfaces, memory, CPU, and more. These facts can then be used in your playbooks and templates to make your automation more dynamic and adaptable. The ansible.builtin.setup module runs automatically at the start of every playbook unless you disable fact gathering with gather_facts: false.

Scenario: Your team needs to install essential packages on 100 servers.

Solution: Use the apt module (for Ubuntu/Debian) or dnf module (for RHEL-based systems).

- name: Install required software
  hosts: servers
  tasks:
    - name: Install Apache
      ansible.builtin.apt:
        name: apache2
        state: present

Ansible File Modules

File modules help in managing files and directories on remote hosts. These modules allow you to copy files, set permissions, create directories, and ensure that specific files exist or are removed from a system.

Use Case: Setting up directory structures and distributing configuration files to target systems, including copying, creating, modifying, or deleting files and directories.

These modules help maintain file consistency across multiple servers, eliminating the need for manual file transfers.

Ansible copy Module

ansible.builtin.copy module copies files from the control machine (where Ansible is run) to managed hosts. It's crucial for distributing configuration files, application binaries, or other data to your servers. It supports features like setting file permissions, ownership, and timestamps.

Ansible file Module

ansible.builtin.file module is a versatile tool for managing files and directories on managed hosts. It can create, modify, or delete files and directories, set permissions and ownership, and even manage symbolic links. It's often used in conjunction with the copy module to ensure files are placed and configured correctly.

Ansible template Module

ansible.builtin.template module uses Jinja2 templating to dynamically generate files on managed hosts. You define a template file with placeholders (variables) that are populated with data from your Ansible inventory, variables defined in your playbook, or facts gathered from the target systems. This is extremely useful for creating customized configuration files that vary from host to host.

Ansible replace Module

This module searches for a specific pattern within a file and replaces it with another string. It's useful for making targeted changes to configuration files without having to rewrite the entire file.

Ansible lineinfile Module

The ansible.builtin.lineinfile module ensures that a specific line exists in a file, and it can also remove lines. It's helpful for managing configuration files where you need to add or remove specific lines without affecting other content.

Ansible stat Module

The stat module retrieves file or file system status information. This includes details like file size, permissions, modification time, and whether the file exists. You can use this information in conditional tasks to only perform actions if certain criteria are met.

Scenario: You need to copy a configuration file to all application servers.

Solution: Use the copy module.

- name: Deploy configuration file
  hosts: app_servers
  tasks:
    - name: Copy config file
      ansible.builtin.copy:
        src: /local/path/app.conf
        dest: /etc/app/app.conf
        owner: root
        group: root
        mode: '0644'

Ansible Networking Modules

Networking modules are designed to automate the management of network devices such as routers, switches, and firewalls. These modules allow you to configure network interfaces, apply firewall rules, and manage VLANs, routing tables, and more.

Use Case: Automating network devices like routers, switches, and firewalls to configure interfaces, apply firewall rules, manage VLANs, and more.

Network engineers benefit from Ansible's networking modules because they allow for network configurations to be made quickly and accurately. Discover how to boost your network simulation skills using modern automation tools, or explore Netmiko for Python-based network automation as a complementary approach.

Popular modules:

  • cisco.ios.ios_config configures Cisco network devices.
  • juniper.junos.junos_config manages Juniper routers and switches.
  • ansible.builtin.iptables configures firewall rules on Linux servers.

Scenario: You need to configure VLANs and firewall rules on a Cisco switch.

Solution: Use the ios_config module to apply configurations.

- name: Configure VLAN on Cisco Switch
  hosts: switches
  tasks:
    - name: Add VLAN 10
      cisco.ios.ios_config:
        lines:
          - vlan 10
          - name Web_Traffic

Ansible Database Modules

Ansible includes database modules that manage popular databases such as MySQL, PostgreSQL, and MongoDB. These modules allow you to create databases, manage users, configure permissions, and execute SQL commands.

Use Case: Managing databases such as MySQL, PostgreSQL, and MongoDB by creating databases, managing users, executing SQL queries.

Database modules are especially useful when setting up development environments or deploying complex applications that rely on databases. Automating these tasks eliminates the need for manual intervention when setting up or maintaining databases, ensuring that database environments are configured correctly every time.

Popular modules:

  • community.mysql.mysql_db creates and manages MySQL databases.
  • community.postgresql.postgresql_user manages PostgreSQL users.
  • community.mongodb.mongodb_user handles MongoDB access control.

Ansible Container Modules

As containerization becomes increasingly popular, Ansible offers modules to manage container platforms such as Docker, Kubernetes, and Podman. These modules allow you to deploy, manage, and scale containers with ease.

Use Case: Managing container platforms like Docker, Kubernetes, and Podman to deploy and scale containers.

Container modules are essential for DevOps teams working with microservices architectures. They simplify container orchestration and help ensure that containerized applications are deployed consistently across different environments.

Popular modules:

  • community.docker.docker_container manages Docker containers.
  • community.kubernetes.k8s controls Kubernetes objects.
  • containers.podman.podman_container handles Podman containers.

Ansible Windows Modules

Ansible also supports Windows environments, offering modules that automate tasks like managing Windows services, user accounts, file systems, and software packages. With these modules, you can manage Windows servers just as easily as you would manage Linux or Unix servers.

Use Case: Automating software installation, patch management, and user account creation in a Windows environment.

Windows modules make it possible for system administrators to automate tasks like patch management, user creation, and service control across hundreds of Windows servers. This is particularly useful in environments where Windows is the primary operating system, allowing admins to apply consistent configurations without manual intervention.

Popular modules:

  • ansible.windows.win_feature installs Windows features.
  • ansible.windows.win_service manages Windows services.
  • ansible.windows.win_updates automates Windows updates.

For enterprise environments, consider exploring managed POC solutions to test your automation strategies effectively.

Ansible Source Control Modules

Source control modules allow you to automate the interaction with version control systems like Git and Subversion. These modules enable you to clone repositories, manage branches, and interact with codebases directly from Ansible playbooks.

Use Case: Automating the deployment of applications by pulling code from version control systems during infrastructure provisioning.

Source control modules are particularly useful in Continuous Integration (CI) and Continuous Deployment (CD) pipelines. Automating code retrieval and deployment reduces the possibility of human error and ensures that applications are always deployed from the most up-to-date source.

Ansible git Module

The ansible.builtin.git module allows you to interact with Git repositories. You can clone repositories, checkout branches, commit changes, and perform other Git operations. It's essential for automating code deployments and managing application versions.

Ansible Package Management Modules

Ansible provides a suite of modules specifically designed for managing software packages across various operating systems. These modules abstract away the complexities of interacting with different package managers, providing a consistent interface for tasks like installation, updates, and removal.

Use Case: Automating software installation, updates, and removal on Linux servers.

Package management modules are essential for system administrators and DevOps engineers who need to manage software across a large number of servers. They eliminate the need for manual intervention, reducing the risk of errors and ensuring consistency.

Ansible yum Module

This module is used for package management on Red Hat-based systems (e.g., CentOS, RHEL). It can install, update, and remove software packages.

Ansible apt Module

This module is used for package management on Debian/Ubuntu-based systems. It provides similar functionality to the yum module, allowing you to manage software packages.

Ansible dnf Module

This module is a newer package manager used on Fedora and some newer RHEL-based systems. It offers similar functionality to yum and apt.

Ansible Command Execution Modules

Ansible offers modules specifically designed for executing commands on managed hosts. These modules provide flexibility in how commands are run, catering to different needs and use cases. While they offer powerful capabilities, it's important to understand their nuances and use them appropriately.

Use Case: Automating ad-hoc tasks, running scripts, or performing complex operations on remote servers.

Command execution modules are essential for a wide range of automation tasks. They allow you to perform ad-hoc operations, run custom scripts, or execute complex commands that might not be covered by dedicated Ansible modules. They are particularly useful when interacting with applications or systems that don't have a specific Ansible module available.

Ansible command Module

The command module executes a specified command directly on the target host, without involving a shell. This is suitable for simple commands where shell features like piping or redirection are not required. It's generally preferred for its predictability and security.

Ansible shell Module

The shell module executes commands through a shell on the managed host. This allows you to use shell features like piping, redirection, and globbing. While powerful, the shell module should be used with caution, as it can introduce complexities related to shell quoting and escaping. It's generally recommended to use the command module or more specific Ansible modules whenever possible, reserving the shell module for situations where shell features are absolutely necessary.

CloudMyLab's hosted Ansible automation stack includes RedHat AAP Server, GitLab CE, and Rundeck giving you a production-grade environment to test modules across all categories without building infrastructure from scratch. Start your free trial to practice with real enterprise tools.

Ansible Modules vs Plugins: What's the Difference?

A common point of confusion is the difference between Ansible modules and Ansible plugins. Both extend Ansible's capabilities, but they serve different purposes and run in different locations.

Feature Modules Plugins
Where they run On the managed (remote) host On the control node
Purpose Execute tasks (install packages, copy files, configure services) Extend Ansible's core functionality (connections, callbacks, filters)
Invoked by Tasks in playbooks Ansible engine automatically or through Jinja2 filters
Examples copy, user, ec2_instance, ios_config ssh (connection), json_query (filter), debug (callback)
Idempotent Yes (by design) Not applicable. They don't modify remote state
Custom development Write in Python, place in library/ Write in Python, place in appropriate plugin directory

In short: Modules do work on remote hosts. Plugins modify how Ansible itself operates on the control node. If you need to configure a server, use a module. If you need to change how Ansible connects, logs, or processes data, use a plugin.

For details on writing your own modules, see our guide on custom Ansible modules in Python.

How to Find and Install Ansible Modules

Ansible ships with hundreds of built-in modules, but many more are available through Ansible Galaxy collections. Here's how to discover and install the modules you need.

List Available Modules

Check which modules are already installed on your system:

# List all available modules
ansible-doc -l

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

# View documentation for a specific module
ansible-doc ansible.builtin.copy

Install Collection Modules from Ansible Galaxy

Modules beyond the built-in set are distributed through collections on Ansible Galaxy. Install them with ansible-galaxy:

# Install the AWS collection
ansible-galaxy collection install amazon.aws

# Install the Cisco IOS collection
ansible-galaxy collection install cisco.ios

# Install a specific version
ansible-galaxy collection install community.docker:3.4.0

# List installed collections
ansible-galaxy collection list

Built-in vs Collection Modules

Aspect Built-in Modules Collection Modules
Namespace ansible.builtin.* vendor.collection.* (e.g., cisco.ios.*)
Installation Included with Ansible Install via ansible-galaxy
Updates Tied to Ansible releases Updated independently
Examples copy, file, user, command ec2_instance, ios_config, k8s
Maintenance Ansible core team Community or vendor maintained

Since Ansible 2.10, the project shifted most vendor-specific modules out of the core package and into collections. This means you'll likely need to install collections for cloud, networking, and third-party integrations. If you're working in Ansible execution environments, you can bundle the exact collections your team needs into a portable container image.

Troubleshooting Ansible Modules

Even with automation, issues can arise. Here are the most common problems and how to fix them:

  • Missing Modules: If Ansible reports a module not found, it might not be installed. Use ansible-galaxy collection install to install the required collection. Double-check the module name for typos.
  • Incorrect Module Parameters: Supplying incorrect or missing parameters to a module is a frequent cause of errors. Run ansible-doc <module_name> to check the required parameters and their data types.
  • Network Connectivity Problems: Ansible needs to connect to managed hosts. Verify SSH credentials, firewall rules, and DNS resolution. Check your inventory file for correct hostnames or IP addresses.
  • Idempotency Issues: If a module makes unintended changes on subsequent runs, it's not truly idempotent. Use the --check (dry-run) and --diff options with ansible-playbook to preview changes before applying them.
  • Permissions Issues: The Ansible user on the control node and the user on managed nodes must have the necessary privileges. Verify that become: true is set when root access is needed.
  • Syntax Errors: Incorrect YAML syntax in your playbooks is a common pitfall. Use a YAML linter or ansible-playbook --syntax-check playbook.yml to catch errors before running.
  • Version Compatibility: Ensure your Ansible version is compatible with the modules you are using. Older modules might not work correctly with newer Ansible versions. Refer to the module documentation for compatibility information.

Best Practices for Ansible Modules

Organize Your Playbooks

Use roles to structure tasks into reusable components. See our full guide on Ansible playbook best practices for detailed organization strategies.

/roles
  /webserver
    /tasks
    /handlers
    /templates
    /files

Secure Your Automation

Never store passwords in playbooks. Use Ansible Vault to encrypt sensitive data. For a deep dive on managing secrets, read our Ansible Vault and credentials guide.

ansible-vault encrypt_string --stdin-name 'db_password'

Test Before Deployment

Use staging environments to verify automation before running in production. CloudMyLab's hosted lab environments are purpose-built for this kind of safe testing.

Version Control Everything

Store all playbooks in Git for tracking changes and enabling team collaboration.

When setting up your testing environment, understand the differences between EVE-NG vs CML to choose the right platform for your automation needs.

Read more: How you write and structure your Ansible playbooks totally impacts how well they scale. Read our article on the best practices for Ansible playbooks.

Use Fully Qualified Collection Names (FQCNs)

Always reference modules by their full namespace i.e. ansible.builtin.copy instead of just copy. This prevents naming conflicts when multiple collections are installed and makes your playbooks explicit about which module is being called.

Final Thoughts

Ansible modules simplify IT automation, making it easier to deploy infrastructure, configure servers, and manage cloud resources.

By using Ansible modules, teams can:

  • Reduce manual work across server fleets
  • Prevent configuration drift between environments
  • Standardize IT operations with repeatable playbooks

If you're managing a growing IT environment, mastering Ansible modules will help streamline your workflows. Start with the built-in modules, expand into collections for your specific platforms, and use Ansible execution environments to keep your module dependencies portable and reproducible.

Get Hands-On with Ansible Modules

Want to practice Ansible modules in a real-world lab? CloudMyLab provides a fully managed test environment for experimenting with Ansible automation without the risk of breaking production systems.

CloudMyLab provides the perfect environment to test and refine your automation skills. Start your free trial today and get access to our enterprise-grade lab infrastructure, complete with all the tools you need for Ansible automation.

Need help getting started? Our team of experts is here to support you. Contact us to learn more about our managed solutions and professional services.

Learning Resources

Here are some helpful resources for learning more about Ansible:

FAQ

What are the different types of Ansible modules?

Ansible modules fall into ten major categories: cloud (AWS, Azure, GCP), system (user, service, cron), file (copy, template, lineinfile), networking (Cisco IOS, Juniper, iptables), database (MySQL, PostgreSQL, MongoDB), container (Docker, Kubernetes, Podman), Windows (win_feature, win_service), source control (git), package management (yum, apt, dnf), and command execution (command, shell). Each category targets specific IT automation tasks.

How many modules does Ansible have?

Ansible offers over 1,300 modules across its built-in collection and community-maintained Galaxy collections. The exact number changes as new collections are published and updated. You can list all modules available on your system with ansible-doc -l and count them with ansible-doc -l | wc -l.

What is the difference between Ansible modules and plugins?

Modules run on the managed (remote) host and perform tasks like installing packages or copying files. Plugins run on the control node and extend Ansible's core behavior, handling connections (SSH), filtering data (Jinja2 filters), or modifying output (callbacks). Modules are idempotent by design; plugins modify how Ansible itself operates.

What is the Ansible setup module used for?

The ansible.builtin.setup module gathers facts about managed hosts, including operating system details, network interfaces, memory, CPU, and disk information. It runs automatically at the start of every playbook (unless disabled with gather_facts: false) and populates variables you can reference in tasks and templates using the ansible_facts dictionary.

How do I install Ansible modules from Galaxy collections?

Use the ansible-galaxy collection install command followed by the collection namespace. For example: ansible-galaxy collection install cisco.ios installs Cisco IOS modules, and ansible-galaxy collection install amazon.aws installs AWS modules. You can specify versions with collection_name:version syntax and list installed collections with ansible-galaxy collection list.

What is the difference between the command and shell modules?

The command module executes commands directly on the target host without a shell, making it more secure and predictable. The shell module runs commands through a shell (like /bin/sh), allowing piping, redirection, and globbing. Use command by default and reserve shell for cases where you specifically need shell features.

Can Ansible manage Windows servers?

Yes. Ansible includes a full set of Windows modules under the ansible.windows namespace, including win_feature, win_service, win_updates, win_copy, and win_user. Ansible connects to Windows hosts using WinRM (Windows Remote Management) instead of SSH, and playbooks use the same YAML syntax as Linux automation.

What are Ansible built-in modules vs collection modules?

Built-in modules ship with Ansible under the ansible.builtin namespace and include core modules like copy, file, user, and command. Collection modules are maintained separately on Ansible Galaxy under vendor-specific namespaces (e.g., cisco.ios, amazon.aws). Since Ansible 2.10, most vendor-specific modules moved to collections that you install separately with ansible-galaxy.

How do I find which Ansible module to use for a task?

Run ansible-doc -l to list all available modules, or ansible-doc -l | grep <keyword> to search by keyword. For detailed documentation on a specific module, run ansible-doc <module_name>. The official Ansible documentation at docs.ansible.com also provides searchable module indexes organized by collection and category.

What is idempotency in Ansible modules?

Idempotency means running a module multiple times produces the same result as running it once. If the target system is already in the desired state, an idempotent module makes no changes and reports "ok" instead of "changed." This property is critical for reliable automation. You can safely re-run playbooks without worrying about unintended side effects or duplicate changes.