首页 > 解决方案 > Jenkins Pipeline env.JAVA_HOME differs from sh printenv

问题描述

Jenkins 2.2024.2
Kubernetes Plugin 1.22.0

The env.JAVA_HOME variable is getting set to a different value than what sh 'printenv' shows. I had thought env was a reflection of the environment. I also can't find where env.JAVA_HOME is set. It doesn't reflect the value in the Global JDK configurations. I also grepped the Jenkins Master root directory for openjdk and only found the correct value.

bash-4.4# grep openjdk *
config.xml:      <home>/usr/local/openjdk-8/jre</home>

Here's a pipeline demonstrating the behavior.

pipeline {
    agent {
        kubernetes { label 'java8-mvn3' }
    }

    stages {
        stage('test') {
            steps {
                container ('java8-mvn3') {
                    echo env.JAVA_HOME
                    echo "++++++++++++++++++++++++++"
                    sh 'printenv | grep JAVA_HOME'
                }
            }
        }
    }
}

** OUTPUT **

[Pipeline] echo
/usr/lib/jvm/java-1.8-openjdk
[Pipeline] echo
++++++++++++++++++++++++++
[Pipeline] sh
+ printenv
+ grep JAVA_HOME
JAVA_HOME=/usr/local/openjdk-8

标签: javajenkinsjenkins-pipeline

解决方案


根据手册页: http: //man7.org/linux/man-pages/man1/printenv.1.html

   NOTE: your shell may have its own version of printenv, which usually
   supersedes the version described here.  Please refer to your shell's
   documentation for details about the options it supports.

所以你很多人需要使用特定的外壳,比如sh '''#!/bin/bash -c ...

或者作为另一种选择导出全局/阶段定义环境级别所需的选项


推荐阅读