ansible配置免密

文件列表

group_vars/
└── all.yml               #填写'k8s_cluster_info'变量信息

inventory/                #填写主机信息
├── hosts

autossh/
├── files
│   └── ssh-key-gen.sh
├── tasks
│   └── main.yml
└── templates
    └── distribute_ssh_pubkey.sh.j2

1.ssh-key-gen.sh

#!/bin/bash
expect <<EOF
set timeout 10
spawn ssh-keygen -t rsa
expect "Enter file in which to save the key (/root/.ssh/id_rsa):"
send "\r"
expect "Enter passphrase (empty for no passphrase):"
send "\r"
expect "Enter same passphrase again:"
send "\r"
expect eof
EOF

2.main.yml

- name: remove exiting key or rsa file
  shell: rm -rf /root/.ssh/*

- name: crete dir save keypair
  file: name=/root/.ssh state=directory

- name: Install expect
  yum: name=expect state=latest

- name: copy ssh-key-gen.sh to nodes
  copy: src=./files/ssh-key-gen.sh dest=/root/.ssh/

- name: run ssh-key-gen.sh to create ssh key pair
  shell: "sh /root/.ssh/ssh-key-gen.sh"
  register: create
  changed_when: "'[SHA256]' in create.stdout"

- name: distribute ssh_pubkey script to nodes
  template: src=distribute_ssh_pubkey.sh.j2 dest=~/.ssh/distribute_ssh_pubkey.sh

- name: run script tp scp ssh_pubkey to nodes
  shell: "sh /root/.ssh/distribute_ssh_pubkey.sh"

- name: remove script files
  file: path=/root/.ssh/{{ item }} state=absent
  with_items:
    - distribute_ssh_pubkey.sh
    - ssh-key-gen.sh

3.distribute_ssh_pubkey.sh.j2

{% for item in k8s_cluster_info %}
expect <<EOF
spawn ssh-copy-id -i /root/.ssh/id_rsa.pub root@{{ item.ip }}
expect {
"*yes/no*" { send "yes\r"; exp_continue}
"*password:" { send "{{ ansible_ssh_pass }}\r" }
}
expect eof
EOF

{% endfor %}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值