Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access parameters in a Parameterized Build?

How do you access parameters set in the "This build is parameterized" section of a "Workflow" Jenkins job?

TEST CASE

  1. Create a WORKFLOW job.
  2. Enable "This build is parameterized".
  3. Add a STRING PARAMETER foo with default value bar text.
  4. Add the code below to Workflow Script:

    node()
    {
         print "DEBUG: parameter foo = ${env.foo}"
    }
    
  5. Run job.

RESULT

DEBUG: parameter foo = null

like image 203
Vizionz Avatar asked Feb 17 '15 22:02

Vizionz


People also ask

How do parameterized build job receive parameters?

Using build parameters, we can pass any data we want: git branch name, secret credentials, hostnames and ports, and so on. Any Jenkins job or pipeline can be parameterized. All we need to do is check the box on the General settings tab, “This project is parameterized”: Then we click the Add Parameter button.

How do I access Jenkins parameters?

How do you access parameters set in the "This build is parameterized" section of a "Workflow" Jenkins job? Create a WORKFLOW job. Enable "This build is parameterized". Add a STRING PARAMETER foo with default value bar text .

How do I get parameters in Jenkins pipeline?

Access Parameters Inside Pipeline Stages You can access a parameter at any stage of a pipeline. Accessing parameters in stages is pretty straightforward. You just have to use params. [NAME] in places where you need to substitute the parameter.

Where is build with parameters in Jenkins?

To execute the Jenkins job from Jenkins web interface first go to respective project workspace and then click on “Build with Parameters” option from left panel. After that, you will be asked to choose/set parameter value (In my project I have set BROWSER parameter.)


9 Answers

I think the variable is available directly, rather than through env, when using Workflow plugin. Try:

node()
{
    print "DEBUG: parameter foo = ${foo}"
}
like image 134
Nick Avatar answered Oct 18 '22 19:10

Nick


I tried a few of the solutions from this thread. It seemed to work, but my values were always true and I also encountered the following issue: JENKINS-40235

I managed to use parameters in groovy jenkinsfile using the following syntax: params.myVariable

Here's a working example:

Solution

print 'DEBUG: parameter isFoo = ' + params.isFoo
print "DEBUG: parameter isFoo = ${params.isFoo}"

A more detailed (and working) example:

node() {
   // adds job parameters within jenkinsfile
   properties([
     parameters([
       booleanParam(
         defaultValue: false,
         description: 'isFoo should be false',
         name: 'isFoo'
       ),
       booleanParam(
         defaultValue: true,
         description: 'isBar should be true',
         name: 'isBar'
       ),
     ])
   ])

   // test the false value
   print 'DEBUG: parameter isFoo = ' + params.isFoo
   print "DEBUG: parameter isFoo = ${params.isFoo}"
   sh "echo sh isFoo is ${params.isFoo}"
   if (params.isFoo) { print "THIS SHOULD NOT DISPLAY" }

   // test the true value
   print 'DEBUG: parameter isBar = ' + params.isBar
   print "DEBUG: parameter isBar = ${params.isBar}"
   sh "echo sh isBar is ${params.isBar}"
   if (params.isBar) { print "this should display" }
}

Output

