Ansible become_method su Runs a Non-Login Shell Without sbin in PATH

In progress Ansible Linux

With become_method: su, Ansible switches to root with a plain su, not su -. That shell doesn't read root's login profile, so PATH keeps the connecting user's directories and lacks /usr/sbin and /sbin. Administration commands that live there (visudo, useradd, iptables) are then "not found" even though root normally runs them without a path.

The Symptom

A task that validates a sudoers file before installing it fails on a fresh Debian node:

- name: Install sudoers drop-in
  ansible.builtin.template:
    src: admins.j2
    dest: /etc/sudoers.d/admins
    mode: "0440"
    validate: visudo -cf %s
  become: true
  become_method: su
No such file or directory: b'visudo'

The file is fine; the shell can't find visudo.

Why su and su - Differ

su su - (login shell)
Environment mostly inherited from the caller reset, then root's login files are read
PATH the connecting user's, without sbin on Debian root's, with /usr/sbin and /sbin
Typical use Ansible's su become method an interactive admin session

Since Debian 10, plain su no longer adds the sbin directories, which is why this shows up on Debian when the same play worked elsewhere.

Fixes

Other options: set environment: { PATH: "/usr/local/sbin:/usr/sbin:/sbin:{{ ansible_env.PATH }}" } on the play, or install sudo first and switch to become_method: sudo for the rest of the run.

The Same Gap over Plain SSH

A command passed straight to ssh as a normal user hits the same missing directories, without Ansible or su involved:

$ ssh leva@node 'swapon --show'
bash: line 1: swapon: command not found

The remote shell is non-interactive and runs as leva, whose PATH on Debian has no sbin directories. Use the absolute path (/usr/sbin/swapon), go through sudo, or read the same information from a file anyone can read: cat /proc/swaps.

References

Review cards

Flashcard Why is `visudo` "not found" under Ansible's `become_method: su` on Debian?

Ansible runs plain su, not su -: no login shell, so PATH stays the connecting user's. Since Debian 10, plain su no longer adds /usr/sbin and /sbin.

Flashcard How do `su` and `su -` differ in the environment they give?

su mostly inherits the caller's environment, PATH included. su - starts a login shell: it resets the environment and reads root's login files, so PATH has the sbin directories.

Quiz Which `validate:` line works whatever `PATH` the `su` shell has?
  • /usr/sbin/visudo -cf %s
  • visudo -cf %s
  • visudo -c -f %s
  • sudo visudo -cf %s

Only an absolute path doesn't depend on PATH. sudo may not even be installed yet on a fresh node. Other fixes: add the sbin directories with environment:, or switch to become_method: sudo once it's set up.