Ansible控制机分发ssh密钥
这个需求也可以使用脚本和sshpass解决,但不如ansible方便
- hosts: k8s
gather_facts: no
tasks:
# 修改StrictHostKeyChecking为no
- lineinfile:
path: /etc/ssh/ssh_config
regexp: '(.*)StrictHostKeyChecking(.*)'
line: "StrictHostKeyChecking no"
# 删除/root/.ssh/
- name: delete /root/.ssh/
file:
path: /root/.ssh/
state: absent
# 创建一个新的 /root/.ssh/ 目录,设置权限为0600只有root用户可以读写
- name: create .ssh directory
file:
dest: /root/.ssh
mode: 0600
state: directory
# 在本地生成一个RSA密钥对
- name: generating local public/private rsa key pair
local_action: shell ssh-keygen -t rsa -b 2048 -N '' -f /root/.ssh/id_rsa
# 查看生成的公钥 id_rsa.pub,存储在sshinfo
- name: view id_rsa.pub
local_action: shell cat /root/.ssh/id_rsa.pub
register: sshinfo
# set_fact自定义facts变量,然后将sshinfo这个register的标准输出赋值给sshpub
- set_fact:
sshpub: "{{sshinfo.stdout}}"
# 将sshpub(即公钥内容)写入authorized_keys.j2,假设这是它的路径
local_action: shell echo {{sshpub}} > /templates/authorized_keys.j2
# 使用template将authorized_keys.j2复制到所有目标主机的 /root/.ssh/authorized_keys
- name: copy authorized_keys.j2 to all
template:
src: "/templates/authorized_keys.j2"
dest: /root/.ssh/authorized_keys
mode: 0600
# 给一个tags
tags:
- k8s
- 自动化