In the previous lesson you used a dozen modules (command, shell, copy, apt, service, user, reboot, setup…) to administer Aurora Store with ad hoc commands. Modules are Ansible's units of work: every task you write in a playbook, every role and every ad hoc command ends up running a module. Ansible ships thousands of them, and knowing which one to choose and how to use it correctly is one of the most valuable skills you can have. In this lesson you will see exactly what a module is, take a tour of the most widely used ones in ansible.builtin organized by category, learn to read their documentation with ansible-doc (parameters, default values, return values and check mode support) and interpret what they return. We will keep working with ad hoc commands on Aurora: playbooks arrive in Module 3.

Contents

  1. What a module is
  2. Module categories and the most widely used ones in ansible.builtin
  3. Package modules
  4. File modules
  5. Service, user and group modules
  6. Modules for running commands
  7. Modules for downloading, unpacking and querying
  8. Reading the documentation with ansible-doc
  9. Common return values
  10. Idempotent and non-idempotent modules
  11. Check mode support

  1. What a module is

A module is a small program (almost always written in Python) that performs one specific task on the managed host: installing a package, creating a file, managing a user… You already know its life cycle from lesson 1.4:

sequenceDiagram
    participant C as Control node
    participant H as Managed host (web1)
    C->>C: Packages the module + arguments (AnsiballZ)
    C->>H: Copies the package over SSH
    H->>H: Python runs the module
    H->>H: Compares current and desired state, acts if needed
    H-->>C: Returns a result in JSON
    C->>C: Displays the result (ok / changed / failed)

Characteristics of a good module:

  • It takes named arguments (name=htop state=present).
  • It describes a desired state, not a sequence of commands: it first checks how the system is and only acts if necessary.
  • It returns JSON describing what happened (changed, failed, messages, data).
  • It's self-contained: it doesn't depend on other modules or on earlier tasks.

