Top 30 Jenkins Pipeline (Jenkinsfile) DSL Syntax Configurations every DevOps Engineer should Know

Jenkins, a popular open-source automation server, empowers developers with its Pipeline as Code (PaC) approach. This allows you to define and automate your delivery pipelines using Jenkinsfile DSL (Domain Specific Language). Mastering key Jenkinsfile configurations is essential for building efficient and reliable pipelines.


Here at Latest Tech Insights, we present the top 20 Jenkinsfile DSL syntax configurations you should know:

{tocify} $title={Table of Contents}

1. Pipeline Declaration (pipeline): Defines the pipeline itself and optionally specifies its name.

Groovy
pipeline {
    agent any
    stages {
        // Pipeline stages defined here
    }
}


2. Stages (stages): Breaks down the pipeline into logical steps for better readability and maintainability.

Groovy
pipeline {
    agent any
    stages {
        stage('Build') {
            // Build related tasks
        }
        stage('Test') {
            // Testing related tasks
        }
    }
}


3. Steps (steps): Define the individual actions performed within each stage. These can involve shell commands, invoking plugins, or calling other stages.

Groovy
pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                sh 'mvn clean install' // Shell command for maven build
            }
        }
    }
}


4. Script (script): Encapsulates a block of groovy code to execute within a stage.

Groovy
pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                script {
                    // Groovy code block for complex logic
                }
            }
        }
    }
}


5. Parallel (parallel): Executes multiple stages concurrently to optimize pipeline execution time.

Groovy
pipeline {
    agent any
    stages {
        stage('Build & Test') {
            parallel {
                stage('Build') {
                    // Build tasks
                }
                stage('Test') {
                    // Test tasks
                }
            }
        }
    }
}


6. Post (post): Defines actions to be performed after the pipeline completes, regardless of success or failure.

Groovy
pipeline {
    agent any
    stages {
        // Pipeline stages
    }
    post {
        success {
            // Actions on successful completion
        }
        failure {
            // Actions on pipeline failure
        }
    }
}


7. Env (environment): Sets environment variables accessible within the pipeline.

Groovy
pipeline {
    agent any
    environment {
        NAME = 'my-application'
        VERSION = '1.0.0'
    }
    stages {
        // Use environment variables within stages
    }
}

8. Input (input): Prompts the user for input during pipeline execution.

Groovy
pipeline {
    agent any
    stages {
        stage('Approval') {
            input {
                message 'Proceed to deployment?'
                ok 'Yes'
                cancel 'No'
            }
        }
    }
}


9. When (when): Defines conditions under which a stage should be executed.

Groovy
pipeline {
    agent any
    stages {
        stage('Deploy to Production') {
            when {
                expression { branch == 'master' }
            }
        }
    }
}


10. Timeout (timeout): Sets a maximum time limit for a stage's execution.

Groovy
pipeline {
    agent any
    stages {
        stage('Test') {
            timeout(time: 30, unit: 'minutes') {
                // Test execution steps
            }
        }
    }
}

Also READ: Success Series to Clear Interview{alertSuccess}

11. Notify (notify): Configures notifications (email, chat) sent upon pipeline completion.

Groovy
pipeline {
    agent any
    stages {
        // Pipeline stages
    }
    notify {
        success {
            // Recipients for success notification
        }
    }
}


12. Pipeline DSL Functions: Jenkinsfile provides built-in functions for common tasks like file operations, triggering builds, and manipulating strings.

Groovy
pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                script {
                    def file = readFile('pom.xml') // Read file content
                }
            }
        }
    }
}


13. Choice (choice): Presents the user with a list of options during pipeline execution.

Groovy
pipeline {
    agent any
    stages {
        stage('Environment Selection') {
            steps {
                choice {
                    choices 'Production', 'Staging', 'Development'
                    description 'Select the deployment environment'
                }
            }
        }
    }
}


14. Discarding Unsuccessful Builds (discardUnsuccessfulBuilds): Automatically discards workspace artifacts from failed builds, saving storage space.

Groovy
pipeline {
    agent any
    discardUnsuccessfulBuilds true  // Enable discarding unsuccessful builds
    stages {
        // Pipeline stages
    }
}


15. Error Handling (catchError): Wraps pipeline steps within a block to gracefully handle exceptions and prevent pipeline failure.

Groovy
pipeline {
    agent any
    stages {
        stage('Test') {
            steps {
                catchError {
                    sh 'run_tests.sh' // Potential exception here
                }
            }
        }
    }
}


16. Credentials (credentialsId): References secret credentials stored in Jenkins for secure access to passwords or tokens within pipeline steps.

Groovy
pipeline {
    agent any
    stages {
        stage('Deploy') {
            steps {
                sh 'aws s3 deploy --access_key_id $AWS_ACCESS_KEY_ID' // Using credentials
            }
        }
    }
}


