SSD Nodes Learn Hosting plans →
Guides Matt ConnorBy Matt Connor

Ansible modules you will actually use

The Ansible modules a VPS admin needs, grouped by job: packages, files, users and commands. Read the docs with ansible-doc, then run one idempotent playbook.

What is an Ansible module?

Ansible modules are the units of work that Ansible ships out to the machines it manages. A task in a playbook names one module and gives it arguments. An ad-hoc command does the same thing from the shell. So when you learn a module, you learn it for both.

If this is your first contact with playbooks, open the first Ansible playbook tutorial beside this page. If you mostly type one-off commands, the Ansible ad-hoc commands you will actually use calls the same modules with -m. This guide sits between the two. It covers the modules a VPS (virtual private server) admin reaches for, grouped by job, and it ends with one playbook that you run twice.

Here is one module used both ways. First the ad-hoc form:

ansible localhost -c local -m ansible.builtin.stat -a 'path=/etc/hostname'

Then the same module as a playbook task:

- name: Check that /etc/hostname exists
  ansible.builtin.stat:
    path: /etc/hostname
  register: hostname_file

The module is the same. Only the way you call it changes.

The property that makes modules worth using is idempotency. An operation is idempotent if running it once gives exactly the same result as running it many times. The Ansible docs say modules should be idempotent, and should avoid making any change when the current state already matches the desired state. This is why you can run a playbook again against a server that is already configured. A well-written module checks first, and then acts only on the difference.

Fully qualified collection names and collections

A collection is a packaging format for Ansible content, including modules, plugins and roles. Since Ansible 2.10, most modules live in collections instead of in the core program.

Every module has a fully qualified collection name (FQCN). The form is namespace.collection.module. In ansible.builtin.lineinfile, the namespace is ansible, the collection is builtin, and the module is lineinfile. The ansible.builtin collection ships inside ansible-core, so it is present on every Ansible install. Modules from other collections, such as community.general.ufw, work only after that collection is installed.

Older posts often use the short name, copy: instead of ansible.builtin.copy:. Prefer the FQCN. The Ansible glossary describes it as the way a playbook refers to a module from one specific source without ambiguity. That matters once two installed collections ship a module with the same short name. The docs also prefer the FQCN over the play-level collections: keyword. That keyword only creates a search path, and roles do not inherit it from the playbook. So a role that depends on it can break when you reuse the role in a different playbook.

Which Ubuntu package gives you ansible-doc and the builtin modules?

On Ubuntu 26.04, the ansible-core package ships /usr/bin/ansible-playbook, /usr/bin/ansible-doc and the source of every builtin module, for example lineinfile.py. The larger ansible package depends on ansible-core. The Ansible install guide describes it as a batteries-included package that adds a community-curated selection of collections. Either package gives you ansible-doc and every module in this guide except ufw.

On Ubuntu 26.04, a plain apt install ansible-core also installs the ansible bundle, because apt installs recommended packages by default. Add --no-install-recommends when you want ansible-core on its own:

sudo apt update
sudo apt install -y --no-install-recommends ansible-core python3-apt
ansible --version

ansible --version should print the core version on its first line. On Ubuntu 26.04 the archive holds ansible-core 2.20.1, in the universe component. On Ubuntu 24.04 it holds 2.16.3. The python3-apt package is in that command because the apt module needs it on the target machine, and in this guide the target is the same machine. For the choice between apt, pipx and the upstream packages, read which Ansible to install on Ubuntu. This page does not repeat it.

How do you find and read module docs with ansible-doc?

ansible-doc shows the documentation of the modules installed on your machine. That matters because the website shows the newest release. As of 15 November 2026, docs.ansible.com documents the ansible.builtin collection at version 2.21.6.post0, while Ubuntu 26.04 ships ansible-core 2.20.1. When a default or an option differs between those versions, ansible-doc describes the version you will actually run.

List the modules in one collection:

ansible-doc -l ansible.builtin

-l lists plugins with a short description of each. The plugin type defaults to module, and the argument filters the list by namespace or collection name. Next, open one module:

ansible-doc ansible.builtin.lineinfile

This prints the module's documentation string. Read each option's default and its allowed choices before anything else. Most surprises in a playbook come from a default you did not know about, such as create being false for lineinfile.

To get a task skeleton that you can paste into a playbook, ask for a snippet:

ansible-doc -s ansible.builtin.lineinfile

-F lists module names with the source file that holds each one, and no descriptions. It helps when you are not sure which collection a module comes from.

Which package module to use on Ubuntu and Rocky

ansible.builtin.apt manages packages on Debian and Ubuntu.

