Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 29 ยท Everyday Modules

Files, Users and Packages

Manage files, users and packages with Ansible: copy, template, file, lineinfile, blockinfile, user, group, apt/dnf, get_url, unarchive and authorized_key, with idempotent examples.

Most real playbooks spend their time on three jobs: put the right files on the machine, make sure the right accounts exist, and install the right software. Ansible has a module for each job, and each module is written to be idempotent: it looks at the current state first and changes something only when the state differs from what you asked for.

This lesson walks through the everyday modules for those jobs: copy, template, file, lineinfile, blockinfile, user, group, package (and the apt/dnf modules behind it), get_url, unarchive and authorized_key. The real modules need a managed host, so their examples are read-only. To see the idea inside, you will run a small JavaScript stand-in for lineinfile, and a second one that shows why file modes must be quoted.

If you need a refresher on why modules beat raw commands, read Modules and Idempotence first.

Files: copy, template and file

The copy module sends a file (or literal text) from the control node to the managed host. The template module does the same after rendering a Jinja2 template (see Jinja2 Templates and Filters).

YAML
- name: Install the message of the day
  ansible.builtin.copy:
    src: motd.txt            # looked up in the role's files/ folder or next to the playbook
    dest: /etc/motd
    owner: root
    group: root
    mode: "0644"

- name: Write a tiny file from inline text
  ansible.builtin.copy:
    content: "managed by Ansible\n"
    dest: /etc/ansible-managed
    mode: "0644"

- name: Render the app config from a template
  ansible.builtin.template:
    src: app.conf.j2
    dest: /etc/myapp/app.conf
    owner: myapp
    mode: "0640"
    validate: "/usr/local/bin/myapp --check-config %s"
  notify: Restart myapp

Both modules compare checksums. If the remote file already has identical content, owner and mode, the task reports ok; otherwise it reports changed. That is exactly what makes notify useful: the handler only runs when something really changed. The optional validate option runs a command against a temporary copy before the real file is replaced, so a broken config never reaches its final path.

The file module manages the file system object itself: directories, symlinks, permissions, and deletion.

YAML
- name: Make sure the data directory exists
  ansible.builtin.file:
    path: /var/lib/myapp
    state: directory
    owner: myapp
    group: myapp
    mode: "0750"

- name: Point "current" at the active release
  ansible.builtin.file:
    src: /srv/myapp/releases/2026-10-31
    dest: /srv/myapp/current
    state: link

- name: Remove an old file
  ansible.builtin.file:
    path: /tmp/old-installer.sh
    state: absent

The state values are file, directory, link, hard, touch and absent. Note that touch always reports changed because it updates timestamps; avoid it when you only need the file to exist (use copy with force: false instead).

Always quote the mode

File modes are written as strings: "0644". The reason is a YAML detail. An unquoted 0644 is read by YAML 1.1 parsers as an octal number, while an unquoted 644 is a decimal number 644, which is a very different permission. Quoting makes Ansible receive the text and interpret it itself. You can also use the symbolic form, such as u=rwX,g=rX,o=. The second TryIt below shows the trap with real numbers.

Editing lines: lineinfile and blockinfile

Sometimes you do not own the whole file. A distribution ships /etc/ssh/sshd_config and you want to change exactly one setting. That is the job of lineinfile.

YAML
- name: Disable SSH password logins
  ansible.builtin.lineinfile:
    path: /etc/ssh/sshd_config
    regexp: '^#?PasswordAuthentication\s'
    line: "PasswordAuthentication no"
    validate: "/usr/sbin/sshd -t -f %s"
  notify: Reload sshd

- name: Remove a line
  ansible.builtin.lineinfile:
    path: /etc/hosts
    regexp: 'legacy-server'
    state: absent

The logic is: if a line matches regexp, replace it with line (the last match, when several match); if nothing matches, add line at the end (or after a line matched by insertafter, or before one matched by insertbefore). Running it twice changes nothing the second time, because the line is already exactly right. If you leave out regexp, Ansible looks for the exact line instead, which is fine for adding a line that must exist but cannot update an old value.

When you need several lines as one unit, use blockinfile. It wraps your text in marker comments so it can find and update its own block later.

YAML
- name: Add a managed block to the hosts file
  ansible.builtin.blockinfile:
    path: /etc/hosts
    block: |
      10.0.0.11 web1.internal
      10.0.0.12 web2.internal
    marker: "# {mark} ANSIBLE MANAGED: app hosts"

The file ends up with a # BEGIN ANSIBLE MANAGED: app hosts line, your text, and a # END ... line. Prefer template when you can own the whole file; use these two only for files you share with the system.

Here is a stand-in for lineinfile. It is not the real module (the real one reads and writes files on the host and supports many more options), but the decision logic is the same: find the match, compare, change only if needed, and report changed.

JS A lineinfile stand-in

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Users and groups

The group and user modules manage accounts. Create the group first when a user's primary group does not exist yet.

YAML
- name: Create the app group
  ansible.builtin.group:
    name: myapp
    state: present

- name: Create the service account
  ansible.builtin.user:
    name: myapp
    group: myapp
    groups: [docker]
    append: true             # keep the user's other groups
    shell: /usr/sbin/nologin
    system: true
    create_home: false

- name: Create a normal admin user with a hashed password
  ansible.builtin.user:
    name: alice
    shell: /bin/bash
    groups: sudo
    append: true
    password: "{{ alice_password_hash }}"   # a hash, never plain text

