patternMinor
Jenkins Pipeline - input only if branch matches
Viewed 0 times
matchesjenkinsinputbranchonlypipeline
Problem
I want to ask for input but only if we are on a certain branch. But the input is run before the when. Can this be done with declarative syntax?
For example this will always prompt even when the branch is not master
For example this will always prompt even when the branch is not master
stage('only on master') {
when {
branch 'master'
}
input { ... }
}Solution
I see two approaches :
Save current branch name on a variable and check it in a if statement
or
Run a shell script to know if current folder is a git repo on master
The following command check if current folder is a git repository printing "true" ( or returning a error if does not have repo)
The next, print the current branch name
Use both to create a script that sets an environment variable.
Check the value on your pipeline, to show the input
Save current branch name on a variable and check it in a if statement
CURRENT_BRANCH = '...' // some value or parameter
stage('only on master') {
if (CURRENT_BRANCH == 'master') {
input {
...
}
}
// be sure to check if input was set or define a default valueor
Run a shell script to know if current folder is a git repo on master
The following command check if current folder is a git repository printing "true" ( or returning a error if does not have repo)
git rev-parse --is-inside-work-treeThe next, print the current branch name
git branch | grep \* | cut -d ' ' -f2Use both to create a script that sets an environment variable.
Check the value on your pipeline, to show the input
stage('only on master') {
// Set true on IS_ON_MASTER if current branch is master,
// otherwise set false
sh ./check-branch-master.sh
if (env.IS_ON_MASTER) {
input {
...
}
}Code Snippets
CURRENT_BRANCH = '...' // some value or parameter
stage('only on master') {
if (CURRENT_BRANCH == 'master') {
input {
...
}
}
// be sure to check if input was set or define a default valuegit rev-parse --is-inside-work-treegit branch | grep \* | cut -d ' ' -f2stage('only on master') {
// Set true on IS_ON_MASTER if current branch is master,
// otherwise set false
sh ./check-branch-master.sh
if (env.IS_ON_MASTER) {
input {
...
}
}Context
StackExchange DevOps Q#3951, answer score: 4
Revisions (0)
No revisions yet.