Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Ansible v2, which variable stores the ssh username?

Tags:

ansible-2.x

In my playbooks, I SSH in as a non-root user, then use become to become root.

What is the Ansible variable name that stores the user that originally SSH'd into the box?

In Ansible < 2.0, I could use {{ ansible_ssh_user }} to access the username SSH'ing into the box.

Just tried with Ansible 2.0.2 and that returns null. I tried ansible_user as suggested by the FAQ, but that also returns null. I also tried ansible_user_id, but that returns the result of become, not the original user.

like image 666
Jeff Widman Avatar asked Jan 25 '16 10:01

Jeff Widman


People also ask

How to dynamically set Ansible SSH user based on hostname?

Create an additional Ansible role to dynamically set Ansible SSH user depending on the defined conditionals. The idea is very straightforward as it is based on the inventory hostname. Checks are performed locally, the defined Ansible SSH user fact is used later to perform the SSH connection.

How do I SSH into Ansible from V vagrant?

Set SSH username to vagrant if it does contain “ vagrant ” string. Set SSH username to ansible if it does not contain “ vagrant ” string. This step can be skipped as the default value can be set inside the Ansible configuration file. Check SSH connection using defined SSH user and register output.

How to pass secrets via environment variables in Ansible?

There is an idea that passing secrets via environment variables is more safe, than passing it via command line. Ansible has few methods to accept password: Store it somewhere in the file (inventory, secrets, group vars, etc). Use a ssh key from ssh agent.

Which variables override role defaults in Ansible inventory?

Host and/or inventory variables override role defaults, but explicit includes such as the vars directory or an include_vars task override inventory variables. Ansible merges different variables set in inventory so that more specific settings override more generic settings.


2 Answers

You can accesss this via ansible_env.SUDO_USER.

I tried a number of other variables, and almost all of them changed their values as soon as I used become on the remote node.

like image 133
Jeff Widman Avatar answered Dec 21 '22 19:12

Jeff Widman


{{ ansible_user }} does actually work fine for me with Ansible 2.5:

with_items:
  - root
  - "{{ ansible_user }}"
like image 31
debuglevel Avatar answered Dec 21 '22 20:12

debuglevel