我正在使用Userin~/.ssh/config文件来指定 ansible 用于访问远程服务器的用户名,例如:
Host 123.234.098.076
User my_local_user_name
Run Code Online (Sandbox Code Playgroud)
有没有办法在 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"
Run Code Online (Sandbox Code Playgroud)
但是,我不确定ansible_user直接设置而不是remote_user在剧本、清单或 ansible 配置中使用设置的任何意外后果,例如:
---
- 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"
Run Code Online (Sandbox Code Playgroud)
如果您需要在建立连接后获取 ssh 用户并且有关目标主机的事实可用,您可以使用ansible_user_idfact。
如果您想在建立连接之前了解 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 }}"
Run Code Online (Sandbox Code Playgroud)
不确定是否ssh -G在每个系统上都可用。
如果你没有remote_user在 Ansible playbook 或清单中指定,它依赖 ssh 来建立连接,所以知道用户名的唯一方法是解析 ssh 配置文件,其中-Goption 派上用场。
| 归档时间: |
|
| 查看次数: |
2976 次 |
| 最近记录: |