Esteban
Esteban

Reputation: 2579

Can I set remote_user in host_vars or group_vars?

I'm starting to write my first serious playbook in ansible.

Something I'd like to do is to specify different remote_user values per host. I'm able to set remote_user in ansible.cfg, through the CLI -u option and even in play variables, like so:

---
- name: install dependencies
  hosts: all
  sudo: yes
  vars:
    remote_user: username

But setting the var at the host or group level (which makes the most sense for my approach) won't work. For instance, having this file as group_vars/all gets me an "Authentication failure" fatal error:

---
remote_user: username

What am I missing?

Upvotes: 2

Views: 6283

Answers (3)

njnygaard
njnygaard

Reputation: 75

You can specify ansible_ssh_user in group_vars/all.yaml.

remote_user documentation.

(Documenting because I just run in to this quirk in 2023 on ansible [core 2.14.1])

Upvotes: 1

dada513
dada513

Reputation: 33

In your group or host vars add a new one with a name like playbook_username, then in your playbook change remote_user to something like this - remote_user: "{{ playbook_username }}"

Normally host variables don't seem to overwrite remote_user, but this workaround works well enough

Upvotes: 0

Antonis Christofides
Antonis Christofides

Reputation: 6939

What you are doing appears to be undocumented. Specifically, you have this:

vars:
  remote_user: username

when, according to the documentation, it should be like this:

remote_user: username

The fact that it happened to work when you did it the wrong way is irrelevant. There is some side effect that makes it work in that case, but of course it won't work in another case, and it may behave differently in different Ansible versions.

To log on as a different user in each host, the usual way is to specify ansible_ssh_user in the inventory. Whether this is a variable that can be overridden in host_vars or group_vars I'm not certain. See also issue 4688 for information about how ansible_ssh_user and remote_user may override each other.

Upvotes: 3

Related Questions