I'm using the User
in ~/.ssh/config
file to specify the user name ansible uses to access the remote server, for example:
Host 123.234.098.076
User my_local_user_name
Is there a way to find that user name in Ansible? In the following playbook ansible_user
is defined:
---
- hosts: "all"
tasks:
- name: "perform whoami"
shell: whoami
register: whoami
- set_fact:
ansible_user: "{{ whoami.stdout }}"
- debug:
msg: "I am user: {{ ansible_user }}" # will display: "I am user: my_local_user_name"
However I'm not sure of any unintended consequences of setting the ansible_user
directly as opposed to using the remote_user
setting in the playbook, in the inventory or in the ansible config such as:
---
- hosts: "all"
remote_user: my_local_user_name
tasks:
#- name: "perform whoami"
# shell: whoami
# register: whoami
#- set_fact:
# ansible_user: "{{ whoami.stdout }}"
- debug:
msg: "I am user: {{ ansible_user }}" # will display: "I am user: my_local_user_name"
Ansible uses your local user (eg Mike) to ssh to the remote machine.
You can simply use the getent module. If the user is present, the play will continue. If the user does not exist, the play will fail. Save this answer.
Open the default hosts file (/etc/ansible/hosts) using your favorite text editor to see what an Ansible hosts file looks like. By default, Ansible looks for the hosts in the /etc/ansible/hosts file. The default inventory file contains different examples you can use as references while setting up your inventory.
By default, Ansible assumes you are using SSH keys to connect to remote machines. SSH keys are encouraged, but you can use password authentication if needed with the --ask-pass option. If you need to provide a password for privilege escalation (sudo, pbrun, and so on), use --ask-become-pass .
If you need to get ssh user after connection has been made and facts about target host are available, you can use ansible_user_id
fact.
If you want to know ssh user before connection has been made, here is a trick:
---
- hosts: all
gather_facts: no
tasks:
- name: Save our destination host
set_fact: dest_host="{{ ansible_host }}"
- name: Get user from local ssh config
local_action: shell ssh -G {{ dest_host }} | awk '/^user /{ print $2 }'
changed_when: false
register: ssh_user
- name: Print forced ansible_user if defined or username from ssh config otherwize
debug: msg="Ansible will connect with {{ ansible_user | default(ssh_user.stdout) }}"
- hosts: all
gather_facts: yes
tasks:
- name: Print our remote name
debug: msg="Ansible connected with {{ ansible_user_id }}"
Not sure if ssh -G
is available on every system.
If you don't specify remote_user
in Ansible playbook or inventory, it relies on ssh to make the connection, so the only way to know username is to parse ssh config files, where -G
option comes in handy.
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