版权声明:有不正确的地方,还望各位指正指导,Thanks! https://blog.csdn.net/a544258023/article/details/85128184
Ansible是用来处理大批量重复性操作的工具,只需要在一台机器上就可以远程控制所有机器,但前提是必须保证每台机器之间SSH可以相互免密登录。关于Ansible的安装和环境准备请参考Ansible环境的准备。
注: 有关Ansible的所有操作只需在第一台机器上修改和执行,其它机器只需知道IP地址即可。
免密安装机器
172.18.18.120
172.18.18.121
172.18.18.122
配置所有免密机器用户名及密码
编辑/etc/ansible/hosts 文件增加配置如下:
[ssh]
172.18.18.120 ansible_ssh_user=root ansible_ssh_pass=123456
172.18.18.121 ansible_ssh_user=root ansible_ssh_pass=123456
172.18.18.122 ansible_ssh_user=root ansible_ssh_pass=123456
编写yml执行文件
编辑/opt/ansible/sshKey.yml文件如下:
- hosts: ssh gather_facts: no 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