DevOps
Infrastructure as Code
Mastering Ansible Modules

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:

CategoryModulesPurpose
Packagesapt, yum, dnfInstall, update, or remove software.
Servicesservice, systemdStart, stop, restart, or enable services.
Filescopy, file, templateTransfer files and manage permissions.
Commandcommand, shell, rawRun arbitrary terminal commands.
Systemsuser, group, hostnameManage 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 missing

Common 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: present

2. 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 command for most tasks: It is safer and does not process shell variables or redirections (like > or |).
  • Use shell only when you specifically need features like piping or shell environment variables.