CI/CD

How would you implement an option of a starting a build from a certain stage and not from the beginning?

Difficulty: unrated

Source: bregman-arie/devops-exercises by Arie Bregman

Answer

To implement an option of starting a build from a certain stage and not from the beginning in a Jenkins pipeline, we can use the when directive along with a custom parameter to determine the starting stage. Here are the steps to implement this:

  1. Add a custom parameter to the pipeline. This parameter can be a simple string or a more complex data type like a map.

    parameters {
        string(name: 'START_STAGE', defaultValue: '', description: 'The name of the stage to start the build from')
    }
    
  2. Use the when directive to conditionally execute stages based on the value of the START_STAGE parameter.

    stage('Build') {
        when {
            expression {
                params.START_STAGE == '' || currentStage.name == params.START_STAGE
            }
        }
        // Build steps go here
    }
    
    stage('Test') {
        when {
            expression {
                params.START_STAGE == '' || currentStage.name == params.START_STAGE || previousStage.result == 'SUCCESS'
            }
        }
        // Test steps go here
    }
    
    stage('Deploy') {
        when {
            expression {
                params.START_STAGE == '' || currentStage.name == params.START_STAGE || previousStage.result == 'SUCCESS'
            }
        }
        // Deploy steps go here
    }
    

In this example, we use the when directive to execute each stage only if the START_STAGE parameter is empty or matches the current stage's name. Additionally, for the Test and Deploy stages, we also check if the previous stage executed successfully before running.

  1. Trigger the pipeline and pass the START_STAGE parameter as needed.

    pipeline {
        agent any
        parameters {
            string(name: 'START_STAGE', defaultValue: '', description: 'The name of the stage to start the build from')
        }
        stages {
            stage('Build') {
                // Build steps go here
            }
            stage('Test') {
                // Test steps go here
            }
            stage('Deploy') {
                // Deploy steps go here
            }
        }
    }
    

When triggering the pipeline, you can pass the START_STAGE parameter to start the build from a specific stage.

For example, if you want to start the build from the Test stage, you can trigger the pipeline with the START_STAGE parameter set to 'Test':

pipeline?START_STAGE=Test

This will cause the pipeline to skip the Build stage and start directly from the Test stage.