17. Pipeline Utility Steps (pipeline utility steps): Jenkins provides a rich set of utility steps for common tasks like injecting passwords, archiving artifacts, and deploying applications.

Groovy
pipeline {
    agent any
    stages {
        stage('Post-Build') {
            steps {
                archiveArtifacts artifacts: '*.war' // Archive war files
            }
        }
    }
}


18. Caching (cache): Caches specific directories or files between pipeline runs to improve performance by avoiding redundant downloads or calculations.

Groovy
pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                cache {
                    path 'node_modules' // Cache node dependencies
                    // Other caching options available
                }
                sh 'npm install'
            }
        }
    }
}


19. Properties (properties): Defines custom properties accessible throughout the pipeline for dynamic configuration.

Groovy
pipeline {
    agent any
    properties([
        string(name: 'BUILD_NUMBER', value: "${env.BUILD_NUMBER}"),
    ])
    stages {
        stage('Build') {
            steps {
                echo "Build Number: ${BUILD_NUMBER}" // Accessing property
            }
        }
    }
}


20. Pipeline as Library (library): Encapsulates reusable pipeline logic into sharable libraries, promoting modularity and code reuse.

Groovy
library 'shared-library' // Referencing a shared pipeline library

 Also READ: Career Advice{alertSuccess}

21. Always (always): Executes a block of code unconditionally after all stages have finished, regardless of success or failure. This is commonly used for cleanup tasks or final notifications.

Groovy
pipeline {
    agent any
    stages {
        // Pipeline stages
    }
    post {
        always {
            cleanWs() // Cleanup workspace after all stages
        }
    }
}


22. Success (success): Executes a block of code only if the entire pipeline execution completes successfully.

Groovy
pipeline {
    agent any
    stages {
        // Pipeline stages
    }
    post {
        success {
            emailaddress 'team@example.com' // Send notification on success
            body 'Pipeline executed successfully!'
        }
    }
}


23. Failure (failure): Executes a block of code only if the pipeline execution fails.

Groovy
pipeline {
    agent any
    stages {
        // Pipeline stages
    }
    post {
        failure {
            emailaddress 'ops@example.com' // Send notification on failure
            body 'Pipeline failed! Check logs for details.'
        }
    }
}


24. Unstable (unstable): Executes a block of code only if the pipeline execution finishes in an unstable state (e.g., some tests failed).

Groovy
pipeline {
    agent any
    stages {
        // Pipeline stages
    }
    post {
        unstable {
            echo 'Pipeline completed with some instability.'
        }
    }
}


25. Fixed (fixed): Executes a block of code only if the current pipeline execution represents a fix for a previously failed build.

Groovy
pipeline {
    agent any
    stages {
        // Pipeline stages
    }
    post {
        fixed {
            echo 'This build fixed a previous failure.'
        }
    }
}


26. Fingerprint (fingerprint): Captures artifacts (files or directories) after a successful build and stores them as fingerprints for comparison with future builds.

Groovy
pipeline {
    agent any
    stages {
        // Pipeline stages
    }
    post {
        success {
            fingerprint archivedArtifacts: '**/*.jar' // Fingerprint jar files
        }
    }
}


27. Publish HTML Reports (publishHTML): Publishes HTML test reports generated during the pipeline execution for easy visualization.

Groovy
pipeline {
    agent any
    stages {
        // Pipeline stages
    }
    post {
        always {
            publishHTML reports: 'test_reports/**/*.html' // Publish test reports
        }
    }
}


28. SlackNotifier (slack): Sends notifications to a Slack channel upon pipeline completion, with options to customize messages and attachments.

Groovy
pipeline {
    agent any
    stages {
        // Pipeline stages
    }
    post {
        always {
            slack channel: '#ci-notifications', message: 'Pipeline execution completed.'
        }
    }
}


29. Artifact Archiving (archiveArtifacts): Archives specific artifacts (files or directories) after pipeline execution for later retrieval or analysis.

Groovy
pipeline {
    agent any
    stages {
        // Pipeline stages
    }
    post {
        always {
            archiveArtifacts artifacts: 'build.log' // Archive build logs
        }
    }
}


30. BuildDiscarder (buildDiscarder): Configures a strategy for automatically discarding old builds based on criteria like age, number, or build status.

Groovy
pipeline {
    agent any
    stages {
        // Pipeline stages
    }
    buildDiscarder(logRetention: numToKeep: 5) // Keep only the last 5 builds
}

By mastering these post-processing steps, you can configure your Jenkins pipelines to perform essential actions after each run, ensuring a smooth and informative CI/CD experience.

Also READ: DevOps Best Practices{alertSuccess}

Post a Comment

Previous Post Next Post