- name: Install nginx, refreshing the cache if it is older than an hour
  ansible.builtin.apt:
    name: nginx
    state: present
    update_cache: true
    cache_valid_time: 3600

state defaults to present. It installs a missing package and leaves an installed one alone. latest also upgrades the package, so choose it on purpose. update_cache has no written default, but the docs say the default is not to update the cache. So the module works from the package lists already on disk unless you ask for a refresh. cache_valid_time makes that refresh conditional: the module runs the equivalent of apt-get update only when the cache is older than that many seconds. name also takes a list, and version specifiers such as foo=1.0.

ansible.builtin.dnf does the same job on Rocky, Alma and Fedora. It needs python3-dnf on the target. Its state has no written default, but the docs say the effective default is present.

ansible.builtin.package is a proxy. It detects the package manager on the host and passes the task to that manager's module. Its docs cover only the arguments that every package module supports: name and state, plus use, which defaults to auto. It hides the package manager. It does not hide package names. Apache is apache2 on Ubuntu and httpd on Rocky, so a package task that names apache2 still fails on Rocky. Use package for tools with the same name on every distribution, like git or curl. Use apt or dnf when you need their extra options.

File modules: copy, template, file, lineinfile, blockinfile, stat and get_url

copy: put a file in place

ansible.builtin.copy copies a file to the target, or writes literal text with content. force defaults to true, so a target file whose contents differ from the source is replaced. Set force: false to write the file only when it does not exist yet. The playbook at the end uses this to create a file once and then edit it. If the file needs variables in it, the docs say to use template instead.

Always set mode. The docs call it the best way to make sure files are created with the correct permissions. Write it as a quoted string with the leading zero, such as '0644'.

template: a file with variables in it

ansible.builtin.template renders a Jinja2 template. src is a path on the Ansible controller, the machine where you run ansible-playbook. dest is a path on the target. The validate option runs a check against a temporary file before the real file is replaced. %s in the command stands for that temporary path.

- name: Install sshd_config only if sshd accepts it
  ansible.builtin.template:
    src: templates/sshd_config.j2
    dest: /etc/ssh/sshd_config
    owner: root
    group: root
    mode: '0644'
    validate: /usr/sbin/sshd -t -f %s

A broken SSH config can lock you out of a VPS, and validate stops that file before it lands. Templates usually pair with handlers, which restart a service only when its file changed. Ansible templates and handlers covers that pattern in full.

ansible.builtin.file sets the owner, group and mode of files, directories and symlinks. It can also remove them. The state choices are absent, directory, file, hard, link and touch. There is no fixed default: it is the current state of the path if it exists, directory if recurse is set, and file otherwise. Write state on every task, because a default that depends on what is already on disk makes the task hard to read. recurse applies the attributes to everything inside a directory, and it works only with state: directory.

lineinfile: change one line

ansible.builtin.lineinfile makes sure one line is in a file, or replaces an existing line that matches a regular expression. state defaults to present. create defaults to false, so the task fails if the file is missing. Give it a regexp that matches the line both before and after your edit. Then on the next run the module finds the line it wrote and compares it with line.

blockinfile: change several lines

ansible.builtin.blockinfile inserts, updates or removes a block of lines between two marker lines. The default marker is # {mark} ANSIBLE MANAGED BLOCK. The module writes one marker line before the block and one after it, and uses them to find its block again on the next run.

- name: Add names for the private network
  ansible.builtin.blockinfile:
    path: /etc/hosts
    marker: '# {mark} PRIVATE HOSTS'
    block: |
      10.0.0.11 db1
      10.0.0.12 db2

If you manage more than one block in the same file, give each task its own marker. Two tasks with the same marker edit the same block, so each one overwrites the other. An empty or missing block removes the block, as if you had set state: absent.

stat: look before you act

ansible.builtin.stat reads facts about a path, like the Linux stat command. Register the result and test it in a later task. stat.exists says whether the path exists. stat.isdir says whether it is a directory. stat.mode gives the permissions as an octal string. get_checksum defaults to true with SHA-1, which means the module reads the whole file. Set get_checksum: false when you only need to know that a large file exists.

get_url: download a file

ansible.builtin.get_url downloads a file over HTTP, HTTPS or FTP. The target machine does the download, so the target needs direct access to the URL. force defaults to false, so the file is downloaded only when dest does not exist yet. A newer version on the server is not fetched once the old one is on disk. timeout defaults to 10 seconds.

- name: Download a file once
  ansible.builtin.get_url:
    url: https://example.com/
    dest: /tmp/example.html
    mode: '0644'

Add the checksum option for anything you will execute. When a checksum is given and the file on disk already matches it, the download is skipped. After a download, the module checks the new file against the checksum. Run ansible-doc ansible.builtin.get_url for the format it expects.

