Insert variable in parameter into parametrized build in Jenkins

Viewed 1745

Have a Jenkins job with build parameter BRANCH. When job run manually user can choose branch from a list to deploy. List provided by git plugin.

But this job also can be invoked by GitLab hook. In this case parameter will have a default value, because didn't receive any input.

Is there a way to have a parameter BRANCH with relevant information? With a branch name coming from GitLab hook.

P.S. I think it's possible by set default value to something ${BRANCH_FROM_HOOK ?: default_value} it will check presence of BRANCH_FROM_HOOK variable. Need only find a way how to put into BRANCH_FROM_HOOK variable, value of branch coming from hook. I now that gitlab plugin, who receive a hook, set into gitlab.Branch value of branch from which hook comes.

UPDATE: What I have done to achieve this:

  • Specify git parameter:

gitParameter defaultValue: "${env.gitlabBranch ?: "origin/master"}" but didn't as gitlabBranch is not set on the build start step.

  • Setup job parameters as it suggested on gitlab plugin page here:

    • Keep Jenkins Environment Variables
    • Keep Jenkins Build Variables
    • Override Build Parameters
  • Added to section "Groovy script":

import hudson.model.*
def env = Thread.currentThread()?.executable.parent.builds[0].properties.get('envVars')
def map = [:]

if (env['gitlabBranch'] != null) {
    map['branch'] = env['gitlabBranch'] 
}
return map

After this add parameter:

gitParameter name: branch, defaultValue: "${env.gitlabBranch ?: "origin/master"}"

to match map['branch'] as said in doc - not work, also tried:

gitParameter defaultValue: "${branch ?: "origin/master"}" - also not worked.

Not worked mean see origin/master value, intead of actual branch coming from gitlab hook.

Where I am wrong?

1 Answers

The answer is use Generic Webhook plugin, not GitLab. And use it's feature map his variables to parameters of job:

If your job is parameterized, and you resolve variables that have the same name as those parameters, then the plugin will populate the parameters when triggering job. That means you can, for example, use the parameters in combination with an SCM plugin, like GIT Plugin, to pick a branch.

End.)

Related