Ansible批量密钥

一、前提说明

1、需求说明

authorized_key模块就用来把公钥上传到各台服务器实现免密登录,目的是解决机器数量多,有几十几百台时,手动处理ssh密钥分发的低效率问题。

密钥分发前效果 :

2、在ansible节点上生成密钥文件
ssh-keygent
3、定义配置
mkdir ansible-ssh
vim ansible-ssh/ansible.cfg
[defaults]
inventory = /etc/ansible/hosts
forks = 5
sudo_user = root
remote_port = 22
host_key_checking = False
timeout = 10
log_path = /var/log/ansible.log
roles_path = .
command_warnings=False
module_lang  = zh_CN.UTF-8
module_set_locale = True
4、指定主机组
vim ansible-ssh/hosts
# 要求做免密的主机用户名密钥都要一致
[ssh-copy]
10.0.0.16
10.0.0.15
10.0.0.14

[ssh-copy:vars]
ansible_ssh_user="root"
ansible_ssh_pass="123123"
ansible_ssh_port="22"
5、定义剧本
vim ansible-ssh/ssh-copy-key.yml
- hosts: ssh-copy
  gather_facts: false
  tasks:
  - name: add authorized_keys
    authorized_key:
      user: root
      key: "{{ lookup('file', '/root/.ssh/id_rsa.pub') }}"
      state: present
      exclusive: no
ansible-playbook -i hosts ssh-copy-key.yml

剧本执行后下发密钥效果 :