Two details cause most trouble. First, groups without append: true replaces the user's supplementary groups. Second, the password option takes a crypted hash (for example from {{ 'secret' | password_hash('sha512') }}, though without a fixed salt that hash changes on every run, so the task would report changed every time). Keep real hashes in Ansible Vault.

To let someone log in with an SSH key, add it with authorized_key:

YAML
- name: Authorize Alice's key
  ansible.posix.authorized_key:
    user: alice
    state: present
    key: "{{ lookup('file', 'files/alice.pub') }}"

This module lives in the ansible.posix collection (see Collections, Galaxy and Reusable Content), so install that collection first.

Packages: package, apt and dnf

The generic ansible.builtin.package module hands the work to the host's package manager, which is handy for names that are the same everywhere (git, curl). For anything specific, use the dedicated module: ansible.builtin.apt on Debian and Ubuntu, ansible.builtin.dnf on current Fedora and RHEL-family systems.

YAML
- name: Install a few tools on any distribution
  ansible.builtin.package:
    name: [git, curl, unzip]
    state: present

- name: Refresh the apt cache and install nginx (Debian/Ubuntu)
  ansible.builtin.apt:
    name: nginx
    state: present
    update_cache: true
    cache_valid_time: 3600    # skip the refresh if it ran within the last hour

- name: Upgrade everything (a deliberate choice)
  ansible.builtin.dnf:
    name: "*"
    state: latest

state: present means "installed, any version" and is the idempotent choice. state: latest upgrades whenever a newer package exists, which makes runs change over time. Pass a list to name so Ansible makes one package manager call for all of them instead of one call per item in a loop. When your fleet mixes distributions, use when: ansible_facts['os_family'] == 'Debian' (see Conditionals and Loops).

Downloading and unpacking: get_url and unarchive

YAML
- name: Download a release archive and verify it
  ansible.builtin.get_url:
    url: https://downloads.example.com/myapp-2.4.0.tar.gz
    dest: /tmp/myapp-2.4.0.tar.gz
    checksum: "sha256:{{ myapp_sha256 }}"
    mode: "0644"

- name: Unpack it
  ansible.builtin.unarchive:
    src: /tmp/myapp-2.4.0.tar.gz
    dest: /opt/myapp
    remote_src: true
    creates: /opt/myapp/bin/myapp

get_url skips the download when dest already exists and matches the checksum. unarchive copies from the control node by default; remote_src: true says the archive is already on the managed host. Adding creates: makes the unpack run once, because the task is skipped when that path exists. Always give get_url a checksum for software you will run.

Treat ansible-doc ansible.builtin.lineinfile as your friend. It prints every option, its default and examples for the version you have installed, so you never have to guess a parameter name.

Why quoting the mode matters

Here is the YAML trap from earlier with real numbers. This stand-in mimics how a YAML 1.1 parser reads an unquoted number, then prints what that value means as a permission.

JS Unquoted modes in YAML

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that an unquoted 644 becomes 01204: a sticky bit, no access at all for the group, and a strange mix for everyone else. Ansible may warn about unquoted modes, but quoting is the habit that avoids the problem entirely.

Putting it together

This small play prepares an application host with a user, a directory and a config line. The diagram shows how each task checks state first.

flowchart LR
  A["Task starts"] --> B["Read current state<br/>on the host"]
  B --> C{"Matches the<br/>desired state?"}
  C -- yes --> D["ok: nothing changed"]
  C -- no --> E["Change the host"]
  E --> F["changed: notify handlers"]

Every file, user and package module follows this loop: read, compare, change only if needed.

YAML
- name: Prepare the app host
  hosts: app
  become: true
  tasks:
    - name: App group
      ansible.builtin.group: { name: myapp }
    - name: App user
      ansible.builtin.user: { name: myapp, group: myapp, shell: /usr/sbin/nologin, system: true }
    - name: Data directory
      ansible.builtin.file: { path: /var/lib/myapp, state: directory, owner: myapp, group: myapp, mode: "0750" }
    - name: Tools
      ansible.builtin.package: { name: [git, curl], state: present }

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the lineinfile module do when no line matches regexp?

    With state present, an unmatched regexp means the line is added. If a match exists and differs, the last match is replaced; if it already equals the line, nothing changes.
  2. 2. Why should you write mode: "0644" with quotes?

    Unquoted 0644 and 644 are different numbers to a YAML parser. Passing the text lets Ansible interpret it as a permission string.
  3. 3. What happens if you give the user module groups: [docker] without append: true?

    Without append, groups sets the complete list of supplementary groups. Add append: true to keep the existing ones.
  4. 4. How do you make unarchive run only once after the first successful unpack?

    creates: names a path; when it already exists the task is skipped, which keeps a command-like module idempotent.

Summary

  • copy and template compare content, owner and mode; they report changed only when something differs, which drives handlers.
  • file manages directories, symlinks, permissions and removal; quote modes as strings such as "0644".
  • lineinfile edits one line (regexp plus line), blockinfile manages a marked block; prefer template when you own the whole file.
  • user and group need append: true to keep existing groups, and passwords must be hashes kept in Vault.
  • Use package for portable names and apt or dnf for distribution-specific options; prefer state: present over latest.
  • get_url with a checksum plus unarchive with creates gives a safe, repeatable install from an archive.

Next: Services, Commands and Scheduling.