Skip to main content

Exploring Ansible Modules

Learn all about modules in Ansible. What are modules, why, and how are they used? How you can use them to improve your Ansible workflow.

Warp Terminal

Ansible is a powerful automation tool that simplifies the management and configuration of systems.

At the heart of Ansible's functionality are modules, which are reusable scripts designed to perform specific tasks on remote hosts.

These modules allow users to automate a wide range of tasks, from installing packages to managing services, all with the aim of maintaining their systems' desired state.

This article will explain what Ansible modules are, how to use them, and provide real-world examples to demonstrate their effectiveness.

What is an Ansible Module?

An Ansible module is a reusable, standalone script that performs a specific task or operation on a remote host. Modules can manage system resources like packages, services, files, and users, among other things. They are the building blocks for creating Ansible playbooks, which define the automation workflows for configuring and managing systems.

Ansible modules are designed to be idempotent, meaning they ensure that the system reaches a desired state without applying changes that are unnecessary if the system is already in the correct state. This makes Ansible operations predictable and repeatable.

Modules can be written in any programming language, but most are in Python. Ansible ships with a large number of built-in modules, and there are also many community-contributed modules available.

Additionally, you can write custom modules to meet specific needs.

Here's a simple syntax to get you started:

---
- name: My task name
  hosts: group_name  # Group of hosts to run the task on
  become: true      # Gain root privileges (if needed)
  module_name:
    arguments:       # Module specific arguments

This is a basic template for defining tasks in your Ansible playbooks.

Ansible Modules - Real-world examples

Let's examine some real-world examples to understand how modules work in action.

Example 1: Installing a package

Let's use the yum module to install the Apache web server on a RockyLinux.

---
- name: Install Apache web server
  hosts: webservers
  tasks:
    - name: Install httpd package
      yum:
        name: httpd
        state: present

In this playbook:

  • The hosts directive specifies that this playbook will run on hosts in the webservers group.
  • The yum module is used to ensure that the httpd package is installed.

Let's run the above playbook:

ansible-playbook playbook.yml

After the successful playbook execution, you will see the following output: