如何为 Ansible 中的所有主机设置默认 ssh 用户?

How*_*Lee 18 ansible

Ansible 2.1 版

我有一个库存文件 hosts

[nodes]
host1
host2
...
Run Code Online (Sandbox Code Playgroud)

和一个简单的剧本 site.yml

---
- hosts: all
  tasks:
    - include: tasks/main.yml
Run Code Online (Sandbox Code Playgroud)

如果我刚开始玩

ansible-playbook -i hosts site.yml -vvvv
Run Code Online (Sandbox Code Playgroud)

我收到所有主机的这个错误,

ESTABLISH SSH CONNECTION FOR USER: None
fatal: [host1]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh.", "unreachable": true}
...
Run Code Online (Sandbox Code Playgroud)

然而,阅读Ansible Inventory文档,我添加ansible_userhosts文件中,

[nodes]
host1    ansible_user=root
host2    ansible_user=root
...
Run Code Online (Sandbox Code Playgroud)

这解决了SSH CONNECTION UNREACHABLE错误。但是,我必须ansible_user=root在所有主机旁边添加吗?或者有没有更简单的方法来做到这一点?

Del*_*tik 22

检查示例/默认ansible.cfg文件,您会在[defaults]以下位置找到它:

# default user to use for playbooks if user is not specified
# (/usr/bin/ansible will use current user as default)
#remote_user = root
Run Code Online (Sandbox Code Playgroud)

取消注释remote_user并将用户设置为您要登录的用户。

Ansible 从哪里获得ansible.cfg?同一个文件解释说:

# nearly all parameters can be overridden in ansible-playbook 
# or with command line flags. ansible will read ANSIBLE_CONFIG,
# ansible.cfg in the current working directory, .ansible.cfg in
# the home directory or /etc/ansible/ansible.cfg, whichever it
# finds first
Run Code Online (Sandbox Code Playgroud)


How*_*Lee 11

另一种方法是使用--user定义远程 ssh 用户。键入ansible-playbook --help以阅读更多信息。这是我的典型命令:

ansible-playbook -i hosts site.yml --user <user> --ask-pass -vvvv

--ask-pass 将提示输入密码 --user


小智 6

除了修改ansible.cfg,您还可以为“所有”组或其他组定义变量

https://docs.ansible.com/ansible/latest/user_guide/intro_inventory.html#group-variables

[all:vars]
ansible_user = root
ansible_port = 22
Run Code Online (Sandbox Code Playgroud)