ansible實現SSH配置免密互信


Ansible是用來處理大批量重復性操作的工具,只需要在一台機器上就可以遠程控制所有機器,但前提是必須保證每台機器之間SSH可以相互免密登錄。關於Ansible的安裝和環境准備請參考Ansible環境的准備。

注: 有關Ansible的所有操作只需在第一台機器上修改和執行,其它機器只需知道IP地址即可。

 

免密安裝機器


172.18.18.120 

172.18.18.121

172.18.18.122

 

配置所有免密機器用戶名及密碼


編輯/etc/ansible/hosts 文件增加配置如下:

[ssh]
172.18.18.120 ansible_ssh_user=root ansible_ssh_pass=123456
172.18.18.121 ansible_ssh_user=root ansible_ssh_pass=123456
172.18.18.122 ansible_ssh_user=root ansible_ssh_pass=123456

 

編寫yml執行文件

編輯/opt/ansible/sshKey.yml文件如下:

- hosts: ssh
  gather_facts: no


  tasks:
    - name: enforce env   
      shell: source /etc/profile
      run_once: true
    - name: close ssh check  #關閉初次訪問提示詢問   
      shell: sed -i "s/^.*StrictHostKeyChecking.*$/   StrictHostKeyChecking no/g" /etc/ssh/ssh_config
    - name: delete /root/.ssh/
      file: path=/root/.ssh/ state=absent
    - name: generating public/private rsa key pair  #生成公鑰和私鑰
      shell: ssh-keygen -t rsa -b 2048 -N '' -f /root/.ssh/id_rsa
    - name: delete /tmp/ssh/ dir
      file: path=/tmp/ssh/ state=absent
      run_once: true
    - name: fetch copy  #從各宿主機將公鑰拷貝到本機
      fetch: src=/root/.ssh/id_rsa.pub dest=/tmp/ssh/
    - name: append file authorized_keys.log  #將各個公鑰合並成一個文件
      shell: find /tmp/ssh/* -type f -exec sh -c 'cat {}>>/tmp/ssh/authorized_keys.log' \;
      run_once: true
    - name: copy authorized_keys  #將合成的公鑰進行分發
      copy: src=/tmp/ssh/authorized_keys.log dest=/root/.ssh/authorized_keys mode=0600
      tags:
       - install ssh

 

 

 

 

 

 

 

 

 

 

 

 

 

 

執行免密安裝

ansible-playbook  /opt/ansible/sshKey.yml

 

 

 


免責聲明!

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



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