5

In group_vars/all.yml I defined a default remote user:

ansible_user: blackknight

But in some cases I like to override that on the command line:

% ansible-playbook -u kingarthur test.yml

test.yml is a simple debug playbook

- hosts: localhost
  tasks:
    - debug: var=ansible_user

when executing it tells me "ansible_user": "blackknight".

How should I change my variables or playbook to have a non-standard ansible_user, but still allow it to specify on the command line (so that the command line option takes precedences over my default in the variables)?

MacFreek
  • 171

1 Answers1

11

From the docs:

Using -e extra variables at the command line

To override all other settings in all other categories, you can use extra variables: --extra-vars or -e at the command line. Values passed with -e are variables, not command-line options, and they will override configuration settings, command-line options, and playbook keywords as well as variables set elsewhere. For example, this task will connect as brian not as carol:

ansible -u carol -e 'ansible_user=brian' -a whoami all

You must specify both the variable name and the value with --extra-vars.

muru
  • 72,889
  • 1
    Thanks for the pointer! Somehow, I missed that part, only reading the top of that page which said that command line takes precedence over variables. That is true for -e for not true for -u. Feels odd to me that these two options behave so differently. Must be an ansible quirk. – MacFreek Oct 09 '19 at 08:23
  • @MacFreek I think what they mean to say is that: options > variables (from inventory, etc.), but variables from -e > options > variables (from inventory, etc.). It's not specific to -u. – muru Oct 09 '19 at 08:24
  • 1
    Indeed, being new to Ansible, I somehow expected all command line options to have equal precedence, but it seems that some command line options are more equal than others ;) (and now I learned about -e. I didn't look further when I discovered -u) – MacFreek Oct 09 '19 at 08:26
  • 2
    I should have read the documentation better. https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#variable-precedence-where-should-i-put-a-variable – MacFreek Oct 09 '19 at 08:46