[Pipeline] {
[Pipeline] properties
WARNING: The properties step will remove all JobPropertys currently configured in this job, either from the UI or from an earlier properties step.
This includes configuration for discarding old builds, parameters, concurrent builds and build triggers.
WARNING: Removing existing job property 'This project is parameterized'
WARNING: Removing existing job property 'Build triggers'
[Pipeline] echo
DEBUG: parameter isFoo = false
[Pipeline] echo
DEBUG: parameter isFoo = false
[Pipeline] sh
[wegotrade-test-job] Running shell script
+ echo sh isFoo is false
sh isFoo is false
[Pipeline] echo
DEBUG: parameter isBar = true
[Pipeline] echo
DEBUG: parameter isBar = true
[Pipeline] sh
[wegotrade-test-job] Running shell script
+ echo sh isBar is true
sh isBar is true
[Pipeline] echo
this should display
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

I sent a Pull Request to update the misleading pipeline tutorial#build-parameters quote that says "they are accessible as Groovy variables of the same name.". ;)

Edit: As Jesse Glick pointed out: Release notes go into more details

You should also update the Pipeline Job Plugin to 2.7 or later, so that build parameters are defined as environment variables and thus accessible as if they were global Groovy variables.

like image 36
GabLeRoux Avatar answered Oct 18 '22 19:10

GabLeRoux


When you add a build parameter, foo, it gets converted to something which acts like a "bare variable", so in your script you would do:

node {
   echo foo
}

If you look at the implementation of the workflow script, you will see that when a script is executed, a class called WorkflowScript is dynamically generated. All statements in the script are executed in the context of this class. All build parameters passed down to this script are converted to properties which are accessible from this class.

For example, you can do:

node {
    getProperty("foo")
}

If you are curious, here is a workflow script I wrote which attempts to print out the build parameters, environment variables, and methods on the WorkflowScript class.

node {
   echo "I am a "+getClass().getName()

   echo "PARAMETERS"
   echo "=========="
   echo getBinding().getVariables().getClass().getName()
   def myvariables = getBinding().getVariables()
   for (v in myvariables) {
       echo "${v} " + myvariables.get(v)
   }
   echo STRING_PARAM1.getClass().getName()

   echo "METHODS"
   echo "======="
   def methods = getMetaClass().getMethods()

   for (method in methods) {
       echo method.getName()    
   } 

   echo "PROPERTIES"
   echo "=========="
   properties.each{ k, v -> 
       println "${k} ${v}" 
   }
   echo properties
   echo properties["class"].getName()

   echo "ENVIRONMENT VARIABLES"
   echo "======================"
   echo "env is " + env.getClass().getName()
   def envvars = env.getEnvironment()
   envvars.each{ k, v ->
        println "${k} ${v}"
   }
}

Here is another code example I tried, where I wanted to test to see if a build parameter was set or not.

node {
   groovy.lang.Binding myBinding = getBinding()
   boolean mybool = myBinding.hasVariable("STRING_PARAM1")
   echo mybool.toString()
   if (mybool) {
       echo STRING_PARAM1
       echo getProperty("STRING_PARAM1")
   } else {
       echo "STRING_PARAM1 is not defined"
   }

   mybool = myBinding.hasVariable("DID_NOT_DEFINE_THIS")
   if (mybool) {
       echo DID_NOT_DEFINE_THIS
       echo getProperty("DID_NOT_DEFINE_THIS")
   } else {
       echo "DID_NOT_DEFINE_THIS is not defined"
   }
}
like image 38
Craig Rodrigues Avatar answered Oct 18 '22 18:10

Craig Rodrigues


Use double quotes instead of single quotes

e.g. echo "$foo" as opposed to echo '$foo'

If you configured your pipeline to accept parameters using the Build with Parameters option, those parameters are accessible as Groovy variables of the same name. See Here.

You can drop the semicolon (;), drop the parentheses (( and )), and use single quotes (') instead of double (") if you do not need to perform variable substitutions. See Here. This clued me into my problem, though I've found that only the double (") is required to make it work.

like image 23
Ken Goodridge Avatar answered Oct 18 '22 19:10

Ken Goodridge


To parameter variable add prefix "params." For example:

params.myParam

Don't forget: if you use some method of myParam, may be you should approve it in "Script approval".

like image 35
burtsevyg Avatar answered Oct 18 '22 17:10

burtsevyg


You can also try using parameters directive for making your build parameterized and accessing parameters:

Doc: Pipeline syntax: Parameters

Example:

pipeline{

agent { node { label 'test' } }
options { skipDefaultCheckout() }

parameters {
    string(name: 'suiteFile', defaultValue: '', description: 'Suite File')
}
stages{

    stage('Initialize'){

        steps{

          echo "${params.suiteFile}"

        }
    }
 }
like image 31
Shivankur Pal Avatar answered Oct 18 '22 19:10

Shivankur Pal


Hope the following piece of code works for you:

def item = hudson.model.Hudson.instance.getItem('MyJob')

def value = item.lastBuild.getEnvironment(null).get('foo')
like image 37
DevD Avatar answered Oct 18 '22 18:10

DevD


The following snippet gives you access to all Job params

    def myparams = currentBuild.rawBuild.getAction(ParametersAction)
    for( p in myparams ) {
        pMap[p.name.toString()] = p.value.toString()
    }
like image 35
Jeremy Woodland Avatar answered Oct 18 '22 18:10

Jeremy Woodland


Please note, the way that build parameters are accessed inside pipeline scripts (pipeline plugin) has changed. This approach:

getBinding().hasVariable("MY_PARAM")

Is not working anymore. Please try this instead:

def myBool = env.getEnvironment().containsKey("MY_BOOL") ? Boolean.parseBoolean("$env.MY_BOOL") : false
like image 43
Maksim Avatar answered Oct 18 '22 19:10

Maksim