12323452345345

ansible用authorized_key模块批量推送密钥到受控主机实现免密登录

一,ansible的authorized_key模块的用途

用来配置密钥实现免密登录:

ansible所在的主控机生成密钥后,如何把公钥上传到受控端?

当然可以用ssh-copy-id命令逐台手动处理,如果受控端机器数量不多当然没问题,

但如果机器数量较多,有几十几百台时,手动处理的效率就成为问题。

authorized_key模块就用来把公钥上传到各台服务器实现免密登录

二,authorized_key的使用例子:

1,在hosts中增加一个段:

[test]
192.168.0.87:22 ansible_ssh_user=root ansible_ssh_pass="rootpass"
192.168.0.88:22 ansible_ssh_user=root ansible_ssh_pass="rootpass" 
192.168.0.89:22 ansible_ssh_user=root ansible_ssh_pass="rootpass" 

批量上传公钥

[root@centos8 ~]# ansible ils -m authorized_key -a "user=root state=present key='{{ lookup('file', '/home/liuhongdi/.ssh/id_rsa.pub') }}'"

 出现报错:

192.168.0.87 | FAILED! => {
    "msg": "Using a SSH password instead of a key is not possible because Host Key checking is enabled and sshpass does not support this. 
            Please add this host's fingerprint to your known_hosts file to manage this host."
}

问题的原因:

ssh第一次连接的时候一般会提示fingerprint key字符串,需要输入yes 进行确认.

确认后会把key字符串加入到 ~/.ssh/known_hosts 文件中

解决办法:

修改ansible的配置文件:

[root@centos8 ~]# vi /etc/ansible/ansible.cfg 

把这一行的注释去掉: 

host_key_checking = False

说明:这一行的作用:

# uncomment this to disable SSH key host checking

用来禁止ssh的指纹key字串检查

2,再次上传公钥到服务器:

[root@centos8 ~]# ansible ils -m authorized_key -a "user=root state=present key='{{ lookup('file', '/root/.ssh/id_rsa.pub') }}'"
192.168.0.87 | CHANGED => {

成功了

手动测试一下:看ssh到目标服务器是否还需要输入密码?

[root@centos8 ~]# ssh -p 22 root@192.168.0.87

三,查看ansible版本

[root@centos8 liuhongdi]# ansible --version
ansible 2.9.5
posted @ 2022-07-19 10:19  ZHappy-Blog  阅读(404)  评论(0)    收藏  举报