2020-11-03

望閒人發表於2020-11-03

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' \;
      
    - 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'