背景:按照公司要求每半年更新一次所有物理服務器的ssh登錄key。
舊key:/root/.ssh/antiykey.pub
新key:/root/.ssh/antiykey190708.pub
1,確保ansible能管理所有機器
確保可以ping通所有要操作的機器。
添加新key:
[root@xiaoxuan ansible]# cat addkey.xml
---
- hosts: antiy-all
remote_user: root
tasks:
- name: add key
authorized_key:
user: root
state: present
key: "{{ lookup('file', '/root/.ssh/antiykey190708.pub') }}"
[root@xiaoxuan ansible]#
hosts: antiy-all ###這個是我的ansible分組,這個組包含所有要更換的機器
authorized_key: ###使用ansible的這個模塊
state: present ###添加key
key: "{{ lookup('file', '/root/.ssh/antiykey190708.pub') }}" ###新key的路徑
[root@xiaoxuan ansible]# ansible-playbook addkey.xml
嗎買劈的,失敗了好多,等會檢查下,向是網絡問題,都是些需要用訪問的ip。
這個時候會生成一個文件,裏面記錄了失敗的ip
[root@xiaoxuan ansible]# ll addkey.retry
-rw-r--r-- 1 root root 1034 Jul 10 11:08 addkey.retry
[root@xiaoxuan ansible]#
查詢發現是文件屬性問題ansible key-fail -m shell -a "lsattr /root/.ssh/authorized_keys"
接着先刪除這個屬性[root@xiaoxuan ansible]# ansible key-fail -m shell -a "chattr -i /root/.ssh/authorized_keys"
再次查看已經刪除這個屬性
接着繼續執行添加key[root@xiaoxuan ansible]# ansible-playbook addkey.xml
搞定
到這裏添加就完成了。
注意:在操作刪除舊key之前一定要確保你的ansible可以使用新key管理所有機器,切記切記,免得給自己找麻煩。
刪除舊key:
[root@xiaoxuan ansible]# cat delkey.xml
---
- hosts: antiy-test
remote_user: root
tasks:
- name: add key
authorized_key:
user: root
state: absent
key: "{{ lookup('file', '/root/.ssh/antiykey.pub') }}"
[root@xiaoxuan ansible]#
執行ansible-playbook addkey.xml
先這樣吧。