Mastering Ansible Modules
Ansible Modules are the discrete units of code that perform the actual heavy lifting on your remote nodes. They are the small programs that allow Ansible to manage users, install packages, copy files, and configure services without you having to write manual shell scripts.
🔄 The Module Life Cycle
Ansible follows a clean "Push, Execute, and Cleanup" workflow for every task it runs.
📂 Categories of Essential Modules
Ansible comes with thousands of built-in modules. Most daily DevOps tasks revolve around these core categories:
| Category | Modules | Purpose |
|---|---|---|
| Packages | apt, yum, dnf | Install, update, or remove software. |
| Services | service, systemd | Start, stop, restart, or enable services. |
| Files | copy, file, template | Transfer files and manage permissions. |
| Command | command, shell, raw | Run arbitrary terminal commands. |
| Systems | user, group, hostname | Manage user accounts and system identity. |
🛠️ Syntax & Idempotency
Every module follows a standard key-value parameter syntax. The most important parameter is often state.
- name: Example Module Usage
apt:
name: nginx
state: present # present = install if missingCommon state Values:
present: Ensure the resource exists (install if missing).absent: Ensure the resource does not exist (remove if present).started/stopped: Common for service modules.restarted: Forces a restart.
🚀 Practical Examples
1. Managing Users and Groups
- name: Create a new developer user
user:
name: devuser
group: developers
shell: /bin/bash
state: present2. File Transfer and Permissions
- name: Deploy configuration file
copy:
src: /local/path/nginx.conf
dest: /etc/nginx/nginx.conf
owner: root
group: root
mode: '0644'3. Running Shell Commands (The Power Tool)
Use the shell module when there isn't a specialized module for your task.
- name: Run a custom backup script
shell: /usr/local/bin/backup.sh >> /var/log/backup.log[!WARNING] Command vs. Shell
- Use
commandfor most tasks: It is safer and does not process shell variables or redirections (like>or|).- Use
shellonly when you specifically need features like piping or shell environment variables.