使用交互 shell 推送公钥证书:
#!/bin/bash yum install -y expect #安装 expect # set_ssh_keys.sh password="123123" ## 主机的密码,每个主机的密码要求一样 auto_ssh_copy_id() { expect -c "set timeout -1; spawn ssh-copy-id -i $2; expect { (yes/no) {send -- yesr;exp_continue;} assword: {send -- $1r;exp_continue;} eof {exit 0;} }"; } for i in $(</root/hosts) ##主机ip文件,一行一个 do auto_ssh_copy_id $password $i done
使用 xml 配置:
vi key.yml
--- - name: Useage:sudo ansible-playbook -i hosts.ini(iplist) xiaoniu-authorized-key.yml -e "hosts=all user=ops " -t authorized-key -k remote_user: root hosts: localhost gather_facts: False - hosts: "{{ hosts }}" remote_user: root gather_facts: no tasks: - name: create user on ansible server to provide pubkey user: name="{{ user }}" generate_ssh_key=yes ssh_key_type=rsa ssh_key_bits=2048 ssh_key_file=.ssh/id_rsa state=present tags: authorized-key - hosts: "{{ hosts }}" remote_user: root tasks: - name: create user on remote host as ansible remote_user user: name="{{ user }}" state=present tags: authorized-key - set_fact: lookup_file_path="/root/.ssh/id_rsa.pub" when: user == "root" tags: authorized-key - set_fact: lookup_file_path="{{ '/home/'+user+'/.ssh/id_rsa.pub' }}" when: user != "root" tags: authorized-key - name: copy id_rsa.pub to remote host for authorized trust authorized_key: user="{{ user }}" key="{{ lookup('file',lookup_file_path) }}" tags: authorized-key
执行配置:
ansible-playbook key.yml -e "hosts=all user=root" -k ansible-playbook key.yml -e "hosts=dev user=root" -k