原理:ansible控制节点在和托管节点在通信时是通过openssh建立的,所以控制节点在和托管节点建立通信时肯定需要账号和密码的认证!每次执行任务都需要输入账号和密码在使用过程当中是很不方便的!所以我们这里要建立起控制节点和托管节点的授信配置,通过公钥认证来实现控制节点和托管节点ssh的无密码连接!
环境:
ansible控制节点: 10.0.0.43
托管节点:10.0.0.44
方法一:
1.编辑/etc/ansible/hosts
[root@c7 ~]# vim /etc/ansible/hosts
[web]
10.0.0.44 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass=123456
ansible_ssh_port=22 :远程主机登陆端口
ansible_ssh_user=root :远程主机登陆用户名
ansible_ssh_pass=123456 :远程主机登陆用户名的密码
2.ssh-keyscan:是用来保存到known_hosts里面免除首次登录需要输入yes,但是如果直接保存到authorized_keys里面,就不会生效。
[root@c7 ~]# ssh-keyscan 10.0.0.44 >> /root/.ssh/known_hosts
3.验证
[root@c7 ~]# ansible web -m ping
10.0.0.44 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
可能遇到的问题:root 目录下没有.ssh目录
解决方法:
[root@c7 ~]# ssh localhost
原因:
.ssh 是记录密码信息的文件夹,如果没有登录过root的话,就没有 .ssh 文件夹,因此登录 localhost ,并输入密码就会生成了。
方法二:
手动配置免密码认证
1.编辑/etc/ansible/hosts
[root@c7 ~]# vim /etc/ansible/hosts
[web]
10.0.0.44
2.生成密钥对
[root@c7 .ssh]# ssh-keygen (一直回车)
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:kd8LqaUWG2MKc8V6fSmVDQ8PlTbMCyrjwKkNnUEhgyk root@c7.7-44
The key's randomart image is:
+---[RSA 2048]----+
| oo.o. ++.. |
|E o o.. . .O* |
| . o += .oo+o |
| . *oo+.+ .. |
| o+ooSoB + |
| .+.+.O + . |
| . = . |
| . |
| |
+----[SHA256]-----+
3.拷贝公钥到目标主机
[root@c7 .ssh]# cd /root/.ssh/
[root@c7 .ssh]# ssh-copy-id -i id_rsa.pub root@10.0.0.44
4.验证
[root@c7 ~]# ansible web -m ping
10.0.0.44 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}