采用Ansible配置ssh和jdk
Ansible简介
Ansible 是基于 Python 语言开发的,主流的自动化运维管理工具,其余的工具还有Puppet和Saltstack。
Ansible只需要在一台普通的服务器上运行即可,不需要在客户端服务器上安装客户端。因为 Ansible 是基于 SSH 远程管理,而 Linux 服务器基本都开启了 SSH 服务,所以 Ansible 不需要为配置工作添加额外的支持。
安装Ansible
[root@master ~]# yum install epel-release
[root@master ~]# yum install ansible
配置ssh和jdk
1. 创建Ansible配置文件
[root@master ansible]# tree /etc/ansible/
/etc/ansible/
├── ansible.cfg
├── hosts
├── jdk.yml
├── roles
│ ├── files
│ │ └── jdk.tar.gz
│ ├── templates
│ │ └── authorized_keys.j2
│ └── vars
│ └── main.yml
└── ssh.yml
在/etc/ansible/roles/目录下,创建 files、templates、vars目录
ansible.cfg
将ansible.cfg文件中 host_key_checking = False 的注释去掉
hosts
将以下内容添加到hosts文件
[root]
192.168.1.8 ansible_ssh_user=root ansible_ssh_pass='<密码>'
192.168.1.9 ansible_ssh_user=root ansible_ssh_pass='<密码>'
[zhangyan]
slave1 ansible_ssh_user=zhangyan ansible_ssh_pass='<密码>'
slave2 ansible_ssh_user=zhangyan ansible_ssh_pass='<密码>'
注:slave1和slave2分别为192.168.1.8和192.168.1.9的主机名
vars/main.yml
配置变量AnsibleDir、BigdataDir
server1_hostname: 192.168.1.7
server2_hostname: 192.168.1.8
server3_hostname: 192.168.1.9
AnsibleDir: /etc/ansible
BigdataDir: /opt/bigdata
hadoopconfigfile: /etc/hadoop
jdk.yml
- hosts: root
remote_user: root
roles:
- roles
tasks:
- name: mkdir jdk directory
file: path={{BigdataDir}} state=directory mode=0755
- name: copy and unzip jdk
unarchive: src={{AnsibleDir}}/roles/files/jdk.tar.gz dest={{BigdataDir}}
- name: set env
lineinfile: dest=/etc/profile line="{{item.value}}" state=present
with_items:
- {value: "export JAVA_HOME={{BigdataDir}}/jdk"}
- {value: "export PATH=$JAVA_HOME/bin:$PATH"}
- name: chmod bin
file: dest={{BigdataDir}}/jdk/bin mode=0755 recurse=yes
- name: enforce env
shell: source /etc/profile
**注:确保jdk.tar.gz解压后的目录名为jdk,否则“chmod bin”中的目录名要改为和解压后的目录名一致 **
ssh.yml
- hosts: root
gather_facts: no
roles:
- roles
tasks:
- name: close ssh yes/no check
lineinfile: path=/etc/ssh/ssh_config regexp='(.*)StrictHostKeyChecking(.*)' line="StrictHostKeyChecking no"
- name: delete /root/.ssh/
file: path=/root/.ssh/ state=absent
- name: create .ssh directory
file: dest=/root/.ssh mode=0600 state=directory
- name: generating local public/private rsa key pair
local_action: shell ssh-keygen -t rsa -b 2048 -N '' -f /root/.ssh/id_rsa
run_once: true
- name: view id_rsa.pub
local_action: shell cat /root/.ssh/id_rsa.pub
register: sshinfo
- set_fact: sshpub={{sshinfo.stdout}}
- name: add sshkey
local_action: shell echo {{sshpub}} > {{AnsibleDir}}/roles/templates/authorized_keys.j2
run_once: true
- name: copy authorized_keys.j2 to all hosts
template: src={{AnsibleDir}}/roles/templates/authorized_keys.j2 dest=/root/.ssh/authorized_keys mode=0600
tags:
- copy sshkey
运行Ansible命令
配置集群ssh
[root@master ansible]# rm -fr /root/.ssh
[root@master ansible]# ansible-playbook /etc/ansible/ssh.yml
配置集群jdk
ansible-playbook /etc/ansible/jdk.yml