使用ansible安装java

本文主要讲述如何使用Ansible在Redhat Linux系列上安装java 17。

关于Ansible的基本概念可以参考运维自动化之Ansible

1. 安装Ansible

安装Ansible参考安装ansible | 鹏叔的技术博客

2. 编写Ansible Playbook

如果远程主机非root用户,需要准备一个ansible.cfg文件用于覆盖ansible默认配置,
也可以直接修改/etc/ansible/ansible.cfg

1
2
3
4
5
6
7
8
9
10
11
# vi ansible.cfg
[defaults]
# replace the user with actual user name
remote_user = user_name_on_managed_host

[privilege_escalation]
become = True
become_method = sudo
become_user = root
become_ask_pass = False

vi install_java.yaml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
---
- name: Install Java
hosts: all
become: yes
vars:
- jdk_package_name: java-17-openjdk-devel
jdk_version: 17.0.9.0.9
env_file: /etc/profile

tasks:
- name: Install OpenJDK
yum: name={{ jdk_package_name }}-{{ jdk_version }} state=present

- name: Set Java environment variables
lineinfile: dest={{ env_file }} insertafter={{ item.position }} line={{ item.value }} state=present
with_items:
- {position: EOF,value: "export JAVA_HOME=/usr/lib/jvm/{{ jdk_package_name }}-{{ jdk_version }}.el8.x86_64"}
- {position: EOF,value: "export PATH=$JAVA_HOME/bin/:$PATH"}
- {position: EOF,value: "export CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar"}
notify: Reload profile

handlers:
- name: Reload profile
shell: source {{ env_file }}

3. 执行Ansible Playbook

1
ansible-playbook install_java.yaml

4. 参考文档

使用ansible 安装java

Ansible 学习总结(6)—— Ansible 19个常用模块使用示例

Linux System Roles

作者

鹏叔

发布于

2024-01-19

更新于

2024-07-10

许可协议

评论