Sobes.tech
Middle

What type of pipelines do you use in Jenkins: written in Groovy or declarative?

sobes.tech AI

Answer from AI

I use both types, but I prefer declarative ones for most projects.

Declarative syntax is more readable, understandable, and easier to maintain, especially in large and complex pipelines. It is well-suited for describing standard build, test, and deployment stages.

Example of a declarative pipeline:

// Declarative pipeline
pipeline {
    agent any

    stages {
        stage('Build') {
            steps {
                sh 'mvn clean package'
            }
        }
        stage('Test') {
            steps {
                sh 'mvn test'
            }
        }
        stage('Deploy') {
            steps {
                echo 'Deploying application...'
            }
        }
    }
}

Scripted pipelines (written in Groovy) are used for more complex scenarios requiring dynamic behavior, branching, or non-standard logic that is difficult to implement declaratively.

Example of a scripted pipeline:

// Scripted pipeline
node {
    stage('Checkout') {
        // Get source code
    }

    stage('Build') {
        // Build project
    }

    if (env.BRANCH_NAME == 'master') {
        stage('Deploy Production') {
            // Deploy to production
        }
    } else {
        stage('Deploy Staging') {
            // Deploy to staging
        }
    }
}

Combining approaches provides flexibility and readability, where the declarative pipeline describes main stages, and scripted blocks add specific logic.

Main differences:

Feature Declarative Scripted (Groovy)
Syntax Structured, predictable More flexible, based on Groovy
Readability High Depends on code complexity
Structure Clearly defined sections (stages, steps, agent, options, etc.) Arbitrary Groovy code
Capabilities Suitable for standard scenarios Flexibility for complex scenarios
Support Easier More difficult with large codebases
Errors More informative at parse stage May occur during execution

In the end, I prefer declarative pipelines as the standard, resorting to scripted ones only when implementing specific business logic or complex integrations. This ensures a balance between ease of maintenance and flexibility.