Modules and action plugins: some modules also have a part that runs on the control node (an action plugin). For example, debug runs only on the control node (which is why it's instantaneous), and copy reads the local file on the control node before sending it. For you, as a user, they're used the same way. Plugins are covered in Module 10.

  1. Module categories and the most widely used ones in ansible.builtin

The modules in the ansible.builtin collection ship with ansible-core and are always available. There are many more in other collections (community.general, ansible.posix, amazon.aws…), which you will see in the next lesson.

Category Most widely used modules (ansible.builtin.) Purpose
Packages package, apt, dnf, apt_repository, pip Installing, upgrading and removing software
Files copy, file, template, lineinfile, blockinfile, fetch, replace Creating and modifying files and directories
Services service, systemd_service Starting, stopping and enabling services
Users user, group, authorized_key* Accounts, groups and SSH keys
Commands command, shell, raw, script Running programs when there's no specific module
Downloads and code get_url, uri, unarchive, git Downloading files, calling APIs, deploying code
Queries stat, setup, package_facts, service_facts Getting information without changing anything
Control and utilities debug, assert, fail, wait_for, pause, reboot Debugging, validating and controlling execution
Network and cloud (in collections: ansible.netcommon, cisco.ios, amazon.aws, azure.azcollection…) Network devices and cloud providers

* authorized_key lives in the ansible.posix collection, not in ansible.builtin: it's a good example of why you should always write the full name, as you will see in the next lesson.

List every available module or filter by name:

ansible-doc -l | wc -l                     # thousands of modules
ansible-doc -l | grep '^ansible.builtin'   # only those included in ansible-core

  1. Package modules

Module System When to use it
ansible.builtin.package Any (detects the package manager) Simple installations in environments with different distributions
ansible.builtin.apt Debian/Ubuntu When you need apt-specific options (update_cache, cache_valid_time, upgrade…)
ansible.builtin.dnf RHEL, Rocky, Fedora dnf-specific options (enablerepo, modules…)

package is a generic layer: it uses apt on Ubuntu and dnf on Rocky Linux, but it only accepts the common parameters (name, state, use). Since Aurora runs only Ubuntu, we will use apt when we need its options and package when the basic ones are enough.

# Generic: valid on any distribution
ansible aurora -m ansible.builtin.package -a 'name=curl state=present' -b

# apt-specific: several packages at once and a controlled cache
ansible aurora -m ansible.builtin.apt -a 'name=curl,vim state=present update_cache=true cache_valid_time=3600' -b

Both report SUCCESS with no changes: curl and vim come with Ubuntu 24.04. It's a safe way to ensure something is there, without worrying about whether it already was.

  1. File modules

4.1 file: directories, permissions and links

file doesn't copy contents: it manages the existence and properties of files, directories and links. Create the root directory of Aurora's website using the aurora_web_root variable you defined in group_vars/webservers.yml:

ansible webservers -m ansible.builtin.file \
  -a 'path={{ aurora_web_root }} state=directory owner=deploy group=deploy mode=0755' -b
  • path={{ aurora_web_root }}: Ansible replaces the variable with /var/www/aurora on each host.
  • state=directory: it must exist as a directory (it's created, along with its parents, if it doesn't exist).
  • owner=deploy group=deploy: owned by the deploy user you created in lesson 2.4.
  • mode=0755: permissions.
state Result
directory Directory (creates intermediate ones)
file Checks/adjusts an existing file (doesn't create it)
touch Creates an empty file or updates its timestamp (always changed)
link / hard Symbolic / hard link (src= is the source)
absent Deletes a file or directory (recursively!)

4.2 copy and template

copy (you've already used it) copies a file or some content as is. ansible.builtin.template does the same, but the source file is a Jinja2 template in which Ansible substitutes variables, conditions and loops: it's how you generate, for example, Aurora's nginx configuration from nginx_port and aurora_domain. You will study it in depth in the "Jinja2 Templates" lesson in Module 5.

4.3 lineinfile: a specific line

lineinfile ensures that one line is (or isn't) in a file, optionally replacing the one that matches a regular expression. It's ideal for targeted changes in files you don't manage in full.

See what would happen if you disallowed password-based SSH access (simulation only, don't apply it):

ansible web1 -m ansible.builtin.lineinfile \
  -a "path=/etc/ssh/sshd_config regexp='^#?PasswordAuthentication' line='PasswordAuthentication no'" \
  -b --check --diff
  • regexp: looks for a line starting with PasswordAuthentication (commented out or not).
  • line: the line that must end up in the file. If regexp finds a match, it replaces it; if not, it appends line at the end.

SSH hardening is covered in the "Security Best Practices" lesson in Module 9. Any security configuration change on real systems should be reviewed by a professional and tested first in a test environment: a mistake in sshd_config can lock you out.

4.4 blockinfile: a block of lines

blockinfile inserts a block delimited by markers, so it can update it later without duplicating it. Use it so Aurora's servers know each other by name in /etc/hosts:

ansible aurora -m ansible.builtin.blockinfile -a 'path=/etc/hosts block="192.168.56.11 web1
192.168.56.12 web2
192.168.56.21 db1"' -b

/etc/hosts will end up containing:

# BEGIN ANSIBLE MANAGED BLOCK
192.168.56.11 web1
192.168.56.12 web2
192.168.56.21 db1
# END ANSIBLE MANAGED BLOCK

If you run it again with the same block, nothing changes; if you change the contents, it replaces only what's between the markers. Check that it works: ansible web1 -a 'getent hosts db1'.

Writing the IPs by hand duplicates what's already in the inventory. Once you know how to use templates and loops, you will generate this block automatically from the ansible_host variables.

Module Manages Use it when…
copy The whole file (fixed contents) The file is yours and doesn't depend on variables
template The whole file (with variables) The file is yours and varies by host/environment
lineinfile One line You only need to touch one setting in a system file
blockinfile A delimited block You need to add several lines together to a file you don't own

  1. Service, user and group modules

5.1 service and systemd_service

ansible.builtin.service is generic (it works with systemd, SysV, OpenRC…). ansible.builtin.systemd_service (formerly called systemd, which still works as an alias) is specific to systemd and adds options such as daemon_reload or masked:

# Reload the systemd configuration and make sure cron is running
ansible aurora -m ansible.builtin.systemd_service -a 'name=cron state=started enabled=true daemon_reload=true' -b

daemon_reload=true is required when you create or modify unit files (.service): in Module 4 you will need it for Aurora's application.

5.2 user and group

In addition to user (lesson 2.4), group manages system groups:

# Simulate creating a group for the operations team
ansible aurora -m ansible.builtin.group -a 'name=aurora_ops state=present' -b --check

Frequently used user parameters: name, state, groups + append=true (add to groups without removing existing ones), shell, home, system=true (system user), password (always a hash, never the plain-text password).

  1. Modules for running commands

Module Requires Python on the host Goes through a shell Use
command Yes No Running a program when there's no module
shell Yes Yes The same, but with pipes, redirections, variables
script No — Copying a local script and running it on the host
raw No Yes A direct SSH command; for hosts without Python or network devices
# raw: works even if the host has no Python (e.g. to install it)
ansible web1 -m ansible.builtin.raw -a 'python3 --version'

# script: runs a script that lives on your machine on the servers
echo 'echo "Hello from $(hostname)"' > /tmp/greeting.sh
ansible aurora -m ansible.builtin.script -a /tmp/greeting.sh

raw is the only way to "bootstrap" a freshly installed server without Python. Outside that case, avoid it: it doesn't report changes, doesn't support check mode and its output is unstructured text.

  1. Modules for downloading, unpacking and querying

7.1 get_url, unarchive and git

# Download a file on the server (the server itself downloads it, not the control node)
ansible web1 -m ansible.builtin.get_url -a 'url=https://www.example.com/ dest=/tmp/example.html mode=0644'
  • get_url is idempotent: if the destination file already exists, by default it doesn't download it again (and with checksum= it verifies its integrity).
  • ansible.builtin.unarchive unpacks .tar.gz, .zip… By default it takes the archive from the control node; with remote_src=true, one that's already on the server.
  • ansible.builtin.git clones or updates a repository on the server (repo=, dest=, version=). You will use it to deploy Aurora's application in later modules.

7.2 stat: querying without changing anything

stat returns information about a file or directory: whether it exists, its type, owner, permissions, size, checksum…

ansible webservers -m ansible.builtin.stat -a 'path={{ aurora_web_root }}'
ansible db1 -m ansible.builtin.stat -a 'path=/etc/postgresql'

In the first case you will see "exists": true and "pw_name": "deploy"; in the second, "exists": false, because PostgreSQL isn't installed yet. In playbooks, stat is combined with conditions to decide what to do (Module 3).

7.3 debug

You already used it in lesson 2.2 to display variables. It's the basic debugging tool: it doesn't connect to the host and never changes anything.

  1. Reading the documentation with ansible-doc

No administrator remembers every parameter of every module: knowing how to read the documentation is the real skill. Open the documentation for lineinfile:

ansible-doc ansible.builtin.lineinfile

The output always has the same sections:

Section What you'll find
Header (> MODULE ...) Full name, file path and description
OPTIONS Every parameter. A leading = means required; -, optional
ATTRIBUTES Support for check_mode, diff_mode, platforms…
NOTES Warnings and special behaviors
SEE ALSO Related modules (very useful for discovering alternatives)
EXAMPLES Usage examples ready to adapt
RETURN VALUES What data the module returns

8.1 Reading a parameter

An excerpt from ansible-doc ansible.builtin.service:

OPTIONS (= indicates it is required):

- enabled  Whether the service should start on boot.
            At least one of `state' and `enabled' are required.
        default: null
        type: bool

= name    Name of the service.
        type: str
  • = name: required (starts with =).
  • - enabled: optional, of boolean type, with no default value (null).
  • Other fields you will see: choices (allowed values, e.g. state), aliases (alternative names for the parameter) and default (the value it takes if you don't specify one).

Always look at default. Many mistakes come from assuming a default value that isn't the real one. For example, in apt, state defaults to present; in file, if you don't specify state, the module doesn't create the file.

8.2 Reading the return values

An excerpt from ansible-doc ansible.builtin.copy:

RETURN VALUES:

- checksum  SHA1 checksum of the file after running copy.
        returned: success
        sample: 6e642bb8dd5c2e027bf21dd923337cbb4214f827
        type: str
  • returned: when that piece of data appears (success, changed, always…).
  • sample: an example of the value.
  • type: its type.

These values are the ones you will be able to save and reuse in playbooks with register ("Registering Results and Debugging Playbooks" lesson in Module 3).

8.3 Handy shortcuts

ansible-doc -s ansible.builtin.user       # parameter summary in task format (snippet)
ansible-doc -l | grep -i postgres         # search modules by keyword
ansible-doc -t callback -l                # documentation for other plugin types

  1. Common return values

In addition to their own, almost every module returns a set of common fields:

Field Type Meaning
changed bool Whether the module modified anything on the host
failed bool Whether the task failed
msg str Explanatory message (especially on errors)
rc int Return code (modules that run commands: 0 = success)
stdout / stdout_lines str / list Standard output, in full or as a list of lines
stderr / stderr_lines str / list Error output
skipped bool Whether the task was skipped (in check mode, for example)
diff dict Before/after differences (with --diff)
ansible_facts dict Facts contributed by the module (setup, for example)
invocation dict Arguments the module was called with (visible with -v)

Check it with command, which returns almost all of them:

ansible db1 -m ansible.builtin.command -a 'ls /does/not/exist'
db1 | FAILED | rc=2 >>
ls: cannot access '/does/not/exist': No such file or directory
non-zero return code

Ansible marks the task as failed because rc isn't 0; non-zero return code is the msg. Add -v to see the full JSON, with changed, failed, rc, stdout, stderr, cmd, start, end, delta…

  1. Idempotent and non-idempotent modules

Idempotent (they describe a state) Non-idempotent (they perform an action)
apt/package with state=present or absent command, shell, raw, script (without creates/removes)
file, copy, template, lineinfile, blockinfile service with state=restarted or reloaded
service with state=started/stopped file with state=touch
user, group, git (with a pinned version), get_url apt with state=latest (may change when a new version comes out)
stat, setup, debug (they never change anything) reboot

The rule you already know: always prefer a state-based module. Non-idempotent ones have their place (a reboot is sometimes necessary), but in playbooks you will learn to control them so they only run when appropriate.

  1. Check mode support

The ATTRIBUTES section of ansible-doc tells you whether a module supports simulation mode:

ATTRIBUTES:

        `check_mode:`
        description: Can run in check_mode and return changed status prediction without modifying
          target, if not supported the action will be skipped.
        support: full
support Meaning
full Correctly predicts whether there would be changes without modifying anything
partial Supports it with limitations (described in details)
none Doesn't support it: in --check, the task is skipped

Look it up before trusting a simulation:

ansible-doc ansible.builtin.command | grep -A 6 'check_mode:'
ansible-doc ansible.builtin.apt | grep -A 6 'check_mode:'

command reports partial support (only if you use creates/removes); apt, full support.

Common Mistakes and Tips

  • Using shell "out of habit" instead of the specific module: you lose idempotency, check mode and truthful reporting. Search first with ansible-doc -l | grep <keyword>.
  • file state=absent on a directory: it deletes it with all its contents, without confirmation. Check the path with --check first.
  • lineinfile without regexp to change a setting: it adds a new line instead of replacing the existing one, and the file ends up with the setting duplicated.
  • Using lineinfile to manage half a configuration file: if you need to change many lines, manage the whole file with template.
  • Mixing up package and apt: package doesn't accept update_cache or other apt-specific parameters.
  • Not checking default in ansible-doc: it's the cause of many "mysterious" behaviors.
  • Tip: the EXAMPLES section of ansible-doc usually settles the question in seconds; start there and then check OPTIONS.

Exercises

Exercise 1: Investigating with ansible-doc

Using only ansible-doc, answer these questions about ansible.builtin.user: (a) which parameter is required? (b) what does append do, and what is its default value? (c) what does it return in home? (d) does it support check mode?

Exercise 2: Aurora's log directory

On the web servers, make sure the directory /var/log/aurora exists, owned by deploy, group deploy, with permissions 0750. Then create a symbolic link {{ aurora_web_root }}/logs pointing to it. Check both with stat.

Exercise 3: Choosing the right module

For each need, state the most appropriate module: (a) adding vm.swappiness=10 to /etc/sysctl.conf if it isn't there; (b) checking whether /etc/nginx/nginx.conf exists; (c) generating the nginx configuration from variables; (d) running apt-get install -y python3 on a host without Python; (e) making sure chrony starts at boot.

Solutions

Exercise 1.

ansible-doc ansible.builtin.user | less

(a) Only name (it appears with =). (b) append: if true, it adds the user to the groups in groups without removing them from the ones they already belong to; if false (the default), it leaves the user in exactly the groups specified. (c) In RETURN VALUES, home is the path to the home directory (for example /home/deploy). (d) In ATTRIBUTES, check_mode has support: full.

Exercise 2.

ansible webservers -m ansible.builtin.file \
  -a 'path=/var/log/aurora state=directory owner=deploy group=deploy mode=0750' -b

ansible webservers -m ansible.builtin.file \
  -a 'src=/var/log/aurora dest={{ aurora_web_root }}/logs state=link' -b

ansible webservers -m ansible.builtin.stat -a 'path=/var/log/aurora'
ansible webservers -m ansible.builtin.stat -a 'path={{ aurora_web_root }}/logs'

The second stat shows "islnk": true and "lnk_source": "/var/log/aurora". In file, dest is an alias of path: for links people usually write src + dest because it reads naturally.

Exercise 3. (a) ansible.builtin.lineinfile (or, even better, ansible.posix.sysctl, from a collection, which also applies the value on the fly). (b) ansible.builtin.stat. (c) ansible.builtin.template. (d) ansible.builtin.raw. (e) ansible.builtin.service or ansible.builtin.systemd_service with enabled=true.

Conclusion

You now know what a module is and how it works, you know the most widely used modules in ansible.builtin grouped by category (packages, files, services, users, commands, downloads and queries) and you have applied them to Aurora: the {{ aurora_web_root }} directory for the website, the /etc/hosts block so the servers know each other by name, queries with stat… You know how to read ansible-doc (required parameters, default values, return values and check mode support), interpret the common fields any module returns and tell idempotent modules apart from those that aren't. You will have noticed that every name we write has three parts (ansible.builtin.apt) and that some modules, such as ansible.posix.sysctl, aren't part of ansible.builtin. In the next lesson, Collections and Fully Qualified Names (FQCN), you will discover what collections are, how they're organized and installed, and why you should always write each module's full name.

Ansible Course: From Beginner to Advanced

Module 1: Introduction to Ansible

Module 2: Ansible Fundamentals

Module 3: Playbooks

Module 4: Roles

Module 5: Advanced Playbook Techniques

Module 6: Ansible Galaxy

Module 7: Ansible Tower, AWX and Automation Platform

Module 8: Ansible for DevOps

Module 9: Ansible Best Practices

Module 10: Advanced Ansible Topics

Module 11: Final Project

© Copyright 2026. All rights reserved