Managing users with ansible.builtin.user

- name: Create a deploy user with sudo rights
  ansible.builtin.user:
    name: deploy
    shell: /bin/bash
    groups: sudo
    append: true

state defaults to present, and create_home defaults to true. groups is the list of supplementary groups. append defaults to false. Set it to true so the groups you list are added to the user's current groups, instead of replacing them.

Be careful with password. On Linux it takes an already encrypted hash, and the module writes the value directly to /etc/shadow without any validation. A plain-text password in that field is stored as a broken hash, and nobody can log in with it. Keep the hash itself out of your git history with Ansible Vault to encrypt secrets.

command vs shell, and why a real module is better

ansible.builtin.command runs a program without a shell. Pipes, redirects, ; and & do not work, and environment variables are resolved by Python, not by a shell. ansible.builtin.shell runs the command through /bin/sh on the remote node. Use shell only when you need a shell feature. The docs warn that badly quoted shell metacharacters can run commands you did not intend.

- name: Initialise the app database once
  ansible.builtin.command:
    cmd: /opt/app/bin/init-db
    creates: /var/lib/app/db.sqlite

- name: Count established TCP connections
  ansible.builtin.shell: ss -tn state established | wc -l
  register: conn_count

Neither module knows what your command does. They cannot compare the current state with a desired state, because you never told them what the desired state is. creates and removes give them one check: with creates, the task is skipped when the named file already exists. Without creates or removes, a command task is skipped in check mode, because Ansible cannot predict what it would do.

So before you write command, search ansible-doc -l for a module that does the job. apt-get install becomes apt. mkdir -p becomes file. sed -i becomes lineinfile. useradd becomes user, and systemctl becomes systemd_service. When you do need a command and its output, showing command output in Ansible explains how to read stdout from the registered result.

debug: print what Ansible knows

ansible.builtin.debug prints a message or a variable while the play runs.

- name: Show the connection count
  ansible.builtin.debug:
    var: conn_count.stdout

- name: Show this only with -vv or more
  ansible.builtin.debug:
    msg: 'Connections: {{ conn_count.stdout }}'
    verbosity: 2

var and msg cannot be used in the same task. var already runs in a Jinja2 context, so write the bare variable name with no {{ }} around it. verbosity hides the task unless you run with at least that many -v flags, which keeps a normal run quiet. The facts Ansible collects about a host are a common thing to print, and Ansible facts and gather_facts lists the useful ones.

Services and the firewall: systemd_service and ufw

The playbook at the end of this guide does not run these two modules. The first needs a machine managed by systemd, and the second needs a collection that may not be installed. So the example runs anywhere, including a container with no init system. Here is how they look in a real play.

- name: Start nginx now and at boot
  ansible.builtin.systemd_service:
    name: nginx
    state: started
    enabled: true

started and stopped are idempotent: they run nothing when the unit is already in that state. enabled controls start at boot. daemon_reload defaults to false. Set it to true when the same play changes a unit file, so systemd reads your changes first. name takes exactly one unit. The older name ansible.builtin.systemd still works, because it is kept as an alias for backward compatibility. On a host without systemd, use ansible.builtin.service, which also supports SysV, OpenRC, BSD init, Solaris SMF and upstart.

UFW (Uncomplicated Firewall) is managed by community.general.ufw. It is not in ansible-core, and it needs the ufw package on the target. Check whether the collection is present, and install it if it is not:

ansible-galaxy collection list community.general
ansible-galaxy collection install community.general
- name: Allow SSH before the firewall is switched on
  community.general.ufw:
    rule: allow
    port: '22'
    proto: tcp

- name: Enable UFW and deny everything else
  community.general.ufw:
    state: enabled
    policy: deny

The order of those two tasks is the important part. If you enable a deny policy over SSH before you allow port 22, the next connection to the server is refused, and that includes Ansible's own connection. The module docs also say not to run it concurrently, because the results are unpredictable and the module may fail silently.

Run one playbook twice to see idempotency

This playbook runs against the machine you are on, with connection: local. It installs a small package, creates a directory, renders a file from a template, creates a second file once, and edits one line in it. Then it reads the rendered file with stat and prints what it found. With connection: local, tasks run on the controller as the user who started ansible-playbook. become: true raises that to root for the package and the files in /etc.

mkdir -p ~/modules-demo/templates
cd ~/modules-demo
cat > templates/app.conf.j2 <<'EOF'
# Managed by Ansible. Local edits are overwritten.
name = {{ app_name }}
port = {{ app_port }}
EOF

Save this as ~/modules-demo/site.yml:

