Ansible批量添加主機


一、管理端生成RSA公鑰

ssh-keygen -t rsa

二、單台添加目標主機

ssh-copy-id root@10.0.0.21
輸入密碼后免密連接建立

三、批量添加目標主機

1.在/etc/ansible/hosts中編輯要批量添加的主機組

[GROUP-CC]
 aaa ansible_connection=ssh ansible_user=root ansible_ssh_pass="111111"
 bbb ansible_connection=ssh ansible_user=root ansible_ssh_pass="222222"
 ccc ansible_connection=ssh ansible_user=root ansible_ssh_pass="333333"
 ddd ansible_connection=ssh ansible_user=root ansible_ssh_pass="444444"
 eee ansible_connection=ssh ansible_user=root ansible_ssh_pass="555555"

2.編輯推送公鑰的yaml文件

cat /etc/ansible/roles/ssh_key/ssh-key.yaml,為了保證sshd權限統一,可以統一sshd_config配置並重啟sshd,sshd_config提前放置在files目錄下。

執行方法 ansible-playbook ssh-key.yaml -e "remote_ip=xx.xx.xx.xx" -k

- hosts: '{{ remote_ip }}'
  gather_facts: false
  #不收集遠程主機信息
  user: root

  tasks:
  - name: ssh-copy
    authorized_key:
      user: root
      key: "{{ lookup('file', '/root/.ssh/id_rsa.pub') }}"
      #本地讀取公鑰位置
      path: '/root/.ssh/authorized_keys'
      state: present
      #present添加 absent刪除
      exclusive: no
      #是否移除authorized_keys文件中其它非指定key

  - name: cpsshd
    copy: src=sshd_config dest=/etc/ssh/sshd_config

  - name: Restart the sshd service
    service:
      name: sshd
      state: restarted

  

3.測試並完成推送

ansible-playbook -C /etc/ansible/roles/ssh_key/ssh-key.yaml
ansible-playbook  /etc/ansible/roles/ssh_key/ssh-key.yaml  

  

 四、常見問題處理

1、權限問題 

192.168.200.111 | UNREACHABLE! => {
    "changed": false, 
    "msg": "Failed to connect to the host via ssh: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).\r\n", 
    "unreachable": true
}

  出現上面問題的原因一般為用戶ssh權限問題,需檢查ansible使用的連接用戶是否有ssh的權限

  root用戶時,需要目標機sshd_config開啟如下配置

PermitRootLogin yes
StrictModes no

sed -i 's/#PermitRootLogin prohibit-password/PermitRootLogin\ yes/g' /etc/ssh/sshd_config
sed -i 's/#StrictModes yes/StrictModes\ no/g' /etc/ssh/sshd_config

  

2、非root用戶,需要在/etc/ansible/hosts或者自定義的inventory.ini中指定用戶ansible_user=XXX,

[GROUP-CC]
 aaa ansible_connection=ssh ansible_user=root ansible_ssh_pass="111111"
 bbb ansible_connection=ssh ansible_user=root ansible_ssh_pass="222222"

       自定義該用戶公鑰並發送

ssh-keygen -t rsa #注意第一步時需要指定路徑和鑰匙名稱 /home/aaa/.ssh/ansibleaaa
ssh-copy-id -i /home/aaa/.ssh/ansibleaaa aaa

  指定公鑰

ansible aaa -m ping --private-key=/home/aaa/.ssh/ansibleaaa

  可以根據需要在管理端的~/.ssh/中添加一個映射用的config文件

  cat ~/.ssh/config

#Host    hostname
#user    username
Host    host1
user    user1
Host    host2
user    user2
#在ssh時,系統會根據Host的映射關系選擇連接的用戶,只要用ssh連接host2,就會默認用user2用戶連接

 

  

 


免責聲明!

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



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