TExcelTAD
Home › Configuration Management: Ansible › become, Packages, Services & Users

become, Packages, Services & Users

Real server configuration needs root: installing packages, writing /etc, managing services and accounts. Ansible connects as a normal user (good: no root SSH logins, see Hardening the SSH Server) and becomes root for the tasks that need it, through sudo by default.

Keyword Meaning
become: true run as another user (root by default); on a play, block or task
become_user: postgres which user to become
become_method: sudo also su, doas, pbrun, machinectl, runas (Windows)
-b / --become the same from the command line
-K / --ask-become-pass ask for the sudo password (when sudo isn't passwordless)

Set become on the tasks or blocks that need it, not on whole plays out of habit: the less runs as root, the less a mistake can break.

What happens without sudo

The sandbox has no sudo (and you are not root), so becoming fails, which shows exactly what become does: it wraps the module call in a sudo command.

bash · try it yourself
cat > root.yml <<'YML'
- name: A task that needs root
  hosts: localhost
  gather_facts: false
  tasks:
    - name: Install nginx
      ansible.builtin.apt:
        name: nginx
      become: true
YML
ansible-playbook root.yml 2>/dev/null | grep '^fatal'
fatal: [localhost]: FAILED! => {"changed": false, "msg": "Task failed: Premature end of stream waiting for become success.\n>>> Standard Error\n/bin/sh: 1: sudo: not found"}

On a server where sudo asks for a password and you forgot -K, the message is Missing sudo password. Where your user isn't in sudoers, it is … is not in the sudoers file.

Packages, services and users on a real server

This is the bread and butter of server playbooks. It runs on a practice VM, so here it is a sample session:

yaml
# base.yml
- name: Base server setup
  hosts: web
  become: true
  tasks:
    - name: Packages present (one apt transaction)
      ansible.builtin.apt:
        name: [nginx, fail2ban, unattended-upgrades, chrony]
        state: present
        update_cache: true
        cache_valid_time: 3600       # don't refresh the cache on every run

    - name: Telnet absent
      ansible.builtin.apt:
        name: telnet
        state: absent

    - name: Deploy group
      ansible.builtin.group:
        name: deploy
        system: true

    - name: Deploy user
      ansible.builtin.user:
        name: deploy
        group: deploy
        shell: /bin/bash
        create_home: true

    - name: Deploy user's SSH key
      ansible.posix.authorized_key:
        user: deploy
        key: "{{ lookup('ansible.builtin.file', 'files/deploy.pub') }}"
        exclusive: true              # remove keys not listed here

    - name: Services running and enabled at boot
      ansible.builtin.service:
        name: "{{ item }}"
        state: started
        enabled: true
      loop: [nginx, fail2ban, chrony]
bash
$ ansible-playbook -i inventories/staging base.yml
PLAY [Base server setup] *******************************************************

TASK [Gathering Facts] *********************************************************
ok: [web1]

TASK [Packages present (one apt transaction)] **********************************
changed: [web1]

TASK [Telnet absent] ***********************************************************
ok: [web1]

TASK [Deploy group] ************************************************************
changed: [web1]

TASK [Deploy user] *************************************************************
changed: [web1]

TASK [Deploy user's SSH key] ***************************************************
changed: [web1]

TASK [Services running and enabled at boot] ************************************
ok: [web1] => (item=nginx)
changed: [web1] => (item=fail2ban)
ok: [web1] => (item=chrony)

PLAY RECAP *********************************************************************
web1                       : ok=7    changed=5    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

The second run of the same playbook reports changed=0, like every example in this course.

Module Notes
apt, dnf, package state: present (default), absent, latest (upgrades on every run: use deliberately)
service / systemd_service state: started/stopped/restarted/reloaded, enabled: true; systemd_service adds daemon_reload: true for new unit files
user, group password takes a hash ({{ 'pw' | password_hash('sha512') }}); system: true for service accounts
ansible.posix.authorized_key exclusive: true makes the list authoritative

Read-only equivalents that work without root

Several modules only read system state and work as any user. They are handy for checks and conditions:

bash · try it yourself
cat > look.yml <<'YML'
- name: Read system state without root
  hosts: localhost
  gather_facts: false
  tasks:
    - name: Look up an account
      ansible.builtin.getent:
        database: passwd
        key: learner

    - name: Installed version of bash (read-only)
      ansible.builtin.command:
        argv: [dpkg-query, -W, "-f=${Version}", bash]
      register: bash_pkg
      changed_when: false

    - name: Is nginx installed?
      ansible.builtin.command:
        argv: [dpkg-query, -W, nginx]
      register: nginx_pkg
      changed_when: false
      failed_when: nginx_pkg.rc > 1

    - name: Report
      ansible.builtin.debug:
        msg:
          - "learner: uid={{ ansible_facts.getent_passwd.learner[1] }} home={{ ansible_facts.getent_passwd.learner[4] }} shell={{ ansible_facts.getent_passwd.learner[5] }}"
          - "bash {{ bash_pkg.stdout }} installed"
          - "nginx installed: {{ nginx_pkg.rc == 0 }}"
YML
ansible-playbook look.yml | sed -n '/"msg"/,/^    ]/p'
    "msg": [
        "learner: uid=1000 home=/home/learner shell=/bin/bash",
        "bash 5.2.21-2ubuntu4 installed",
        "nginx installed: False"
    ]

On a normal server you would use ansible.builtin.package_facts instead of dpkg-query, and then when: "'nginx' in ansible_facts.packages". It needs the apt Python bindings (python3-apt) in the interpreter Ansible uses on the host. Ubuntu's system Python has them; the sandbox runs modules with Ansible's own Python, which doesn't, so package_facts (and apt itself) fail here with "Failed to import the required Python library (apt)". The same message on a real host means ansible_python_interpreter points at a virtualenv instead of /usr/bin/python3.

become_user for application accounts

Becoming a non-root user is useful for application tasks: run migrations as the app user, or SQL as postgres:

yaml
- name: Create the database (as the postgres OS user, via peer auth)
  community.postgresql.postgresql_db:
    name: linkly
  become: true
  become_user: postgres

Becoming an unprivileged user from an unprivileged login needs ACL support on the host (setfacl) or pipelining, because Ansible's temporary module files must be readable by the target user. The error message tells you when that bites.

Test yourself

What does become: true do by default?

  1. Logs in as root over SSH
  2. Runs the task through sudo as root
  3. Disables privilege checks
  4. Uses su without a password

Why prefer become: true on individual tasks or blocks over the whole play?

  1. It is faster
  2. Less code runs as root, so mistakes have a smaller blast radius
  3. Plays can't use become
  4. It hides passwords

Which apt state upgrades the package on every run when a new version exists?

  1. present
  2. latest
  3. absent
  4. installed