If you're diving into Jenkins and wondering "whatβs the deal with Declarative vs Scripted Pipelines?", you're not alone.
When I first got into CI/CD, I kept seeing two totally different ways to write Jenkins pipelinesβand I wasnβt sure which one to use or why.
So letβs break it down in simple terms, with real examples, key differences, and when you should use one over the other.
π€ What Is a Jenkins Pipeline?
A Jenkins Pipeline is a way to define your entire CI/CD process as code using a file called Jenkinsfile.
It automates steps like:
- Cloning your code
- Running tests
- Building artifacts (like Docker images or JARs)
- Deploying to staging or production
There are two types of pipeline syntax in Jenkins:
- Declarative Pipeline (newer, structured)
- Scripted Pipeline (older, Groovy-style code)
π§Ύ Declarative Pipeline
The Declarative syntax is the recommended approach. It's clean, structured, and built for simplicity.
β Example:
pipeline {
agent any
stages {
stage('Build') {
steps {
echo 'Building the project...'
}
}
stage('Test') {
steps {
echo 'Running tests...'
}
}
stage('Deploy') {
steps {
echo 'Deploying to production...'
}
}
}
}
π’ Pros:
Easier to read and maintain
Built-in error handling (post section)
Enforces structure (helps new users)
π΄ Cons:
Less flexible than scripted
Not everything Groovy supports is allowed here
π§ Scripted Pipeline
The Scripted syntax is more powerful but also more complex. It's written entirely in Groovy, so it's like writing code, not config.
βοΈ Example:
node {
stage('Build') {
echo 'Building the project...'
}
stage('Test') {
echo 'Running tests...'
}
stage('Deploy') {
echo 'Deploying to production...'
}
}
π’ Pros:
Full control and flexibility (it's just Groovy!)
Good for complex logic or loops
π΄ Cons:
Harder to read and maintain
Easy to mess up with no structure or guidance
Not beginner-friendly
π‘ So... Which One Should You Use?
β
Use Declarative if you're:
New to Jenkins
Writing simple to medium-complexity pipelines
Wanting cleaner code with better readability
π§ Use Scripted if you're:
Comfortable with Groovy
Need dynamic behavior, custom conditions, or advanced loops
π¦ Bonus Tip: Combine Both!
You can use Scripted blocks inside a Declarative pipeline using script { ... }. Example:
pipeline {
agent any
stages {
stage('Mixed') {
steps {
script {
def items = ['A', 'B', 'C']
items.each { item ->
echo "Processing ${item}"
}
}
}
}
}
}
This gives you the structure of Declarative with the power of Scripted β best of both worlds!
π Final Thoughts
Whether you choose Declarative or Scripted, Jenkins Pipelines make CI/CD much more powerful and scalable. Start with Declarative, then reach for Scripted only if you truly need it.
π¬ Got questions? Drop a comment below and let's talk DevOps!
If this helped you, consider following me here on Dev.to and subscribing to my YouTube channel https://www.youtube.com/@DataEnthusiastEra for more DevOps tutorials! π
Top comments (0)