查找可应答的ssh用户



我使用~/.ssh/config文件中的User来指定可用于访问远程服务器的用户名,例如:

Host 123.234.098.076
User my_local_user_name

有没有办法在Ansible中找到该用户名?在以下行动手册中定义了ansible_user

---
- 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"

然而,我不确定直接设置ansible_user,而不是在剧本、库存或ansible配置(如:)中使用remote_user设置会产生任何意外后果

---
- 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"

如果您需要在连接完成并且有关目标主机的事实可用后获得ssh用户,则可以使用ansible_user_id事实。

如果您想在连接之前了解ssh用户,这里有一个技巧:

---
- 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 }}"

不确定ssh -G是否在每个系统上都可用。

如果您没有在Ansible playbook或inventory中指定remote_user,那么它依赖于ssh来建立连接,所以知道用户名的唯一方法是解析ssh配置文件,其中-G选项很有用。

最新更新