Inventory ansible_user Overrides a Play's remote_user
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_userper group or host (abootstrapgroup withansible_user: root), or override on the command line (-u rootis weaker than inventory vars;-e ansible_user=rootwins). - Or connect as the regular user and escalate with
become: trueandbecome_method: suuntilsudoexists.
References
- DevOps and Infrastructure as Code MOC - hub for automation notes.
- Ansible become_method su Runs a Non-Login Shell Without sbin in PATH - the next trap when escalating with
su. - Ansible documentation: Controlling how Ansible behaves, precedence rules - why variables override keywords.
- Ansible documentation: Using variables, variable precedence - the full order.
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.