Using `remote_user` in `ansible_ssh_common_args` in inventory file

1,275 views
Skip to first unread message

tariver 16

unread,
Apr 9, 2021, 2:45:06 AM4/9/21
to Ansible Project

Greetings!
Asked this on stackoverflow but received no answer, so trying my luck here.

In my network there is one server (server2) that can't be accessed directly. First you have to ssh to server1 and from there to server2.

My config file has the following line:
remote_user = foo.bar

My inventory:
hosts:
  server1:
    ansible_host: 10.0.0.1
  server2:
    ansible_host: 10.0.0.2 ansible_ssh_common_args: '-o ProxyCommand="ssh -W %h:%p -q foo...@10.0.0.1"'

This works fine, but I don't want the user name to be hardcoded. Here and here there are examples that remote_user can be passed via {{ ansible_ssh_user }} but I can't get it to work.

What I tried:
ansible_ssh_common_args: '-o ProxyCommand="ssh -W %h:%p -q {{ ansible_ssh_user }}@10.0.0.1"'

Also tried {{ ansible_user }} and {{ user }}. But when I run ansible server2 -m ping I get an error:
"The field 'ssh_common_args' has an invalid value, which includes an undefined variable. The error was: 'ansible_user' is undefined"

Is it possible to use user defined by remote_user in ansible_ssh_common_args?

Brian Coca

unread,
Apr 9, 2021, 12:04:37 PM4/9/21
to Ansible Project
Only if you set ansible_ssh_user previously, the connection
information won't be 'recursive' to itself.

That said, in future you could use this lookup to get the 'resolved'
remote_user for the connection plugin
https://github.com/ansible/ansible/pull/74186

--
----------
Brian Coca

tariver 16

unread,
Apr 9, 2021, 12:21:31 PM4/9/21
to Ansible Project
Thank you for your answer.

Yes it works if I set ansible_ssh_user as variable in the inventory file, but for my purpose it's the same as hardcoding it. What I want to do is to share this with my colleagues, so they can also use it without making any changes.

You can use this global variable in the playbook. As an example:
- name: Playbook to test default user
  hosts: all
  gather_facts: false
  tasks:
  - name: Print default users
    debug:
      var: ansible_user

When I run it with ansible-playbook test-default-user.yml --limit server1 I get

ok: [server1] => {
    "ansible_user": "foo.bar"
}

Also works with ansible_ssh_user. So I thought it's the same with the inventory.

Brian Coca

unread,
Apr 12, 2021, 12:33:34 PM4/12/21
to Ansible Project
It 'works' in certain cases and debug is a bad example of that, once
the PR I linked is merged we will probably deprecate any updates to
ansible_* vars as they are currently inconsistent and many times wrong
(especially when you consider loops).



--
----------
Brian Coca

tariver 16

unread,
Apr 13, 2021, 2:09:53 AM4/13/21
to Ansible Project
Thanks for your answer. I'll wait for the new version then and rewrite my inventory according to it.
Reply all
Reply to author
Forward
0 new messages