简体   繁体   中英

Jenkins Pipeline Choose Specific Branch

I have a Jenkins Pipeline that I would like to have a user input on to checkout a specific branch of their choosing. ie 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: 'git@github.com: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: 'git@github.com: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: 'git@github.com:repo/notification-sender.git'
                }
            }
          }
    post {
      always {
        echo 'Cleanup'
        cleanWs()
        }
    }
  }

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 .

Here is a solution without any plugin using Jenkins 2.249.2, and a declarative pipeline:

The following pattern prompt the user with a dynamic dropdown menu (for him to choose a branch):

(the surrounding withCredentials bloc is optional, required only if your script and jenkins configuratoin do use credentials)

node {

withCredentials([[$class: 'UsernamePasswordMultiBinding',
              credentialsId: 'user-credential-in-gitlab',
              usernameVariable: 'GIT_USERNAME',
              passwordVariable: 'GITSERVER_ACCESS_TOKEN']]) {
    BRANCH_NAMES = sh (script: 'git ls-remote -h https://${GIT_USERNAME}:${GITSERVER_ACCESS_TOKEN}@dns.name/gitlab/PROJS/PROJ.git | sed \'s/\\(.*\\)\\/\\(.*\\)/\\2/\' ', returnStdout:true).trim()
}

} pipeline {

agent any

parameters {
    choice(
        name: 'BranchName',
        choices: "${BRANCH_NAMES}",
        description: 'to refresh the list, go to configure, disable "this build has parameters", launch build (without parameters)to reload the list and stop it, then launch it again (with parameters)'
    )
}

stages {
    stage("Run Tests") {
        steps {
            sh "echo SUCCESS on ${BranchName}"
        }
    }
}

}

The drawback is that one should refresh the jenkins configration and use a blank run for the list be refreshed using the script ... Solution (not from me): This limitation can be made less anoying using an aditional parameters used to specifically refresh the values:

parameters {
        booleanParam(name: 'REFRESH_BRANCHES', defaultValue: false, description: 'refresh BRANCH_NAMES branch list and launch no step')
        choice(
          name: 'BranchName',
          choices: "${BRANCH_NAMES}",
          description: 'choose a branch (ignored if refresh_branches is selected)'
    )
}

then wihtin stage:

stage('a stage') {
   when {
      expression { 
         return ! params.REFRESH_BRANCHES.toBoolean()
      }
   }
   ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM