I want to write a Groovy script for Extended Choice Parameter that would use access WORKSPACE variable. When I try:
List<String> artifacts = new ArrayList<String>()
artifacts.add(env.WORKSPACE)
asdf = env.WORKSPACE
println asdf
return artifacts
I get the following error:
No such property: env for class: _1775dc8d170bd01576ff2b650850017e
groovy.lang.MissingPropertyException: No such property: env for class: _1775dc8d170bd01576ff2b650850017e
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:53)
at org.codehaus.groovy.runtime.callsite.PogoGetPropertySite.getProperty(PogoGetPropertySite.java:52)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:307)
at _1775dc8d170bd01576ff2b650850017e.run(_1775dc8d170bd01576ff2b650850017e:2)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:585)
at com.cwctravel.hudson.plugins.extended_choice_parameter.ExtendedChoiceParameterDefinition.executeGroovyScript(ExtendedChoiceParameterDefinition.java:727)
at com.cwctravel.hudson.plugins.extended_choice_parameter.ExtendedChoiceParameterDefinition.executeGroovyScriptAndProcessGroovyValue(ExtendedChoiceParameterDefinition.java:709)
at com.cwctravel.hudson.plugins.extended_choice_parameter.ExtendedChoiceParameterDefinition.computeValue(ExtendedChoiceParameterDefinition.java:676)
at com.cwctravel.hudson.plugins.extended_choice_parameter.ExtendedChoiceParameterDefinition.computeEffectiveValue(ExtendedChoiceParameterDefinition.java:855)
at com.cwctravel.hudson.plugins.extended_choice_parameter.ExtendedChoiceParameterDefinition.getParameterDefinitionInfo(ExtendedChoiceParameterDefinition.java:1451)
at jdk.internal.reflect.GeneratedMethodAccessor701.invoke(Unknown Source)
What am I doing wrong?
Also, will I be able to call a python script from this plugin, that would provide me list of parameters that I wish to use?
The env is available in the environment of a Jenkins build. The extended choice groovy script runs before your build, as you are entering the parameters. It runs in a GroovyShell environment, and all it can do is run a simple script to render the choices for the parameter. For example, if you are creating a multi select parameter, the script to generate the choices could be:
return ["DEV environment", "TEST environment", "PROD environment"]
So you can use env.WORKSPACE in your Jenkinsfile or pipeline script, but in the extended choice parameter script box, it isn't defined.
According to this this answer, you should be able to use something like
System.getEnv().get('WORKSPACE')
But I couldn't get that to do what you want.
Related
In my Jenkins pipeline I want to access the Windows environment variable named "ProgramFiles(x86)". However, I do not know what syntax I have to use to make Jenkins pipeline understand that the '(x86)' is part of the environment variable name. I keep getting an error with for example "echo env.ProgramFiles(x86)
groovy.lang.MissingPropertyException: No such property: x86 for class: groovy.lang.Binding
I also tried
echo "${ProgramFiles(x86)}"
and
echo "${env.ProgramFiles(x86)}"
but no success there either.
you can use single quotes around the variable name see below example:
echo "${env.'ProgramFiles(x86)'}"
I'm trying to use DSL pipelines in Jenkins. I thought it'd be nice if I could use the project name as part of my script.
git credentialsId: 'ffffffff-ffff-ffff-ffff-ffffffffffffff',\
url: "${repo_root}/${JOB_NAME}.git"
I get the error:
groovy.lang.MissingPropertyException: \
No such property: JOB_NAME for class: groovy.lang.Binding
I thought I followed these directions, and they mention JOB_NAME as one of the variables.
I decided to try:
sh 'env'
in my DSL, and this prints out:
JOB_NAME = foo-bar
which is what I expect.
Another blog mentions:
Usage of environment variables
We have two ways to get their value. The properties passed by -D= during the startup we could read as System.getProperty("key") thanks to the Groovy's strong relation with Java.
Reading normal environment variables in Java way is the System.getenv("VARIABLE")...
Let's try this:
println "JOB_NAME = " + System.getenv('JOB_NAME');
Now, I get:
java.lang.NullPointerException: Cannot get property 'System' on null object
Null object? But, I can see that JOB_NAME is an environment variable!
How do I read in the $JOB_NAME into a DSL script in a Pipeline job. I am trying a Pipeline job, and when I get that working will make this a Multibranch Pipeline with a Jenkinsfile.
All environment variables are accessible using env, e.g. ${env.JOB_NAME}.
Okay this really vexed me for a while today. Ultimately, I was being done in by a couple of things:
Single-quoted strings in Groovy mean "don't evaluate variables," just like it does in bash
Using $ interpolation is completely unnecessary if you're just referencing the variable, so you can just do env.JOB_NAME.
This SO question proved to be the one that helped me crack the code: Jenkins Workflow Checkout Accessing BRANCH_NAME and GIT_COMMIT
Indeed just use ${env.JOB_NAME} to access a known variable.
However if you need to access environment variable where name is given by another variable (dynamic access), just use env["your-env-variable"].
I had the problem where I configured 3 environment variables (in Jenkins -> Administer -> Configure System -> Environment variables), let's name them ENV_VAR_1, ENV_VAR_2, ENV_VAR_3.
Now I want to dynamically access them, I can do as such :
def envVarName = "ENV_VAR_" + count // Suppose count is initialized in a loop somewhere above...
def value = env[envVarName] // Will be resolved to env["ENV_VAR_1"] depending on count value
My environment variables in Jenkins configuration look like this :
I had an issue with this not working. The globally set properties/environment variables were only available inside a node step. It's a bug in version 2.4 of Pipeline plugin. Upgrade to 2.5 if you face this issue and your global properties will be available anywhere in the script. I've posted this to the Jenkins wiki here with the test script I used.
Jenkins version: 2.6, Linux
Problem: The parameterized build variables are not are not visible (as env variables) in the Execution step "shell script", They used to be visible in the older 1.x jenkins version.
Steps:
Create a parameterized build with a multi configuration project.
Add a parameter to the build (using This project is parameterized-> string parameter, {if that matters} ).
Add a build step "Execute shell" to the job.
Access these parameters in this shell script as env variables.
echo "++++++++++++ building $lib_name ($lib_version) ++++++++++++++"
To solve this, I have tried to create a groovy script in "Prepare an environment for the run" section. I created env variables using hardcoded values which are pased to shell script as env vars.
def map = ['lib_name':'lib1']
map['lib_version'] = 'master'
return map
But, without hardcoding, I cannot access these variable values even when using solution from
How to retrieve Jenkins build parameters using the Groovy API?
I dont know what else has to be done. Can some one please suggest?
---> Updating based on the comments on this question:
When I run the following lines in jenkins, I get exception:
def buildVariablesMap = Thread.currentThread().executable.buildVariables
buildVariablesMap.each{ k, v -> println "${k}:${v}" }
FATAL: No such property: executable for class: hudson.model.OneOffExecutor
groovy.lang.MissingPropertyException: No such property: executable for class: hudson.model.OneOffExecutor
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:53)
at org.codehaus.groovy.runtime.callsite.GetEffectivePojoPropertySite.getProperty(GetEffectivePojoPropertySite.java:66)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGetProperty(AbstractCallSite.java:296)
I have had also similar problem. This is a solution which worked for me. I created a method which always takes and delivers exactly one build parameter which I need.
method:
String readingBuildParameters(VariableResolver varRes, String paramName){
return varRes.resolve(paramName)
}
the line how I use it in a code:
Build currentBuild = Executor.currentExecutor().currentExecutable
VariableResolver varResolver = currentBuild.getBuildVariableResolver()
df_parameter = readingBuildParameters(varResolver, "parameter_name")
BR,
Zoltan
To access the parameters in your shell script:
to evaluate them in echo: e.g. echo "${myParam}"
to use them in code: def myNewvalueParam = ${myOtherParam}
To retrieve build variables from groovy script as a build step:
def buildVariablesMap = Thread.currentThread().executable.buildVariables
println buildVariablesMap['BUILD_NUMBER']
But please note that for your custom/altered environment variables to be visible for the next steps you should use EnvInject plugin, with it you can define a step that will export new env variables as key-value pair just like properties file.
This was a bug in jenkins, probably in the credentials plugin:
https://issues.jenkins-ci.org/browse/JENKINS-35921
Thanks for all your help!
I am using Jenkins + pipeline plugin + envInject plugin. I am trying to get values from property file in pipeline script. But it doesn't see variables. This is me property file:
filename = "1.txt"
This is how I set up property injection:
This is my script:
echo "${filename}"
Please, help me to get these values
Where did you define variable "filename" ?
In order to access Jenkins project variables in EnvInject Plugin, you must first define it as Project Parameters (e.g. Check "This project is parameterized" and add a String Parameter "filename").
Only then you can call it within EnvInject script.
I trigger a shell script from Jenkins, This scripts get date and export it as a environment(Linux) variable $DATE. I need to use this $DATE inside same Jenkins job. I made job as parameter build. Created a string parameter as DATE value as DATE=$DATE. But it is not working.
Please suggest !!
You mention that you are exporting a DATE environment variable in an shell script, which is presumably being started via an "Execute shell" step.
The problem is, once the shell step has completed, that environment is gone — the variables will not be carried over to subsequent build steps.
So when you later try to use the $DATE value — whether in another build step, or as a parameter to another job — that particular environment variable will no longer exist.
What you can do instead is use the EnvInject plugin to export environment variables during a build. Variables set up using this plugin will be available to all subsequent build steps.
For example, you could write the DATE to a properties field in one build step:
echo DATE=$(date +%Y-%m-%d) > env.properties
Then you can add an "Inject environment variables for your job" build step, and enter env.properties in the "Environment Properties File Path" field.
That way, the DATE variable (and anything else in that properties file) will be exported and will be visible to the rest of the build steps.
You could use an assignment statement and sh's returnStdout to get the value in Jenkins without having to write to a properties file.
foo = sh(
returnStdout: true,
script: 'date'
)
Then later on in the Jenkinsfile you can use $foo like any other variable.
EDIT: This is for a pipeline job, not a freestyle job.
I had the same issue.
The solution that worked for me was:
env.ABC=bat(returnStdout: true,
script: ''' #echo off echo abc ''').trim()
The .trim() and #echo off is important if you want to reuse the variable in another batch script.