1.使用 ssh-keygen -t rsa生成密鑰對
ssh-keygen -t rsa
2.推送單個公鑰到遠程機器
格式: ssh-copy-id -i ~/.ssh/id_rsa.pub username@[ip,hostname]
ssh-copy-id -i ~/.ssh/id_rsa.pub username@192.168.100.2
3.添加ansible hosts
編輯/etc/ansible/hosts,沒有則創建些文件。
格式:【主機名】 【主機地址】 【主機密碼】 默認是root用戶來進行的
[tomcat-servers]
1 ansible_ssh_user="tomcat" ansible_ssh_host=192.168.100.1 ansible_ssh_pass="test"
2 ansible_ssh_user="tomcat" ansible_ssh_host=192.168.100.2 ansible_ssh_pass="test"
新版的ansible(2.4) hosts有更新, 用以下方式:
[tomcat-servers]
192.168.100.1 ansible_user=tomcat ansible_ssh_pass="test" 192.168.100.2 ansible_user=tomcat ansible_ssh_pass="test"
4.批量推送公鑰到遠程機器
機器多的情況下,使用ssh-copy-id方法有些費時,使用ansible-playbook推送ymal,這里使用到了authoried_keys模塊,可以參考 http://docs.ansible.com/authorized_key_module.html
將以下文件命名為:push.ssh.ymal
# Using alternate directory locations:
- hosts: tomcat-servers
user: tomcat
tasks:
- name: ssh-copy
authorized_key: user=tomcat key="{{ lookup('file', '/home/tomcat/.ssh/id_rsa.pub') }}"
tags:
- sshkey
5.執行推送命令
ansible-playbook push.ssh.ymal
6.如若報錯,解決
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.
修改host_key_checking(默認是check的):
vi /home/xiangdong/ansible/ansible.cfg # uncomment this to disable SSH key host checking host_key_checking = False
7.測試
#查看各機器時間 ansible all -a date #ansible all -m command -a date # 作用同上 #ping ansible all -m ping
輸出結果:
$ ansible all -m ping 192.168.100.1 | SUCCESS => { "changed": false, "ping": "pong" }
參考:
1.http://mageedu.blog.51cto.com/4265610/1412028
2.http://www.justwinit.cn/post/8973/