MissingPropertyException: No such property: filename for class: groovy.lang.Binding - jenkins

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.

Related

How to set multiple environmental variable with Jenkins Groovy Script

I am trying to use Jenkins environmental variable with groovy scripts and assign them to environment variable so I can use those variable through out each Jenkins steps. But I cannot take out Groovy map objects. Is there anything I am doing wrong?
this is simple. In groovy script I have added two keys as "repo" and "version". Environment variables are created from that name and in a shell, I can get those simply by calling their keys.
echo $repo
echo $version

Accessing environment variables in Extended Choice Parameter

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.

How to put JOB_NAME excluding folder into an environment variable in Jenkins?

I want to put the name of the currently executing Jenkins job into an environment variable for use later in my pipeline, without the folder name. I'm assuming I need something like :
withEnv(['JOB_BASE_NAME=JOB_NAME.split('/').last()']) {
echo "Job base name: ${JOB_BASE_NAME}"
}
but I get an error:
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException:
unclassified method java.lang.String div java.lang.String
In Jenkins documentation, you have the §Using environment variables section which mentions:
The full list of environment variables accessible from within Jenkins Pipeline is documented at localhost:8080/pipeline-syntax/globals#env, assuming a Jenkins master is running on localhost:8080
If you follow the link you can find that JOB_BASE_NAME is already provided OOTB by Jenkins so this is exactly what you want.
JOB_BASE_NAME -
Short Name of the project of this build stripping off folder paths, such as "foo" for "bar/foo".
I worked it out. In case anyone finds it useful:
def jobBaseName = "${env.JOB_NAME}".split('/').last()
echo "Job Name (excl. path): ${jobBaseName}"
might be too late, but thought would help someone in need for a simpler solution using bash.
${JOB_NAME%%/*}
Example:
I have a project created with name: poc_jenkins_pipeline
If i try accessing default jenkins variable ${JOB_NAME}
it returns value poc_jenkins_pipeline/develop i.e. <project name>/<branch name>
By using % operator in bash ${JOB_NAME%%/*} returns value poc_jenkins_pipeline
Reference Link - https://qa.nuxeo.org/jenkins/pipeline-syntax/globals
If you want the name of Jenkins job without the folder name you can use:
def job = "${JOB_BASE_NAME}"

How to invoke Inject environment variables to the build process plugin in jenkinsFIle jenkins 2.x with pipeline

I'm trying to migrate my project from jenkins 1 to jenkins 2.x using pipeline as code or Jenkinsfile.
But I don't see any option in snippet generator to generate environment injector plugin into a script in Jenkinsfile.
Anyone can help?
I'm assuming that you want to read properties from a specific file and inject them as environment variables?
If so, this is a solution:
Create the file that will contain the environment properties
You create some properties file called project.properties with following content:
PROJECT_VERSION='1.4.34'
Then, on your pipeline code, you've to add the following code in order to be able to read the file and inject read variables as environment variables:
node {
load "${WORKSPACE}\\project.properties" // assuming that props file is in
Jenkins Job's workspace
echo "PROJECT VERSION: ${PROJECT_VERSION}"
}
First line read and inject variable PROJECT_VERSION as environment variable
Second line is just to print read variable to make sure that everything worked seamlessly
Result:
Wanted to just comment on your question, but my lack of reputation is hindering me.
The list of supported steps is here: https://jenkins.io/doc/pipeline/steps/
In general, you can use other plugins by using their Java style invocation.
i.e.
step([$class: 'classname', parametername: 'value'])
I used this example for read a properties file and use it in a pipeline stage:
node(){
file = readFile('params.txt')
prop=[:]
file.eachLine{ line ->
l=line.split("=")
prop[l[0]]=l[1]
}
withEnv(['MyVar1='+prop["MyVar1"],'MyVar2='+prop["MyVar2"],'MyVar3='+prop["MyVar3]]){
stage('RUN_TEST'){
echo env.MyVar1
echo env.MyVar2
echo env.MyVar3
sh"echo $MyVar1"
}
}
}

Parameterised build in jenkins: Not getting parameters as shell env variables

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!

Resources