junior developper
junior developper

Reputation: 448

Jenkins: How to access parameters in a parameterized job

I have a parameterized build like below:

enter image description here

then i've create a groovy script to create a variable URL_TOMCAT where its value depends on the TARGET_TOMCAT parameter:

Even after this update i got the same error

import hudson.model.*
def target = build.buildVariableResolver.resolve("TARGET_TOMCAT")
def URL_TOMCAT = ""
switch(target ) {
  case "tomcat1": URL_TOMCAT= "http://localhost:8080/manager/text"
   break
  case "tomcat2": URL_TOMCAT = "http://localhost:8089/manager/text"
   break  
}

Then i want to get The URL_TOMCAT value and adjust the maven build step as shown: enter image description here

But i got this error : enter image description here

Has any on an idea how to fix this error?

Upvotes: 1

Views: 9814

Answers (1)

Tuffwer
Tuffwer

Reputation: 1047

In your groovy script you need to make an API call to get the value of the parameter from Jenkins into your workspace.

Import hudson.model

def targetTomcat = build.buildVariableResolver.resolve("TARGET_TOMCAT")

def URL_TOMCAT = ""
switch(targetTomcat) {
  case "tomcat1": URL_TOMCAT = "http://localhost:8080/manager/text"
    break
  case "tomcat2": URL_TOMCAT = "http://localhost:8089/manager/text"
    break  
}

I want to point out that the URL_TOMCAT variable won't be available to any other buildsteps, it's scoped to just the groovy build step. If you want to expose your URL_TOMCAT variable to the rest of the build you'll need to expose it to the build environment somehow. I normally do this by writing the value to a file as a key value pair and using the EnvInject Plugin

You can write it to a file in groovy like so:

def workspace = build.buildVariableResolver.resolve("WORKSPACE")
new File("${workspace}\\Environment.Variables").write("URL_TOMCAT=${URL_TOMCAT}")

If you don't want to write it to the jobs workspace you can skip grabbing that value and just code a specific path.

After your groovy build step add an Envinject build step and enter the path to the file containing the key value pair in the Properties File Path field. You should be able to reference URL_TOMCAT like any other environment variable in the rest of the build. Continuing with the about path I would use ${WORKSPACE}\Environment.Variables as the path.

Upvotes: 1

Related Questions