NetwNETW
Ansible course
CHAPTER 05

Modules

The building blocks that do the actual work

10 min read3 sections
In this chapter
What are modules?Common modulesIdempotency

01What are modules?

Modules are the building blocks of Ansible. Each module does one thing: install a package, start a service, copy a file. You call a module in a task, and Ansible runs it on the target. Ansible has hundreds of built-in modules. Prefer modules over shell commands; modules are idempotent and handle edge cases.

Why this exists

Idempotency is the golden rule. A task is idempotent if running it twice produces the same result as running it once. If nginx is already installed, the apt module does nothing. If it is not installed, it installs it.

02Common modules

These are the modules you will use most often.

  • ▸apt/yum/dnf: install, remove, or update packages
  • ▸service: start, stop, restart, enable, or disable services
  • ▸copy: copy a file from control node to target
  • ▸template: copy a file with Jinja2 variable substitution
  • ▸file: create directories, set permissions, delete files
  • ▸user: create, modify, or remove user accounts
  • ▸command/shell: run arbitrary commands (use sparingly)
  • ▸git: clone or update a Git repository
  • ▸debug: print a message or variable value
  • ▸lineinfile: ensure a line exists in a file

03Idempotency

Idempotency is what makes Ansible safe to run repeatedly. Modules check the current state before making changes. If the desired state is already met, they do nothing. This is the difference between Ansible and a shell script.

Mental model

A light switch is idempotent: flipping it to ON when it is already ON does nothing. A shell script that runs 'apt install nginx' is not idempotent: it reinstalls every time.

Check your understanding
0 / 1 correct
What makes a task idempotent?