ansible批量推送公钥

官方文档

使用ssh-keygen -t rsa生成密钥对

1
ssh-keygen -t rsa

添加ansible hosts

1
2
3
4
5
$ cat /etc/ansible/hosts
[web]
192.168.56.102 ansible_ssh_user=root ansible_ssh_pass=root ansible_ssh_port=22
192.168.56.103 ansible_ssh_user=root ansible_ssh_pass=root ansible_ssh_port=22
192.168.56.104 ansible_ssh_user=root ansible_ssh_pass=root ansible_ssh_port=22

修改ansible.cfg

1
2
host_key_checking=False
# 不用检查host key

编写yaml文件

注意文件格式,不要用tab

1
2
3
4
5
6
7
8
$ cat push-ssh.yaml
- hosts: web
user: root
tasks:
- name: ssh-key-copy
authorized_key: user=root key="{{ lookup('file','/root/.ssh/id_rsa.pub')}}"
tags:
- sshkey

批量推送

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$ ansible-playbook push-ssh.yaml
PLAY [web] ***************************************************************************************************************************************************
TASK [Gathering Facts] ***************************************************************************************************************************************
ok: [192.168.56.104]
ok: [192.168.56.103]
ok: [192.168.56.102]
TASK [ssh-key-copy] ******************************************************************************************************************************************
changed: [192.168.56.104]
changed: [192.168.56.102]
changed: [192.168.56.103]
PLAY RECAP ***************************************************************************************************************************************************
192.168.56.102 : ok=2 changed=1 unreachable=0 failed=0
192.168.56.103 : ok=2 changed=1 unreachable=0 failed=0
192.168.56.104 : ok=2 changed=1 unreachable=0 failed=0

验证

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[root@localhost ~]# ssh root@192.168.56.102
Last login: Fri Jul 14 15:56:00 2017 from 192.168.56.101
[root@localhost ~]#
[root@localhost ~]# exit
登出
Connection to 192.168.56.102 closed.
[root@localhost ~]# ssh root@192.168.56.102
Last login: Fri Jul 14 15:56:10 2017 from 192.168.56.101
[root@localhost ~]# exit
登出
Connection to 192.168.56.102 closed.
[root@localhost ~]# ssh root@192.168.56.103
Last login: Fri Jul 14 15:56:00 2017 from 192.168.56.101
[root@localhost ~]# exit
登出
Connection to 192.168.56.103 closed

当前网速较慢或者你使用的浏览器不支持博客特定功能,请尝试刷新或换用Chrome、Firefox等现代浏览器