How to get specific information about the current build project in Jenkins with Groovy? - groovy

In Jenkins/Hudson, with the help of a Postbuild Groovy script, I would like to get one of the following:
an environment variable (e.g. current JOB_NAME, BUILD_NUMBER etc.)
the result of a specific build number of the current project
the build number of the last not successful build in the current project
At the moment I only found the following way, but it's rather limited:
def item = hudson.model.Hudson.instance.getItem("GroovyMultipleFailTest")
def build = item.getLastBuild()
build.getNumber()

Using Jenkins v2.17 this works for me:
echo "BUILD_NUMBER=${env.BUILD_NUMBER}"

${manager.build.getEnvironment(manager.listener)['BUILD_NUMBER'] }

Bo Persson had the best answer, but was a little short.
To access the environment variables from the build in the Groovy Postbuild, you can grab them from the build. This sample code is useful for dumping all of the BUILD's environment variables to the console:
manager.build.getEnvironment(manager.listener).each {
manager.listener.logger.println(it);
}

If you're using Groovy script within "Env Inject", you can get current build and current job by:
currentJob.getName()
currentBuild.toString()

an environment variable (e.g. current JOB_NAME, BUILD_NUMBER etc.)
String jobName = System.getenv('JOB_NAME')

The only way I got it to work for me was with build.properties.environment.BUILD_NUMBER

I tried various approaches in this article and others, and it looks like the only one put below and also build.properties.environment.BUILD_NUMBER (upvoted) are working for me in Jenkins Execute system Groovy Script build step groovy command type
EnvVars envVars = build.getEnvironment(listener)
def n = envVars.get('BUILD_NUMBER')

Related

How can I combine expressions and predefined variables to get my build repository name as an uppercase string?

I'm trying to get my build repository name as an uppercase string combining predefine variables and expressions on Azure Devops as follows:
variables:
repoNameUpper: $[upper(variables['Build.Repository.Name'])]
- script: |
echo $(repoNameUpper)
Yet I get no output from it, what am I doing wrong here?
Yes, I know I could set a variable to achieve what I need using a bash script, yet I think it would not be so cool.
It because the Build.Repository.Name is agent-scoped, and can be used as an environment variable in a script and as a parameter in a build task. in another words - is not known at plan compile time, only at job execution time.
You can find more info in this GitHub issue.

How to set a string name for pipeline build in jenkins

I am running jenkins on a linux machine.
I have a pipeline job in place, so each pipeline build shows build number in general. Instead of that is it possible to give string parameter to display on the UI ?
I have tried checking build parameter plugin, but in pipeline configuration i don't see option to inject the string parameter. And the documentation doesn't help.
You can set the build name by doing:
currentBuild.displayName = "#${currentBuild.number} Hello"
This will name the build #2 Hello for build number 2.
For my case, i had to add a line in my pipeline groovy script
node(Slave01) {
currentBuild.displayName = "${URL_Name}"
}
${URL_Name} = here is the parameter

Jenkins + Build Flow, how to pass a variable from one job to another

I have a build flow scenario similar to the documentation example: two jobs, one running after the other.
b = build("job1")
build("job2", param1: b.????)
My job1 is a shell script that builds a package out of a checked out git repositoy and prints out the version of the built package.
I need to extract the version from job1 (parse output??) and make it available somehow as a parameter to job2. How can this be achieved? Please note that I can't know the version before running job1.
The problem with simply using export in a shell script build step is that the exported variables disappear when the shell script exits, they are not propagated up to the job.
Use the EnvInject plugin to create environment variables in your build. If you
write out a properties file as part of your build, EnvInject can read the file and inject variables as a build step. A properties file has a simple KEY=VALUE format:
MY_BUILD_VERSION=some_parsed_value
Once you have an environment variable set in your job, in the Build Flow
plugin, you can extract the variable's value and use it in subsequent jobs:
def version = build.environment.get( "MY_BUILD_VERSION" )
out.println String.format("Parameters: version: %s", version)
build( "My Second Build", MY_BUILD_VERSION: version )
When you run job1 export the version with name as system property.
export appVersion="stringOfVersion-123"
Then it depend if you know how long is version (count of numbers or others characters). If you know it you can parse variable from end in second build as new variable and use it.
How parse string you can find in this question with nice examples.
If job2 always should get some information from job1 you could use approach without parameters. job1 could publish artifact with version and job2 will use that artifact (with Copy Artifact Plugin for example). With that approach job2 could be executed also as standalone job.
For anyone else coming upon this, another solution is to use a scriptler script, where you pass in the .properties file path, and the script will add the properties to the list of job variables:
Properties properties = new Properties()
FilePath workspace = build.getWorkspace()
FilePath sourceFile = workspace.child(path)
properties.load(sourceFile.read())
properties.each { key, value ->
key = key.replace(".", "_").toUpperCase()
Job.setVariable(build, key, value)
println "Created Variable: " + key + "=" + value
}
This will convert any periods to underscores, and capitalize all letters. Using a scriptler script ensures that you have a method that works independent of the "plugin soup" you are using.