- name: Module tour on this machine
  hosts: localhost
  connection: local
  become: true
  gather_facts: false
  vars:
    app_name: demo
    app_port: 8080
  tasks:
    - name: Install tree
      ansible.builtin.apt:
        name: tree
        state: present
        update_cache: true
        cache_valid_time: 3600

    - name: Create the config directory
      ansible.builtin.file:
        path: /etc/demo-app
        state: directory
        owner: root
        group: root
        mode: '0755'

    - name: Render the main config from a template
      ansible.builtin.template:
        src: templates/app.conf.j2
        dest: /etc/demo-app/app.conf
        owner: root
        group: root
        mode: '0644'

    - name: Create the defaults file only if it is missing
      ansible.builtin.copy:
        content: |
          listen_port = 8080
          log_level = info
        dest: /etc/demo-app/defaults.conf
        force: false
        mode: '0644'

    - name: Change one line in the defaults file
      ansible.builtin.lineinfile:
        path: /etc/demo-app/defaults.conf
        regexp: '^log_level\s*='
        line: 'log_level = warn'

    - name: Read the rendered file's metadata
      ansible.builtin.stat:
        path: /etc/demo-app/app.conf
      register: app_conf

    - name: Show what stat found
      ansible.builtin.debug:
        msg: 'exists={{ app_conf.stat.exists }} mode={{ app_conf.stat.mode }}'

Run it:

ansible-playbook -i localhost, site.yml

The trailing comma in -i localhost, tells Ansible the value is a list of hosts, not an inventory file. If your user needs a password for sudo, add -K so Ansible asks for it. The ansible-playbook flags explained covers the rest. When the run ends, check the result by hand:

cat /etc/demo-app/app.conf
cat /etc/demo-app/defaults.conf
tree /etc/demo-app

app.conf should hold the name and port from vars, and defaults.conf should read log_level = warn.

Now run the same ansible-playbook command a second time. Compare the PLAY RECAP line from each run, and look at the changed= count. Between the runs, nothing changed the machine. Each module in this playbook checks the current state before it acts, so the second run is the test of that promise. If a task reports changed on both runs, it does its work again every time, and the next section lists the usual reasons. To preview a run without touching anything, add --check --diff, which Ansible check mode explains.

Why does a task report changed on every run?

The task is a command or shell task with no creates or removes. The module cannot see the state, so it runs your command every time. Replace it with a real module, or add creates.

The lineinfile pattern does not match the line it writes. A regexp of '^log_level = info' matches the old line, but not log_level = warn after the edit. On the next run the module no longer finds the line it changed. Match the key, not the value, as the playbook does.

Two modules own the same file. Replace force: false with the default in the playbook above, and copy puts log_level = info back on every run, because the file no longer matches its content. Then lineinfile changes it to warn again. Each module undoes the other. Give each file one owner: a template for the whole file, or one seeded copy plus line edits.

A package uses state: latest. Each time the archive has a newer version, the task upgrades it. That is correct behaviour, but it belongs in a planned update window, not in every routine run.

FAQ

What is the difference between ansible.builtin.command and ansible.builtin.shell?

command runs a program directly, with no shell, so pipes, redirects, ; and & do not work. shell runs the command through /bin/sh on the target, so those features work. The Ansible docs recommend command unless you need a shell feature, because badly quoted shell metacharacters can run commands you did not intend. Before using either one, look for a real module that does the job, since a module checks the current state and a command does not.

Which Ubuntu package provides ansible-doc and the builtin modules?

The ansible-core package. On Ubuntu 26.04 it ships /usr/bin/ansible-doc, /usr/bin/ansible-playbook and the ansible.builtin modules, at version 2.20.1. The ansible package depends on ansible-core and adds a community-curated selection of collections, so installing either one gives you ansible-doc.

Should I write copy or ansible.builtin.copy in my tasks?

Write the fully qualified collection name, ansible.builtin.copy. It tells Ansible exactly which collection the module comes from, so a module with the same short name in another collection can never be picked by mistake. The Ansible docs prefer the FQCN over the collections: keyword, which only sets a search path and is not inherited by roles.

How do I make a lineinfile task safe to run twice?

Give it a regexp that matches the line both before and after the edit. For example, '^log_level\s*=' matches log_level = info and log_level = warn. On the next run the module finds the line it wrote and compares it with line. Remember that create defaults to false, so the task fails if the file does not exist yet.

Do I need to install anything to use community.general.ufw?

Yes, on both sides. The controller needs the community.general collection, which is not part of ansible-core. Check with ansible-galaxy collection list community.general and install it with ansible-galaxy collection install community.general. The target needs the ufw package. Allow your SSH port in an earlier task before you enable the firewall, or the deny policy blocks your own connection.

Was this article useful?