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

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

Ansible 版本 2.1

我有一个库存文件hosts

[nodes]
host1
host2
...

一个简单的剧本site.yml

---
- hosts: all
  tasks:
    - include: tasks/main.yml

如果我刚开始表演,

ansible-playbook -i hosts site.yml -vvvv

我在所有主机上都遇到此错误,

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

然而,阅读Ansible 库存doc,我添加ansible_userhosts文件中,

[nodes]
host1    ansible_user=root
host2    ansible_user=root
...

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

答案1

检查示例/默认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

取消注释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

答案2

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

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

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

答案3

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

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

[all:vars]
ansible_user = root
ansible_port = 22

相关内容