🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
### 目录结构 ``` [root@ansible-20 ~]# tree /etc/ansible/roles/java/ /etc/ansible/roles/java/ ├── files │   └── jdk-8u151-linux-x64.tar.gz ├── tasks │   └── main.yml └── templates └── java_home.sh.j2 ``` ### host文件 [root@ansible-20 ~]# cat /etc/ansible/hosts ``` [java] 192.168.47.74 [java:vars] JAVA_DOWNLOAD_DIR='/data/soft/java/' JAVA_HOME='/opt/jdk' JAVA_TAR='jdk-8u151-linux-x64.tar.gz' JAVA_VERSION='jdk1.8.0_151' ``` ### 总执行文件 [root@ansible-20 ~]# cat /etc/ansible/java_install.yml ``` - hosts: java roles: - java ``` ### 执行文件主体 [root@ansible-20 ~]# cat /etc/ansible/roles/java/tasks/main.yml ``` ## 安装jdk环境 ### 创建存放java的目录 - name: create_data_dir file: name={{ item }} state=directory with_items: - "{{ JAVA_DOWNLOAD_DIR }}" ### 拷贝java压缩包到指定目录 - name: copy java.tar copy: src={{ JAVA_TAR }} dest={{ JAVA_DOWNLOAD_DIR }} ### 解压java压缩包 - name: unarchive java_tar unarchive: src: "{{ JAVA_DOWNLOAD_DIR }}/{{ JAVA_TAR }}" dest: "/opt" owner: root group: root mode: 0755 copy: no register: extracted_java ### 创建软链接 - name: link java file: src: "/opt/{{ JAVA_VERSION }}" dest: "{{ JAVA_HOME }}" state: link ### 写入环境变量 - name: Set JAVA_HOME template: src: java_home.sh.j2 dest: "{{ JAVA_HOME }}/java_home.sh" mode: 0755 register: java_profile ### 执行变量脚本.如果脚本内容没有改变就不执行 - name: sh JAVA_HOME shell: "/bin/bash {{ JAVA_HOME }}/java_home.sh" when: java_profile.changed ``` ### 写入变量脚本 [root@ansible-20 ~]# cat /etc/ansible/roles/java/templates/java_home.sh.j2 ``` #!/bin/bash echo 'export JAVA_HOME={{ JAVA_HOME }}' >> /etc/profile echo 'export PATH=$JAVA_HOME/bin:$JAVA_HOME/jre/bin:$PATH' >> /etc/profile echo 'export CLASSPATH=.$CLASSPATH:$JAVA_HOME/lib:$JAVA_HOME/jre/lib:$JAVA_HOME/lib/tools.jar' >> /etc/profile ```