ansible用authorized_key模塊批量推送密鑰到受控主機(免密登錄)(ansible2.9.5)


一,ansible的authorized_key模塊的用途

用來配置密鑰實現免密登錄:

ansible所在的主控機生成密鑰后,如何把公鑰上傳到受控端?

當然可以用ssh-copy-id命令逐台手動處理,如果受控端機器數量不多當然沒問題,

但如果機器數量較多,有幾十幾百台時,手動處理的效率就成為問題。

authorized_key模塊就用來把公鑰上傳到各台服務器實現免密登錄

 

說明:劉宏締的架構森林是一個專注架構的博客,地址:https://www.cnblogs.com/architectforest

         對應的源碼可以訪問這里獲取: https://github.com/liuhongdi/

說明:作者:劉宏締 郵箱: 371125307@qq.com

 

二,authorized_key的使用例子:

1,在hosts中增加一個段:

[ils]
121.122.123.87:12888 ansible_ssh_user=webop ansible_ssh_pass="weboppass"
121.122.123.88:12888 ansible_ssh_user=webop ansible_ssh_pass="weboppass" 
121.122.123.89:12888 ansible_ssh_user=webop ansible_ssh_pass="weboppass" 

 

批量上傳公鑰

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

 出現報錯:

121.122.123.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=webop state=present key='{{ lookup('file', '/home/liuhongdi/.ssh/id_rsa.pub') }}'"
121.122.123.87 | CHANGED => {

 

成功了

手動測試一下:看ssh到目標服務器是否還需要輸入密碼?

[root@centos8 ~]# ssh -p 12888 webop@121.122.123.87

 

三,查看ansible版本

[root@centos8 liuhongdi]# ansible --version
ansible 2.9.5

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM