ansible playbook 配置主机组内ssh免密登录
工作中有这个需求,本想着谷歌一个playbook拿来直接用,搜了半天没找到,看来这个需求比较偏门,记录一下,以备不时之需。
需要自己先在/etc/ansible/hosts 里定义好主机组,执行playbook后先输入主机组名称,以及需要免密登录的用户名。
- hosts: "{{ host_group_name }}"
gather_facts: no
vars_prompt:
- name: "host_group_name"
prompt: "Please input the host group name(The host group name is defined in /etc/ansible/hosts)"
private: no
- name: "user_name"
prompt: "Please input the username,that you want to create ssh password-free login"
private: no
tasks:
- name: check id_rsa
stat:
path: /root/.ssh/id_rsa.pub
register: rootsshkey
- name: check id_rsa
stat:
path: /home/"{{user_name}}"/.ssh/id_rsa.pub
register: nonrootsshkey
- name: enforce env
shell: source /etc/profile
- name: close ssh check #关闭第一次ssh连接的提示
shell: sed -i "s/^.*StrictHostKeyChecking.*$/ StrictHostKeyChecking no/g" /etc/ssh/ssh_config
- name: delete /root/.ssh/
file: path=/root/.ssh/ state=absent
when:
- user_name == 'root'
- name: delete /home/{{user_name}}/.ssh/
file: path=/home/{{user_name}}/.ssh/ state=absent
when:
- user_name != 'root'
- name: generating public/private rsa key pair #root用户生成公钥和私钥
shell: ssh-keygen -t rsa -b 2048 -N '' -f /root/.ssh/id_rsa
when: (user_name == 'root') and (rootsshkey.stat.exists == False)
- name: generating public/private rsa key pair #非root用户生成公钥和私钥
become: yes
become_method: su
become_user: "{{user_name}}"
shell: ssh-keygen -t rsa -b 2048 -N '' -f /home/{{user_name}}/.ssh/id_rsa
when: (user_name != 'root') and (nonrootsshkey.stat.exists == False)
- name: delete /tmp/ssh/ dir
file: path=/tmp/ssh/ state=absent
delegate_to: 127.0.0.1 #这里也可以用local_action,效果一样。
- name: fetch copy for root #root用户拷贝公钥到本机
fetch: src=/root/.ssh/id_rsa.pub dest=/tmp/ssh/
when:
- user_name == 'root'
- name: fetch copy for non-root #非root拷贝公钥到本机
fetch: src=/home/{{user_name}}/.ssh/id_rsa.pub dest=/tmp/ssh/
when:
- user_name != 'root'
- name: append file authorized_keys.log #将各个公钥合并成一个文件
local_action: shell find /tmp/ssh/* -type f -exec sh -c 'cat {}>>/tmp/ssh/authorized_keys.log' \;
run_once: true
- name: copy authorized_keys #root用户将合成的公钥进行分发
copy: src=/tmp/ssh/authorized_keys.log dest=/root/.ssh/authorized_keys mode=0600
when:
- user_name == 'root'
- name: copy authorized_keys #非root用户将合成的公钥进行分发
become: yes
become_method: su
become_user: "{{user_name}}"
copy: src=/tmp/ssh/authorized_keys.log dest=/home/{{user_name}}/.ssh/authorized_keys mode=0600
when:
- user_name != 'root'