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

Article ID:360029265412
2 minute readKnowledge base

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.

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 controller 2.164.3.2

This article is part of our Knowledge Base and is provided for guidance-based purposes only. The solutions or workarounds described here are not officially supported by CloudBees and may not be applicable in all environments. Use at your own discretion, and test changes in a safe environment before applying them to production systems.