学习备忘录,附带代码块儿,方便今后工作批量部署ssh公钥
ansible’s module: authorized_key
ansible安装方式忽略,直接使用authorized_keys模块可以减少 输入ssh-copy-id xx->yes->输入密码 的繁琐流程,大大简化了大家的工作量。
AD-Hoc部署
首先对管理集群建立统一账号,本文以root为例,基于企业安全,可设置其他可sudo的用户,大同小异:
username: root
passwd: root
port:22
下面例子仅以一条数据为例,实际中可能下面的数据是上百条,需要提前按照格式写好配置:
#cat >> /etc/ansible/hosts <-EOF
>[test]
>192.168.240.20 ansible_ssh_user="root" ansible_ssh_pass="root" ansible_ssh_port=22
>EOF
关闭ansible的host_key_checking:
#sed -ri '/^#host_key/c\host_key_checking=false/' /etc/ansible/ansible.cfg
测试被管理机器是否可以通过ssh协议连接:
#ansible test -m ping
192.168.240.20 | SUCCESS => {
"changed": false,
"ping": "pong"
}
可以看到没有问题,这时候借助authorized_key模块完成批量推送任务:
#ansible test -m authorized_key -a "user=root key='{{ lookup('file','/root/.ssh/id_rsa.pub') }}'"
192.168.240.20 | CHANGED => {
"changed": true,
"comment": null,
"exclusive": false,
"follow": false,
"key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQA…………
"key_options": null,
"keyfile": "/root/.ssh/authorized_keys",
"manage_dir": true,
"path": null,
"state": "present",
"unique": false,
"user": "root",
"validate_certs": true
}
测试结果:ssh 192.168.240.20 发现无需再输入密码。
PlayBook部署
直到ansible test -m ping都是一样的,在当前目录下编辑一个ssh_push.yaml文件:
#轧马路标准格式文件,缩进很重要
#script_name:ssh_push.yaml
- hosts: test
user: root
tasks:
- name: ssh-copy
authorized_key:
user: root
key: "{{ lookup('file','/root/.ssh/id_rsa.pub') }}"
...
执行结果如下:
# ansible-playbook ssh_push.yaml
PLAY [test] ********************************************************************************
TASK [Gathering Facts] *********************************************************************
ok: [192.168.240.20]
TASK [ssh-copy] ****************************************************************************
changed: [192.168.240.20]
PLAY RECAP *********************************************************************************
192.168.240.20 : ok=2 changed=1 unreachable=0 failed=0
测试结果:ssh 192.168.240.20 发现无需再输入密码。