ansible playbook实现ssh之间互相免密访问
以下是基于python version = 3.6,python version = 3.6.8 jinja version = 3.0.3 版本的ansible实现一个playbook脚本,主要功能实现的是
192.168.1.61,192.168.1.62、192.168.1.63三台计算机
相互的ssh免密访问
脚本如下:
---
# 定义一个名为 ssh_key_exchange 的 playbook
- name: ssh_key_exchange
# 指定要操作的主机组,这里使用 ssh_nodes 表示所有主机
hosts: ssh_nodes
# 设置远程用户为 root
remote_user: root
vars:
ansible_user: "root"
ansible_password: "123"
ansible_user_dir: "/root"
ansible_ssh_common_args: '-o StrictHostKeyChecking=no'
# 定义任务
tasks:
# 任务 1:检查 SSH 密钥对是否存在,如果不存在则生成
- name: Generate SSH key if it doesn't exist
# 使用 openssh_keypair 模块生成 SSH 密钥对
openssh_keypair:
path: ~/.ssh/id_rsa
state: present
# 记录任务执行结果
register: ssh_key_result
# 只在 SSH 密钥对不存在时执行此任务
when: ssh_key_result.changed
ignore_errors: true
# 任务 2:获取 SSH 公钥内容
- name: Get public key content
# 使用 slurp 模块获取 SSH 公钥文件的内容
slurp:
src: ~/.ssh/id_rsa.pub
# 记录任务执行结果
register: public_key
# 任务 3:将公钥内容存储为变量
- name: Set public key as a fact
# 设置一个名为 host_public_key 的事实变量,存储 SSH 公钥内容
set_fact:
host_public_key: "{{ public_key['content'] | b64decode }}"
# 定义另一个名为 distribute_public_keys 的 playbook
- name: distribute_public_keys
# 指定要操作的主机组,这里使用 ssh_nodes 表示所有主机
hosts: ssh_nodes
# 设置远程用户为 root
remote_user: root
vars:
ansible_user: "root"
ansible_password: "123"
ansible_user_dir: "/root"
ansible_ssh_common_args: '-o StrictHostKeyChecking=no'
# 定义任务
tasks:
#测试
- name: Loop through all hosts and display custom variable
debug:
msg: "The custom variable on {{ item }} is {{ hostvars[item] }}"
loop: "{{ groups['ssh_nodes'] }}"
# 任务 4:将每台主机的公钥分发到其他所有主机的 authorized_keys 文件中
- name: Distribute public keys to all hosts
# 使用 authorized_key 模块将公钥添加到 authorized_keys 文件中
authorized_key:
user: root
key: "{{ hostvars[item]['host_public_key'] }}"
# 遍历所有主机
loop: "{{ groups['ssh_nodes'] }}"