I have a Jenkins Pipeline that I would like to have a user input on to checkout a specific branch of their choosing. i.e. If I create a branch 'foo' and commit it, I'd like to be able to build on that branch from a menu. As there are several users all creating branches I want this to be in a declarative pipeline rather than GUI. At this stage shown below, I'd like a user input to checkout the branch after Jenkins has polled git to find out the branches available. Is this possible?
stage('Checkout') {
checkout([$class: 'GitSCM',
branches: [[name: '*/master']],
doGenerateSubmoduleConfigurations: false,
extensions: [[$class: 'CloneOption', noTags: true, reference: '', shallow: true]],
submoduleCfg: [],
userRemoteConfigs: [[credentialsId: 'secretkeys', url: '[email protected]:somekindofrepo']]
]);
}
}
I currently have this but it's not pretty;
pipeline {
agent any
stages {
stage("Checkout") {
steps {
checkout([$class: 'GitSCM',
branches: [
[name: '**']
],
doGenerateSubmoduleConfigurations: false,
extensions: [[$class: 'LocalBranch', localBranch: "**"]],
submoduleCfg: [],
userRemoteConfigs: [
[credentialsId: 'repo.notification-sender', url: '[email protected]:repo/notification-sender.git']
]
])
}
}
stage("Branch To Build") {
steps {
script {
def gitBranches = sh(returnStdout: true, script: 'git rev-parse --abbrev-ref --all | sed s:origin/:: | sort -u')
env.BRANCH_TO_BUILD = input message: 'Please select a branch', ok: 'Continue',
parameters: [choice(name: 'BRANCH_TO_BUILD', choices: gitBranches, description: 'Select the branch to build?')]
}
git branch: "${env.BRANCH_TO_BUILD}", credentialsId: 'repo.notification-sender', url: '[email protected]:repo/notification-sender.git'
}
}
}
post {
always {
echo 'Cleanup'
cleanWs()
}
}
}
Head over to your Jenkins instance and create a new item. Enter a name for the job, and select the “Multibranch Pipeline” option at the end of the screen. Then, click on the OK button. In the next screen, go to the “Branch sources” tab, click on the “Add source” button, and choose “Git” from the dropdown menu.
The problem is that Jenkins is defining the origin with only the branch that is discovered. @swoop81 answer is working but if you just want to checkout one branch, you could fetch only this one.
Instead of taking the input as a string you can use "Build with Parameter" along with https://wiki.jenkins.io/display/JENKINS/Git+Parameter+Plugin .
By using the plugin you can instruct the Jenkins to fetch all the available branches, tags from GIT repository.
Get the branch name in the pipeline with the parameter BRANCH_TO_BUILD and checkout the chosen branch .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With