Read file from Jenkins workspace with System groovy script

I have a question very similar to this: Reading file from Workspace in Jenkins with Groovy script
However I need to read the file from a System Groovy script so the solution of using Text-finder or the Groovy PostBuild plugin will not work.
How can I get the workspace path from a system groovy script? I have tried the following:
System.getenv('WORKSPACE')
System.getProperty("WORKSPACE")
build.buildVariableResolver.resolve("WORKSPACE")
Thanks!
If you have a file called "a.txt" in your workspace, along with a script called "sysgvy.groovy" that you want to execute as a system groovy script. Suppose your "sysgvy.groovy" script needs to read the file "a.txt".
The issue of this topic is that if your script read "a.txt" directly without providing any path, "sysgvy.groovy" executes and will throw an error saying cannot find "a.txt".
I have tested and found that the following method works good.
def build = Thread.currentThread().executable
Then use
build.workspace.toString()+"\\a.txt"
as the full location string to replace "a.txt".
It's also important to run on the Jenkins master machine by placing "a.txt" and "sysgvy.groovy" onto Jenkins master machine's workspace. Executing on slave machine does not work.
Try it, the file should be found and get read in the script without any problem.
If there is problem with variable Thread, it is just that some modules need to be imported. So add these lines to the start of code:
import jenkins.*
import jenkins.model.*
import hudson.*
import hudson.model.*
Each build has a workspace, so you need to find the desired project first. (The terms "job" and "project" are used rather interchangeable in Jenkins - also in the API.)
After that, you can either cross your fingers and just call getWorkspace(), which is deprecated (see JavaDoc for details).
Or you can find a specific build (e.g. the last), which can give you the workspace used for that specific build via the getWorkspace() method as it is defined in the AbstractBuild class.
Example code:
Jenkins.instance.getJob('<job-name>').lastBuild.workspace;
Just use
build.workspace
The "build" variable is available keyword in System Groovy Script.

Append content from file using Email Ext Jenkins plugin

I have been modifying the default groovy template that the Email Ext plugin supplies.
Firstly, I had to modify the JUnitTestResult and need to format it accordingly to my need. I found in the it.JUnitTestResult, it is a reference to the ScriptContentBuildWrapper class. And then I was able to format the JUnitTestResult according to my need.
Now I am facing a second difficulty:
Along with those contents, I need to append more content from a file that resides in the job workspace. How to access the files that reside in the workspace directory.
I would be interested to know how I can access the build context object. Whats the java class name and things like that.
Just use build which returns an AbstractBuild
Try -
build.workspace
Which returns the FilePath of the directory where the build is being built.
See AbstractBuild.getWorkspace.
Tip: in Groovy, you can avoid the "get" and use field-like access notation.
Depending on which version of email-ext you are using, you can use the tokens provided to get access to things, so if you look at the token help, you'll see lots of tokens. These can be used in the groovy templates to do the same thing. For instance, the FILE token can be used in the Groovy by doing FILE(path: 'path/to/file') and it will replace with the contents of the file (only works on files that are below the workspace).
The build object is not available directly in all groovy scripts (e.g. groovy build script, groovy system build script, groovy post-build script, groovy script as evaluated in email-ext). The most portable way of obtaining build object in groovy script for a running build is:
import hudson.model.*
def build = Thread.currentThread().executable
Then you can get workspace and access files inside like this:
workspace = build.getEnvVars()["WORKSPACE"]
afilename = workspace + "/myfile"
afile = new File(afilename);
// afile.write "write new file"
// afile << "append to file"
// def lines = afile.readLines()

Resources