How can I approve a deployment and add an optional delay for the deployment

Issue

I have a Jenkins Pipeline for my application deployment, and when I approve the deployment, I would like to be able to add an optional delay for the deployment of a number of hours.

Environment

Resolution

The input step can accept parameters, so one possible solution to this would be to add a choice type parameter to the input step, and then use the sleep step based on the number of hours selected by the approver:

pipeline {
    agent none
    stages {
        stage('Build') {
            agent any
            steps {
                echo 'compiling...'
            }
        }
        stage('Test') {
            agent any
            steps {
                echo 'testing...'
            }
        }
        stage('Approval') {
            // no agent, so executors are not used up when waiting for approvals
            agent none
            steps {
                script {
                    def deploymentDelay = input id: 'Deploy', message: 'Deploy to production?', submitter: 'rkivisto,admin', parameters: [choice(choices: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24'], description: 'Hours to delay deployment?', name: 'deploymentDelay')]
                    sleep time: deploymentDelay.toInteger(), unit: 'HOURS'
                }
            }
        }
        stage('Deploy') {
            agent any
            steps {
                // uses https://plugins.jenkins.io/lockable-resources
                lock(resource: 'deployApplication'){
                    echo 'Deploying...'
                }
            }
        }
    }
}

Here is what the Pipeline looks like in Blue Ocean:

Pipeline view in Blue Ocean

When you choose 1 hour from the drop down list (I did a drop down list instead of a string, to reduce input errors), you can see in the log that it is sleeping for the selected number of hours:

Delay of one hour

Here is what it looks like when the build gets to the Approval stage, and you choose 0 hours delay:

Delay of zero hours

Tested product/plugin versions

CloudBees Core on Modern Cloud Platforms - Managed Master 2.164.3.2

Have more questions? Submit a request

0 Comments

Please sign in to leave a comment.