Search code examples
jenkinsjenkins-pipelinepipelinejobsjenkins-job-dsl

Coalesce parameters in Jenkins Job DSL


I have a pipelineJob defined in Job DSL.

It runs a pipeline/Jenkinsfile which it checks out of git.

I want people to be able to type in the git branch from which to pull the Jenkinsfile - (i.e. in a stringParam) - or, if they have not typed in a branch, to default to a branch which I have set in a choiceParam (i.e. this will be 'develop' or 'master')

This does not work:

pipelineJob('some-job') {
  parameters {
    choiceParam('gitCreds', [gitCreds], 'Stash credential')
    stringParam('gitUrl', 'https://some-repo.git', 'URL for the Stash repo')
    stringParam('gitBranchOverride', '', 'Type in some feature branch here if you wish')
    choiceParam('gitBranch', ['develop'], '...otherwise the job should default to a branch here')
 }
  definition {
    cpsScm {
      scm {
        git {
          branch('$gitBranchOverride' ?: '$gitBranch')
          extensions {
            wipeOutWorkspace()
          }
          remote {
            credentials(gitCreds)
            url ('$gitUrl')
          }
        }
      }
    }
  }
}

It works if I enter a value into gitBranchOverride, but if I don't, it seems to enumerate all the branches, and check out a random one - i.e. it's not honouring the value in gitBranch


Solution

  • Don't know if i'm understanding your problem correctly but this is how I have my code for creating pipelinejobs:

    def git_branch = getBinding().getVariable('GIT_BRANCH')
    def gitrepo = "ssh://[email protected]/somerepo.git"
    def credential_id = "awesomecredentials"
    pipelineJob("MyAwesomeJob") {
        description("""This job is awesome\n\n__input__:\n* My parameter\n* Branch\n\n__branch__: ${git_branch}""")
        parameters {
            stringParam(name='MyParameter', description='AwesomeParameterHere')
            stringParam('branch', defaultValue='origin/develop', description='Branch to build')
        }
        definition {
            cpsScm {
                scm {
                    git {
                        branch('$branch')
                        remote {
                            url("gitrepo")
                            credentials(credential_id)
                        }
                    }
                    scriptPath("jenkins/my_awesome_pipeline/Jenkinsfile")
                }
            }
        }
    }
    

    With this, my job is created with a parameter for branch with a default one selected.