ansible ssh免登录配置,主机间免登录

1. 配置好ansible的host文件,并配置通用账号密码,这里使用root

ansible ssh免登录配置,主机间免登录_第1张图片 

ansible_ssh_user=root

ansible_ssh_pass=123456

2. 使用ssh-key生成公钥和私钥

只在一台机器上生成秘钥:

ssh-keygen -t rsa -b 2048 -P '' -f  /home/log4x/.ssh/id_rsa

在所有主机上生成秘钥:

ansible all -m shell -a " ssh-keygen -t rsa -b 2048 -P '' -f  /root/.ssh/id_rsa"


使用playbook,编写  yml执行文件

编辑/opt/ansible/sshKey.yml文件如下:

- hosts: all
  #gather_facts: no

  # 包含在本机执行的run_once的任务 > ansible主控机必须放分组第一个!
  tasks:
    - name: enforce env   
      shell: source /etc/profile
      run_once: true
    - name: close ssh check  #关闭初次访问提示询问   
      shell: sed -i "s/^.*StrictHostKeyChecking.*$/   StrictHostKeyChecking no/g" /etc/ssh/ssh_config
    - name: delete /root/.ssh/
      file: path=/root/.ssh/ state=absent
    - name: generating public/private rsa key pair  #生成公钥和私钥
      shell: ssh-keygen -t rsa -b 2048 -N '' -f /root/.ssh/id_rsa
    - name: delete /tmp/ssh/ dir
      file: path=/tmp/ssh/ state=absent
      run_once: true
    - name: fetch copy  #从各宿主机将公钥拷贝到本机
      fetch: src=/root/.ssh/id_rsa.pub dest=/tmp/ssh/
    - name: append file authorized_keys.log  #将各个公钥合并成一个文件
      shell: find /tmp/ssh/* -type f -exec sh -c 'cat {}>>/tmp/ssh/authorized_keys.log' \;
      run_once: true
    - name: copy authorized_keys  #将合成的公钥进行分发
      copy: src=/tmp/ssh/authorized_keys.log dest=/root/.ssh/authorized_keys mode=0600
      tags:
       - install ssh

执行免密安装

ansible-playbook  /opt/ansible/sshKey.yml

你可能感兴趣的:(ansible,ssh,运维)