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.
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.
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.
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.
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.
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.
{{ ansible_user }}
does actually work fine for me with Ansible 2.5:
with_items:
- root
- "{{ ansible_user }}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With