Chuchaki
Chuchaki

Reputation: 371

List git branches as dynamic parameter in declarative pipeline

Im struggeling to include a dynamic choice parameter into my declarative pipeline. I have tried lots of different suggestions from everywhere which did not really help as I've completely lost track right now :-)

For the desired functionality: I have a Jenkinsfile (declarative) for the jenkins pipeline. I want to have a parameter which allows me to choose a specific branch from a git repository to be used in the pipeline.

Basic structure of the jenkinsfile:

pipeline {

    agent { node { label "XXX-XXX-XXX" } }

    options {
        gitLabConnection('XXX-XXX-XXX')
    }

    stages {
        stage("STAGE A") {
            parallel{
                stage("A"){
                    steps {
                        // DO STUFF
                    }
                }
                stage("B"){
                    steps {             
                        // DO STUFF
                    }
                }
            }
        }
    }
}

I've tried to add a parameter using the following snippet within the pipeline. I was not able to dynamically fill the list of choices. It was either empty or it generated errors.

parameters {
        choice(
            name: 'CHOICE_2',
            choices: 'choice_1\nchoice_2\nchoice_3\nchoice_4\nchoice_5\nchoice_6',
            description: 'CHOICE_2 description',
        )
}

Alternatively I've tried to have the following outside of the pipeline declaration. I left one if the script variations in as an example. Here again, I was not able to populate the list of choices. The field stayed empty:

node {
    label "XXX-XXX-XXX"
    properties([
        parameters([
            [$class: 'ChoiceParameter', 
                choiceType: 'PT_SINGLE_SELECT', 
                description: 'The names', 
                filterLength: 1, 
                filterable: true, 
                name: 'Name', 
                randomName: 'choice-parameter-5631314439613978', 
                script: [
                    $class: 'GroovyScript', 
                    script: [
                        classpath: [], 
                        sandbox: false, 
                        script: '''
                            def gettags = "git ls-remote [email protected]".execute()
                            def tagList = []
                            def t1 = []
                            String tagsString = null;
                            gettags.text.eachLine {tagList.add(it)}
                            for(i in tagList)
                                t1.add(i.split()[1].replaceAll('\\^\\{\\}', ''))
                            t1 = t1.unique()
                            tagsString = StringUtils.join((String[])t1, ',');

                            return tagsString
                                '''
                    ]
                ]
            ], 
        ])
    ])
}

At this point I've tried too many different approaches and would like to go a step back.

Can anyone support me with an approach and some hints or ressources ?

Thanks & with best regards,

Upvotes: 2

Views: 5419

Answers (1)

nandilov
nandilov

Reputation: 719

I will suggest that you build a file with a lisf of the remote branches, aftet that you can have a stage to approve and choose the right branch - have you tried multibranch pipelines? Maybe it applies to your use case...

pipeline {

    agent { node { label "XXX-XXX-XXX" } }

    options {
        gitLabConnection('XXX-XXX-XXX')
        skipDefaultCheckout() //this will avoid to checkout the code by defaul
    }

    stages {
        stage("Get Branches from Git Remote"){ // you might need to tweak the list retrieved from git branches cmd
            steps{
                 withCredentials([usernamePassword(credentialsId: 'git-credential', passwordVariable: 'key', usernameVariable: 'gitUser')]) {    
                     sh """
                        mkdir git_check
                        cd git_check
                        git clone https://${gitUser}:${key}@${GIT_URL} .
                        git branch -a | grep remotes > ${WORKSPACE}/branchesList.txt 
                        cd ..
                        rm -r git_check
                     """
                  }
               }    
            }
        }
        stage('User Input'){
           steps{
               listBranchesAvailable = readFile 'branchesList.txt'
                    env.branchToDeploy = timeout (time:1, unit:"HOURS") {
                        input message: 'Branch to deploy', ok: 'Confirm!',
                                parameters: [choice(name: 'Branches Available:', choices: "${listBranchesAvailable }", description: 'Which branch do you want to build?')]
                        }     
           }       
        }
        stage('Checkout Code'){
            steps{
                cleanWs() // ensure workspace is empty
                git branch: "${branchToDeploy}", changelog: false, credentialsId: 'gitcredential', poll: false, url: "${GIT_URL}" //checks out the right code branch

            }
        }
        stage("STAGE A") {
            parallel{
                stage("A"){
                    steps {
                        // DO STUFF
                    }
                }
                stage("B"){
                    steps {             
                        // DO STUFF
                    }
                }
            }
        }
    }
}

Upvotes: 1

Related Questions