Declarative vs Scripted Pipeline
Jenkins supports two pipeline syntaxes: Declarative and Scripted. Understanding the difference is essential for correct design decisions and interviews.
High-Level Comparisonβ
| Aspect | Declarative Pipeline | Scripted Pipeline |
|---|---|---|
| Syntax | Structured | Groovy-based |
| Readability | High | MediumβLow |
| Flexibility | Limited | Very High |
| Safety | Built-in safeguards | No safeguards |
| Recommended | β Yes | β οΈ Only when needed |
Declarative Pipelineβ
What It Isβ
Declarative Pipeline provides a structured, opinionated syntax that enforces best practices.
Characteristicsβ
- Uses predefined blocks
- Easier to read and maintain
- Built-in validation
- Safer for teams
Exampleβ
pipeline {
agent any
stages {
stage('Test') {
steps {
sh 'mvn test'
}
}
}
}
Scripted Pipelineβ
What It Isβ
Scripted Pipeline is written using Groovy and provides full control over pipeline logic.
Characteristicsβ
- Very flexible
- Powerful conditional logic
- Harder to read
- Easier to misuse
Exampleβ
node {
stage('Test') {
sh 'mvn test'
}
}
When to Use Declarative Pipelineβ
Use Declarative when:
- You are building standard CI/CD pipelines
- Team size is medium to large
- Readability and maintainability matter
- You want safer defaults
This covers 90% of real-world use cases.
When Scripted Pipeline Is Justifiedβ
Scripted pipeline is justified when:
- Complex dynamic logic is required
- Advanced loops or conditions are needed
- Declarative syntax becomes limiting
Even then, prefer shared libraries.
Mixing Declarative and Scriptedβ
Declarative pipelines can include scripted blocks:
script {
if (env.BRANCH_NAME == 'main') {
sh 'deploy.sh'
}
}
This provides flexibility without losing structure.
Common Mistakesβ
- Starting directly with scripted pipeline
- Writing unreadable Groovy logic
- Ignoring shared libraries
- Overengineering pipelines
Interview Trapsβ
-
Which pipeline type is recommended?
β Declarative -
Can scripted logic be used in declarative?
β Yes, usingscript {} -
Is scripted pipeline deprecated?
β No, but discouraged for most use cases