How to Use Script Block in Declarative Jenkins Pipeline
In Jenkins declarative pipelines, use the
script block to run Groovy code that is not supported directly by declarative syntax. Place the script block inside a steps section to execute complex logic or custom scripts.Syntax
The script block allows you to run Groovy code inside a declarative pipeline. It must be placed inside a steps block. This lets you use imperative Groovy code where declarative syntax is limited.
- pipeline: The root block for declarative pipelines.
- stage: Defines a stage in the pipeline.
- steps: Contains the commands or scripts to run.
- script: Runs Groovy code inside declarative syntax.
groovy
pipeline {
agent any
stages {
stage('Example') {
steps {
script {
// Groovy code here
echo "Hello from script block"
}
}
}
}
}Example
This example shows how to use the script block to run Groovy code that prints a message and uses a loop, which is not possible directly in declarative syntax.
groovy
pipeline {
agent any
stages {
stage('Script Block Demo') {
steps {
script {
echo 'Starting loop in script block'
for (int i = 1; i <= 3; i++) {
echo "Loop iteration: ${i}"
}
echo 'Loop finished'
}
}
}
}
}Output
[Pipeline] echo
Starting loop in script block
[Pipeline] echo
Loop iteration: 1
[Pipeline] echo
Loop iteration: 2
[Pipeline] echo
Loop iteration: 3
[Pipeline] echo
Loop finished
Common Pitfalls
Common mistakes when using the script block include:
- Placing
scriptoutsidestepscauses syntax errors. - Using declarative-only steps inside
scriptblock without proper Groovy syntax. - Not handling exceptions inside
scriptblock can cause pipeline failures.
Always remember script is for Groovy code, so use Groovy syntax inside it.
groovy
pipeline {
agent any
stages {
stage('Wrong Usage') {
// This will cause error because script is outside steps
script {
echo 'This is wrong placement'
}
}
}
}
// Correct usage:
pipeline {
agent any
stages {
stage('Right Usage') {
steps {
script {
echo 'This is correct placement'
}
}
}
}
}Quick Reference
Use the script block inside steps to run Groovy code in declarative pipelines. It enables complex logic like loops, conditionals, and variable manipulation not possible in pure declarative syntax.
- Always place
scriptinsidesteps. - Use Groovy syntax inside
script. - Keep declarative and scripted parts clear for readability.
Key Takeaways
Use the
script block inside steps to run Groovy code in declarative pipelines.Place
script only inside steps to avoid syntax errors.The
script block allows loops, conditionals, and complex logic not supported by declarative syntax.Write Groovy code inside
script using proper Groovy syntax.Keep your pipeline readable by separating declarative and scripted parts clearly.