Advanced Jenkins

Pipeline Structure and Scripted vs Declarative

Declarative vs Scripted Pipeline

In Jenkins, you define CI/CD workflows in a Jenkinsfile using one of two pipeline syntaxes: declarative or scripted. Both leverage Apache Groovy, support Shared Libraries, and run on the same pipeline engine. However, they vary in structure, complexity, flexibility, and ease of onboarding.


Scripted Pipelines

Scripted Pipelines are written as full Groovy programs. They expose the entire Groovy language, providing unmatched control over flow, logic, and DSL extension.

node {
  stage('Build') {
    sh 'mvn clean package'
  }
  if (env.BRANCH_NAME == 'main') {
    stage('Deploy') {
      sh 'kubectl apply -f deploy.yaml'
    }
  }
}
  • Define stages, steps, and logic purely in Groovy.
  • Implement loops, conditionals, and custom functions.
  • Access any Groovy library or third-party plugin.

Note

Scripted Pipelines are ideal when you need fine-grained control or have advanced Groovy logic.


Declarative Pipelines

Declarative Pipelines use a structured, block-oriented syntax that enforces a consistent layout and validates your pipeline before execution.

pipeline {
  agent any
  stages {
    stage('Build') {
      steps {
        sh 'mvn clean package'
      }
    }
    stage('Deploy') {
      when {
        branch 'main'
      }
      steps {
        sh 'kubectl apply -f deploy.yaml'
      }
    }
  }
}
  • Follows an opinionated structure (pipeline {}, agent {}, stages {}).
  • Provides built-in validation, error checking, and post actions.
  • Simplifies onboarding and reduces boilerplate.

Warning

Complex dynamic stages or intricate conditional logic may require embedded scripted blocks.


Side-by-Side Comparison

FeatureScripted PipelineDeclarative Pipeline
SyntaxFull GroovyBlock-based Groovy
ValidationRuntime onlyPre-execution validation
FlexibilityMaximumOpinionated, moderate
Learning CurveSteeper (Groovy proficiency)Gentler (pipeline structure)
Ideal Use CaseCustom DSLs, complex logicStandard workflows, team conventions

How to Choose

  • Scripted Pipelines

    • When your team is proficient in Groovy.
    • If you need dynamic stage generation or intricate logic.
    • For creating custom pipeline DSLs.
  • Declarative Pipelines

    • When readability and consistency matter most.
    • For fast onboarding of new team members.
    • When you prefer built-in validation and standardized steps.

Watch Video

Watch video content

Previous
Invalidate Cache