Declarative vs Scripted Pipeline in Jenkins: Key Differences and Usage
Declarative pipeline uses a simple, structured syntax focused on ease and readability, while a Scripted pipeline offers full Groovy scripting power for complex logic. Declarative pipelines are easier for beginners and standard workflows, whereas scripted pipelines suit advanced customizations.Quick Comparison
This table summarizes the main differences between Declarative and Scripted pipelines in Jenkins.
| Aspect | Declarative Pipeline | Scripted Pipeline |
|---|---|---|
| Syntax Style | Simple, predefined blocks | Full Groovy scripting |
| Ease of Use | Beginner-friendly | Requires Groovy knowledge |
| Flexibility | Limited to pipeline features | Highly flexible and customizable |
| Error Handling | Built-in options | Manual coding needed |
| Use Case | Standard CI/CD workflows | Complex logic and dynamic pipelines |
| Readability | Clear and structured | Can be complex and verbose |
Key Differences
Declarative pipelines use a fixed syntax with predefined sections like pipeline, stages, and steps. This structure enforces best practices and makes the pipeline easy to read and maintain. It also includes built-in features like post blocks for handling success or failure.
In contrast, Scripted pipelines are written as Groovy scripts, giving full control over the flow and logic. This allows complex conditions, loops, and dynamic behavior but requires more Groovy knowledge and careful coding to avoid errors.
Declarative pipelines are ideal for most users because they simplify pipeline creation and reduce errors. Scripted pipelines are better when you need advanced scripting capabilities that Declarative syntax cannot provide.
Code Comparison
Here is an example of a simple Jenkins pipeline that checks out code, builds, and tests using Declarative syntax.
pipeline {
agent any
stages {
stage('Checkout') {
steps {
git 'https://github.com/example/repo.git'
}
}
stage('Build') {
steps {
echo 'Building...'
sh 'make build'
}
}
stage('Test') {
steps {
echo 'Testing...'
sh 'make test'
}
}
}
post {
success {
echo 'Pipeline succeeded!'
}
failure {
echo 'Pipeline failed!'
}
}
}Scripted Pipeline Equivalent
The same pipeline implemented with Scripted syntax uses Groovy code blocks and explicit flow control.
node {
try {
stage('Checkout') {
git 'https://github.com/example/repo.git'
}
stage('Build') {
echo 'Building...'
sh 'make build'
}
stage('Test') {
echo 'Testing...'
sh 'make test'
}
echo 'Pipeline succeeded!'
} catch (err) {
echo 'Pipeline failed!'
throw err
}
}When to Use Which
Choose Declarative pipeline when you want a clear, easy-to-write pipeline with standard CI/CD steps and built-in error handling. It is best for most projects and teams new to Jenkins pipelines.
Choose Scripted pipeline when you need complex logic, dynamic stages, or custom Groovy scripting that Declarative syntax cannot handle. It suits advanced users comfortable with Groovy programming.