一、概述
通过向主机组发送java --version ,获得返回状态,从而判断对应主机是否安装jdk,如果没有安装,则发送安装包,执行安装
二、操作
1、准备环节
mkdir /ansible
mv jdk-8u151-linux-x64.tar.gz /ansible/
2、配置主机host
[root@k8s01 ansible]# cat /ansible/hosts
[java]
192.168.10.132
192.168.10.133
[all:vars]
ansible_ssh_port=22
ansible_ssh_user=root
ansible_sss_pass=123456
测试:
ansible java -m ping -i hosts
3、yaml编写
[root@k8s01 ansible]# cat /ansible/install_jdk.yaml
---
- name: "检测并安装jdk"
hosts: java_module
tasks:
- name: "检测主机是否安装jdk"
shell: java -version
ignore_errors: True
register: check_jdk_result
- name: "创建jdk目录"
file:
path: /usr/java
state: directory
owner: root
group: root
mode: 0755
when: check_jdk_result.rc != 0
- name: "将jdk解压并拷贝到远程目录下"
unarchive:
src: jdk-8u151-linux-x64.tar.gz
dest: /usr/java
copy: yes
when: check_jdk_result.rc != 0
- name: "添加环境变量,提前手动打开看一下解压后的jdk文件名"
shell: /bin/echo {{ item }} >> /etc/bashrc
loop:
- export JAVA_HOME=/usr/java/jdk1.8.0_151
- export CLASSPATH=\$JAVA_HOME/lib/
- export PATH=\$PATH:\$JAVA_HOME/bin
when: check_jdk_result.rc != 0
- name: "加载配置文件"
shell: source /etc/bashrc
args:
executable: /bin/bash
- name: "测试jdk是否安装好"
shell: java -version
ansible-playbook install_jdk.yaml -i hosts
4、部分解释
环境变量添加到/etc/bashrc而不是/etc/profile
原因是开始用的/etc/profile,结果java命令死活找不到
突然想起如果用户不连接,默认不读取/etc/profile和用户家目录下的profile,但是读取/etc/bashrc和用户家目录下的bashrc
所以改成/etc/bashrc,就可以正常检测命令了