Reputation: 28463
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"
Upvotes: 7
Views: 5474
Reputation: 68269
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.
Upvotes: 7