Jenkins input()'s semantics
Aug 27, 2019Jenkins can be quite tricky when you need to define conditional logic within the dsl
, but not specifically in script {}
block. The latter allows for any plain groovy code, so that’s quite easy. But sometimes you need team interaction; in such cases it’s useful to resort to the input()
method. The most common scenario is when want a basic approve/abort
, so there you just do:
stage('User consent') {
steps {
input 'Deploy to production?'
}
}
}
But what happens if you want to go further and perform some action on abort
?
The most obvious way forward for me was to wrap the input step into a try/except
, as suggested by Cloudbees. The action is taken upon abort
click, then except
code is called:
try {
userInput = input(
id: 'Proceed1', message: 'Was this successful?', parameters: [
[$class: 'BooleanParameterDefinition', defaultValue: true, description: '', name: 'Please confirm you agree with this']
])
} catch { // abort clicked
// Your remediation code goes here
}
Looks nice, however, if the userInput
is not available. You cannot check if the user has put a tick or not when the build was aborted:
...
} catch { // abort clicked
if (userInput) {
// This won't work! `userInput` is not defined within this scope
}
}
You could wrap code in a try/except/finally
, but that heavily bloats the pipeline.
So what’s the best way? KISS! Use abort for a complete abort of the job and use conditional logic for everything else. Here’s a stage view:
stage('User consent') {
script {
userInput = input(
id: 'Proceed1', message: 'Something has changed. Choose an action to take.', parameters:
[choice(name: 'Action', choices: 'Abort reverting last commit\nProceed to deployment', description: '')])
if (userInput == 'Abort reverting last commit') {
dir('checkout-repo') {
sh """
git revert --no-commit ${commit}
git commit -m 'Jenkins revert: rollback ${commit} on abort'
git push origin HEAD:master
"""
}
currentBuild.result = 'ABORTED'
error("Job aborted, reverted changes made in last commit")
}
}
}
This way, things can’t go wrong. If a user is presented with a selection to abort and revert or to proceed with the deployment. Depending on the choice, after clicking approve
, the appropriate action will be taken, but proceed
is not processed: the pipeline just goes on. Only if abort is clicked, then the pipeline get’s aborted completely.