How to Use Tools in Jenkins Pipeline: Syntax and Examples
In Jenkins Pipeline, you use the
tools block to specify tools like JDK or Maven that your build needs. This block installs and sets up the tool automatically, making it available in your pipeline steps.Syntax
The tools block in a Jenkins Pipeline declares the tools your build requires. You specify the tool type and the tool name as configured in Jenkins global settings. Jenkins then sets environment variables pointing to the tool's location.
- tools: The block where you list required tools.
- toolType: The kind of tool, e.g.,
jdk,maven. - toolName: The exact name of the tool configured in Jenkins.
groovy
pipeline {
agent any
tools {
jdk 'jdk11'
maven 'maven3'
}
stages {
stage('Build') {
steps {
sh 'java -version'
sh 'mvn --version'
}
}
}
}Example
This example shows a Jenkins Pipeline that uses the tools block to set JDK 11 and Maven 3. It runs shell commands to print their versions, proving the tools are available.
groovy
pipeline {
agent any
tools {
jdk 'jdk11'
maven 'maven3'
}
stages {
stage('Check Tools') {
steps {
sh 'java -version'
sh 'mvn --version'
}
}
}
}Output
openjdk version "11.0.16" 2022-07-19
OpenJDK Runtime Environment (build 11.0.16+8)
OpenJDK 64-Bit Server VM (build 11.0.16+8, mixed mode)
Apache Maven 3.8.6 (b89d5959f1e3a0a1a7e1a1f3f9e7a1a1a1a1a1a1)
Maven home: /usr/share/maven
Java version: 11.0.16, vendor: Oracle Corporation
Common Pitfalls
Common mistakes when using tools in Jenkins Pipeline include:
- Using a tool name that is not configured in Jenkins global tool configuration.
- Forgetting to use the
toolsblock inside thepipelineblock. - Assuming tools are available without declaring them, which can cause build failures.
Always verify tool names in Jenkins settings and declare them explicitly.
groovy
pipeline {
agent any
stages {
stage('Build') {
steps {
// Wrong: no tools block, java command may fail
sh 'java -version'
}
}
}
}
// Correct way:
pipeline {
agent any
tools {
jdk 'jdk11'
}
stages {
stage('Build') {
steps {
sh 'java -version'
}
}
}
}Quick Reference
Summary tips for using tools in Jenkins Pipeline:
- Define tools in the
toolsblock insidepipeline. - Use exact tool names from Jenkins global configuration.
- Tools set environment variables like
JAVA_HOMEautomatically. - Use shell steps to run commands with the tools.
Key Takeaways
Always declare required tools in the
tools block of your Jenkins Pipeline.Use tool names exactly as configured in Jenkins global tool settings.
The
tools block sets environment variables for easy tool usage in steps.Omitting the
tools block can cause build failures due to missing tools.Verify tool installation and names before running your pipeline.