Scripted Pipeline in Jenkins: What It Is and How It Works
scripted pipeline in Jenkins is a way to define your build process using Groovy code inside a Jenkinsfile. It offers full programming flexibility to control the pipeline flow with loops, conditions, and custom logic, unlike the simpler declarative pipeline syntax.How It Works
Think of a scripted pipeline as writing a small program that tells Jenkins exactly what steps to run and when. It uses Groovy, a programming language similar to Java, to give you full control over the pipeline's behavior.
Imagine you are giving step-by-step instructions to a friend on how to bake a cake, but you also want to add your own rules like "if the oven is busy, wait" or "repeat this step three times." Scripted pipelines let you do that with code, so Jenkins can handle complex workflows.
This flexibility means you can use loops, conditions, and variables to customize your build and deployment process exactly how you want it.
Example
This example shows a simple scripted pipeline that prints messages and runs a shell command.
node {
stage('Example') {
echo 'Starting the scripted pipeline'
def count = 3
for (int i = 1; i <= count; i++) {
echo "Iteration ${i}"
}
sh 'echo Hello from shell command'
}
}When to Use
Use scripted pipelines when you need full control over your build process and want to write complex logic that declarative pipelines can't easily handle. They are great for advanced workflows that require loops, conditional steps, or dynamic behavior.
For example, if your build needs to run different tests based on certain conditions or you want to retry steps multiple times with custom rules, scripted pipelines let you do that.
However, if your pipeline is simple and straightforward, declarative pipelines are easier to read and maintain.
Key Points
- Scripted pipelines use Groovy code for full programming flexibility.
- They allow loops, conditions, and complex logic in Jenkins pipelines.
- Defined inside a
Jenkinsfileusing thenodeblock. - Best for advanced or dynamic build workflows.
- More complex to write and read compared to declarative pipelines.