Ansible Curriculum
What Are Modules
At the core of all Ansible executions (whether running playbooks or ad-hoc commands) is the Module. A module is a reusable, standalone script that performs a specific action on a target host, such as installing a package, copying a file, starting a service, or creating a user account.
Ansible playbooks do not define how to perform these tasks. Instead, they specify the desired state of the system by calling a module and passing configuration parameters to it. The module handles the underlying operating-system-specific logic to achieve that state.
In this guide, we will cover what a module is, examine the task execution path, and analyze the declarative nature of Ansible modules.
Module Task Execution Path
When a task executes in a playbook, the Ansible engine processes the module behind the scenes:
The Declarative Nature of Modules
Unlike imperative shell scripts where you write the commands to execute, Ansible modules are declarative. You define the desired final state of your system, and the module checks the current state and makes modifications only if necessary.
For example, if you want to ensure that a directory exists, you call the file module:
When this task runs:
- The module checks if
/var/www/uploadsexists. If it does not, the module creates it. - The module checks the owner, group, and permissions of the directory. If they do not match
www-dataand0755, the module updates them. - If the directory already exists and has the correct settings, the module skips modifications, preserving idempotency.
Supported Module Languages
Most built-in Ansible modules are written in Python. When managing Linux/Unix targets, the control node transfers these Python files to the target hosts, which execute them using their local Python interpreters.
When managing Windows targets, the control node transfers PowerShell scripts instead. These scripts run using the host's built-in PowerShell console.
If you need to write custom modules, you can write them in Python, PowerShell, or any language that can run on the target host and return a structured JSON payload to standard output.
Summary
Ansible modules are the executable units of work that configure your target hosts. By using declarative parameters to specify the desired state of your systems, you can write playbooks that run consistently across different platforms. In the next section, we will cover module categories.