Inventory ansible_user Overrides a Play's remote_user

In progress Ansible

In Ansible, connection variables such as ansible_user win over playbook keywords such as remote_user. A play that says remote_user: root still connects as the user named in the inventory's ansible_user. Nothing warns about it: the play runs as the wrong user and fails later, on whatever needed root.

How It Bites During Bootstrap

A playbook prepares fresh nodes that don't have sudo yet, so it connects as root directly:

- hosts: nodes
  remote_user: root
  tasks:
    - ansible.builtin.apt:
        name: sudo
        state: present

The inventory, written for later day-to-day runs, also sets the regular admin account:

all:
  vars:
    ansible_user: admin

Ansible logs in as admin, and apt fails with:

Failed to lock apt for exclusive operation

The message suggests another apt process; the real cause is that the task doesn't run as root.

Why the Inventory Wins

Ansible resolves settings in an order: configuration, then command-line options, then playbook keywords, then variables (with their own long precedence list), with -e extra vars last. remote_user is a keyword; ansible_user is a variable, so it overrides the keyword wherever it is defined.

Fixes

  • Use one mechanism: set ansible_user per group or host (a bootstrap group with ansible_user: root), or override on the command line (-u root is weaker than inventory vars; -e ansible_user=root wins).
  • Or connect as the regular user and escalate with become: true and become_method: su until sudo exists.

References

Review cards

Flashcard Why does inventory ansible_user beat a play's remote_user?

remote_user is a playbook keyword and ansible_user is a variable. Variables come later in Ansible's precedence order, so the variable wins wherever it is defined.

Flashcard What happens if a playbook that uses `remote_user: root` is run with an inventory that sets `ansible_user: admin`?

Ansible connects as the user named in the inventory's ansible_user, which in this case is admin. The task runs as admin, not root, leading to permission issues.