I run a very long bash script in Jenkins.
./test
At the very end of the output, I have an output like:
Updated to version 1.8
What is the best way to grab this value?
Install the Groovy Postbuild plugin. It's an old plugin, but it does the job.
You can search for strings in the console using the post stage of a the desired stage. You can use the following methods:
if ( manager.logContains('.*some_text.*') ) {
echo 'some_text found!'
}
// -- or --
def consoleLine = manager.getLogMatcher('.*some_text.*').group(0)
Related
I need to get GitVersion.exe variables in my Jenkins pipeline.
The GitVersion documentation gives a hint on how to do that. Essentially call gitversion /output buildserver.
This call does add the variables to the current step and they are lost once the step completes. I can show this call executes when combining a set command in the same bat execution. The second set shows the variables are gone from the environment.
bat 'nuget install GitVersion.CommandLine -OutputDirectory c:/packages -Version 3.6.5'
bat 'c:/packages/GitVersion.CommandLine.3.6.5/tools/GitVersion.exe /output buildserver && set'
bat 'set'
The documentation of GitVersion is aware of that and suggests to use EnvInject.
Installing the plugin and executing the same pipeline did not change the result. I read that the Plugin is not made for pipelines so that may have something to do with it.
Pipelines support a syntax for environment.
Following that syntax I can set static variables at the top of my pipeline like this:
environment {
ASuperVariable = 'MySuperVariable'
}
What I need is combining those calls so that I can add run time variables to the Jenkinsfile pupeline.
environment {
bat 'gitversion /output buildserver'
}
Now obviously the above call is not even syntax correct. Is there a way to mark a section so that the contained environment changes are available for other steps?
EDIT:
This is still unsolved. At the moment I need to create a batch script and pass the tool into it as an argument. Inside the batch I can call the tool to add to the environment of the batch script and use that wile the batch is running. A Multi line batch in the Jenkins file could be a solution if the process remains the same over all the multiple lines.
Not sure whether you would be able to use scripted pipeline or at least a script block inside declarative. It'd be quite easy doing so:
withEnv(['ASuperVariable=MySuperVariable']) {
echo env.ASuperVariable
}
Or when calling a windows cmd script:
node('win') {
withEnv(['ASuperVariable=MySuperVariable']) {
bat 'echo %ASuperVariable%'
}
}
In my build job on Jenkins via pipeline, I need show build description in build history list. how to set it in pipeline?
According to this support article, you can update the display name of a given build by running currentBuild.displayName = "7.6.2" (or whatever your version is) within a script block.
So with the use of the version number plugin, you can do something like this:
BUILD_VERSION_GENERATED = VersionNumber(
versionNumberString: '7.6.2.${BUILDS_ALL_TIME, X}',
projectStartDate: '1970-01-01',
skipFailedBuilds: true)
currentBuild.displayName = BUILD_VERSION_GENERATED
Wrap that in a script {} block in the steps section of a stage if you're using declarative pipeline and you're good to go.
Execute the script Console ($JENKINS_URL/script):
def job = Jenkins.instance.getItemByFullName("folderName/my-pipeline-job")
job.nextBuildNumber = 10
job.save()
Replace folderName/my-pipeline-job with your folder/job name with the desired next build number.
I have some groovy code which I am planning to re-use in Jenkins Groovy Post Build plugin of multiple jobs. How can I achieve this? Is there a place I can store the script in a global variable and call that in the jobs where ever I need?
You can load any groovy file living on the Jenkins master within the groovy postbuild and execute it. For example, you could have a special directory on the c drive where all the common scripts live. I'll update my answer later with some code that shows you how to load the script in.
Update
Assuming you have a test.groovy file on your C: drive, it should be as simple as the following in Groovy Postbuild:
evaluate(new File("C:\\test.groovy"))
Please view the comment section of the Groovy Postbuild for more examples and possibly other ways.
Here is the solution that worked for me:
Installed Scriptler plugin for Jenkins and saved the Groovy script in that. Now the script is available in JENKINS_HOME/scriptler/scripts directory. This way we can avoid manual step of copying files to Jenkins master.
Used the groovy file in Post build:
def env = manager.build.getEnvironment(manager.listener) evaluate(new File(env['JENKINS_HOME'] + "\\scriptler\\scripts\\GroovyForPostBuild.groovy"))
This is a copy of my answer to this similar question on StackOverflow:
If you wish to have the Groovy script in your Code Repository, and loaded onto the Build / Test Slave in the workspace, then you need to be aware that Groovy Postbuild runs on the Master.
For us, the master is a Unix Server, while the Build/Test Slaves are Windows PCs on the local network. As a result, prior to using the script, we must open a channel from the master to the Slave, and use a FilePath to the file.
The following worked for us:
// Get an Instance of the Build object, and from there
// the channel from the Master to the Workspace
build = Thread.currentThread().executable
channel = build.workspace.channel;
// Open a FilePath to the script
fp = new FilePath(channel, build.workspace.toString() + "<relative path to the script in Unix notation>")
// Some have suggested that the "Not NULL" check is redundant
// I've kept it for completeness
if(fp != null)
{
// 'Evaluate' requires a string, so read the file contents to a String
script = fp.readToString();
// Execute the script
evaluate(script);
}
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!
What's the best (or any!) way to put the output of a command in a Jenkins build name?
I'd like to put the output of the git describe command into the build name of a Jenkins job.
I've installed the build-name-setter plugin with the hopes of setting the build name to something like:
${ENV, var="GIT_DESCRIBE"}
I just don't know how to set $GIT_DESCRIBE before the name is set! I've tried using the EnvInject plugin. The only way to dynamically set the environment variables is to use groovy script. This would work well, except my job is running on a remote slave and the groovy script is (apparently) running only on the master.
If you need the "describe" data (i.e. you can't just use the existing $GIT_BRANCH or $GIT_COMMIT environment variables), you could add an "Execute shell step" with:
echo GIT_DESCRIBE=$(git describe) > git.properties
Then after that, add an EnvInject build step which injects properties from the git.properties file.
I tried following the steps outlined by Christopher Orr but my "Execute shell" script seemed to only run after the build had started. In my case GIT_DESCRIBE was never set/injected in time for the build to use it.
After some time researching I found a solution using the "Evaluated Groovy script" step as part of the Environment Injector Plugin. The Groovy script is evaluated pre-build. The main caveat there though is that the .groovy script is not run in the $WORKSPACE. What I ended up doing was executing a shell script located in my app ($WORKSPACE) from the .groovy script and returning its output as a map with GIT_DESCRIBE.
Evaluated Groovy script
def sout = new StringBuilder()
def serr = new StringBuilder()
def proc = "$WORKSPACE/git-describe.sh".execute()
proc.waitForProcessOutput(sout, serr)
def map = [GIT_DESCRIBE: sout.toString()]
return map
git-describe.sh
#! /bin/bash
# change working directory to the current script's directory
cd "${0%/*}"
echo `git describe`
From there you should be able to reference GIT_DESCRIBE in your "Build name" macro.
${ENV, var="GIT_DESCRIBE"}
With build-name-setter plugin v1.6.7 one could do the following:
"Execute shell" build step, which does git describe >version.txt
"Update build name" build step, which takes build name from version.txt.