文件列表
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 %}