ansible是一个配置管理系统,可以用来自动化处理集群间批量重复性任务,常用来安装部署hadoop、spark、es等大数据工具,但是在运用它之前需要保证各个机器之间相互可以免密登录,也就是可以使用ssh不用密码可以登录到任何一台机器上。
免密安装机器
172.18.18.120
172.18.18.121
172.18.18.122
-
在线安装ansible
yum -y install ansible
-
配置所有免密机器用户名及密码
cat /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
-
编写执行命令
cat /opt/ansible/sshKey.yml
- hosts: ssh
gather_facts: no
tasks:- name: set env #关闭关闭公钥认证
lineinfile: dest=/etc/profile insertafter="{{item.position}}" line="{{item.value}}" state=present
with_items:
- {position: EOF, value: "\n"}
- {position: EOF, value: "export ANSIBLE_HOST_KEY_CHECKING=False"}
run_once: true
- name: enforce env #刷新环境变量
shell: source /etc/profile
run_once: true
- 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
- name: generating public/private rsa key pair #使用ssh-key产生公钥和私钥
shell: ssh-keygen -t rsa -b 2048 -N '' -f /root/.ssh/id_rsa
- name: delete /tmp/ssh/ #删除临时公钥目录
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
-
免密执行安装
ansible-playbook /opt/ansible/sshKey.yml