To specify a specific Java version in a Jenkins pipeline, you can use the tool
directive to define the Java installation that you want to use, and then you can use the withEnv
directive to set the JAVA_HOME
environment variable to the path of the Java installation.
Here is an example of how you can specify a specific Java version in a Jenkins pipeline:
pipeline { agent { label 'my-agent' } tools { jdk 'jdk8' } stages { stage('Build') { steps { withEnv(['JAVA_HOME=/path/to/jdk8']) { sh 'java -version' } } } } }
In this example, the tool
directive is used to define the jdk8
installation as the Java installation that will be used in the pipeline. The withEnv
directive is then used to set the JAVA_HOME
environment variable to the path of the jdk8
installation. The java -version
command is then run to verify that the correct Java version is being used.
Keep in mind that you will need to install the desired Java version on the Jenkins agent(s) where the pipeline will be run. You can use the Jenkins Global Tool Configuration
page to install and manage the Java installations that are available to your Jenkins instance.
You can also use the java
command to specify the path to the Java executable that you want to use, as shown in the following example:
pipeline { agent { label 'my-agent' } stages { stage('Build') { steps { sh '/path/to/jdk8/bin/java -version' } } } }
In this example, the java
command is used to specify the path to the java
executable in the jdk8
installation. The java -version
command is then run to verify that the correct Java version is being used.
Keep in mind that the path to the Java executable may vary depending on your operating system and the Java installation that you are using. You will need to specify the correct path to the java
executable in your pipeline.