enter image description here
Trying to fetch project name ,build number and build status for job..which are jenkins environment variables
Please see below example by which you can access the jenkins environmental variables and get the values :
println ("Job name is : ${JOB_BASE_NAME}")
println ("Job number is : ${BUILD_ID}")
println ("Build status is : ${currentBuild.currentResult}")
Related
I am into a scenario where I need to read the console output and find a specific string and set this as environment variable. This variable I would be using in input to run a different script in same job.
for example: my jenkins job's console would contain something like
build_id: 123456
Can somebody help in finding this number and pass it to input.environment variable to other script in same job?
I have looked into this answer but its not working, I am getting groovy errors while running it in post build groovy script.
Jenkins pipeline, is there a way to set environment variable from console output
Script I am using:
import jenkins.model.*
jenkins = Jenkins.instance
def consoleLog = Jenkins.getInstance().getItemByFullName(env.JOB_NAME).getBuildByNumber(Integer.parseInt(env.BUILD_NUMBER)).logFile.text
def buildId = (consoleLog =~ 'build_id="(.*)"')[0][1]
echo "build_id: $buildId"
env.build_id = buildId
Error I am getting:
ERROR: Failed to evaluate groovy script.
groovy.lang.MissingPropertyException: No such property: env for class: Script1
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:53)
at org.codehaus.groovy.runtime.callsite.PogoGetPropertySite.getProperty(PogoGetPropertySite.java:52)
After running jenkins job, in console I am facing warning message as,
"Warning: A secret was passed to "sh" using Groovy String interpolation, which is insecure"
My code looks like,
steps. withCredentials([
steps.string(
credentialsld: 'git-oauth-token-read',
variable: 'GitOauthToken'
)
})
{
steps.sh(returnStdout: false,
script:
"git remote add mainline https://xxx:${new Jobs().getToken()}#github.com/;"
)
}
Here,
new Jobs().getToken() - returns the env.GitOauthToken
I tried using different combinations of single and double quotes to the script, but I am not able to remove this warning.
Any help would be appreciated.
Thank you!
I have a Jenkinsfile where I want to declare some variables to later use in other sections. I know about Jenkins use the Groovy syntax rules for variable expansion but I expected some variable values where fully resolved. Instead I found that they just resolved in one level. Code inlcuded below shows what I want: Trying to use $PATHTOFILES variable to link data downloaded/generated in previous stages for a Docker container. Instead the variable is just resolved as pwd.
I tried several options seeking to expand the values that I need, so far unsuccessfully.
agent none
environment {
...
PATHTOFILES = "`pwd`"
...
}
...
stage('Unit'){
agent {
docker {
image "${DOCKERIMAGEURI}"
args '-v $PATHTOFILES:$CONTAINER_DATA_PATH'
}
}
}
Logs show that a value '-v `pwd`:/some/valid/path' is used as argument, leading to an error. Any ideas?
You did wrong to get current workspace of job. One of below 3 methods should work:
1) use shell cmd: pwd and pipeline step: sh() together
PATHTOFILES = sh(script: 'pwd', returnStdout:true).trim()
2) use pipeline step: pwd()
PATHTOFILES = pwd()
3) use environment variable: WORKSPACE
PATHTOFILES = env.WORKSPACE
Please help. env is null.
Jenkinsfile:
node {
println "Your ENV:"
println env.dump
println "Your params:"
println params.dump
}
Jenkins output:
[Pipeline] properties
[Pipeline] node
Running on foobarquux in c:\workspace\123abc
[Pipeline] {
[Pipeline] echo
Your ENV:
[Pipeline] echo
null
[Pipeline] echo
Your params:
[Pipeline] echo
null
I expect that my environment variables will not be null. I expect env.dump not to be null and to see something beyond Your ENV: when println env.dump executes.
After reading very helpful comments from #mkobit, I realized I needed parentheses for dump, and even with them Jenkins throws a security exception.
${WORKSPACE} only works if it is used in an agent (node)! Otherwise it comes out as null.
I have agent none at the top of my pipeline because I have a few input steps that i don't want use heavyweight executors for. And I was setting an environment variable in the top-level environment {} block that used ${WORKSPACE}. For the life of me I couldn't figure out why it was being set to null. Some other thread mentioned the workspace on an agent, so i moved that definition into a step on an agent, and lo and behold, when you set a var with WORKSPACE while running on an agent, it all works as expected.
The sidebar here is that if you are using a top-level agent none, the environment and presumably other pre-stages blocks are not running in an agent. So anything that relies on an agent will behave unexpectedly.
Groovy's optional parenthesis requires at least one parameter, which is different than Ruby.
Method calls can omit the parentheses if there is at least one parameter and there is no ambiguity:
So, to call the dump() method you would do env.dump() or params.dump(). However, this method will not be whitelisted and you will get a security exception (if you are running in the sandbox or using any sort of Jenkins security) because this would print out all fields of the object.
Thanks to StephenKing for pointing out, i check again with a new fresh Jenkins instance. see comments inside
Assuming the job has 2 parameters [str1=val1, bool1=true] :
node {
// Print the value of a job parameter named "str1"
// output: val1
println "${params.str1}"
// Calling the dump() function to print all job parameters (keys/vals)
// NOTE: calling this method should be approved by Jenkins admin
// output: .... m=[str1:val1, bool1:true] ...
println params.dump()
// Same as the above.
// output: .... m=[str1:val1, bool1:true] ...
println "${params.dump()}"
// SYNTAX ERROR, the '$' is not expected here by the parser
//println ${params.dump()};
// This appears in the question, but it seems like this is not
// what the author meant. It tries to find a param named "dump"
// which is not available
// output: null
println params.dump
}
I need to monitor what are the changes going with a job on jenkins(update the changes to a file). Need to list the env variables of a job. JOB_NAME,BUILD_NUMBER,BUILD_STATUS,GIT_URL for that build(all the builds of a job). I didn't find out a good example with the groovy. What is the best way to fetch all the info?
build.getEnvironment(listener) should get you what you need
Depending on what you would like to achieve there are at least several approaches to retrieve and save environment variables for:
current build
all past builds
Get environments variables for current build (from slave)
Execute Groovy script
// Get current environment variables and save as
// a file in $WORKSPACE.
new File(".",'env.txt').withWriter('utf-8') { writer ->
System.getenv().each { key, value ->
writer.writeLine("${key}:${value}")
}
}
Using Groovy Plug-in.
Get environment variables for current build (from master)
Execute system Groovy script
// Get current environment variables and save as
// a file in $WORKSPACE.
import hudson.FilePath
def path = "env-sys.txt"
def file = null
if (build.workspace.isRemote()) {
file = new FilePath(build.workspace.channel, build.workspace.toString() + "/" + path)
} else {
file = new FilePath(build.workspace.toString() + "/" + path)
}
def output = ""
build.getEnvironment(listener).each { key, value ->
output += "${key}:${value}\n"
}
file.write() << output
Using Groovy Plug-in.
Environment variables returned by Groovy scripts are kept in map. If you don't need all of them, you can access individual values using standard operators/methods.
Get environment variables for all past builds (from master)
This approach expecst that you have installed EnvInject Plug-in and have access to $JENKINS_HOME folder:
$ find . ${JENKINS_HOME}/jobs/[path-to-your-job] -name injectedEnvVars.txt
...
ps. I suspect that one could analyze EnvInject Plug-in API and find a way to extract this information directly from Java/Groovy code.
Using EnvInject Plug-in.
To look for only specific variables you can utilize find, grep and xargs tools .
You can use below script to get the Environment Variables
def thread = Thread.currentThread()
def build = thread.executable
// Get build parameters
def buildVariablesMap = build.buildVariables
// Get all environment variables for the build
def buildEnvVarsMap = build.envVars
String jobName = buildEnvVarsMap?.JOB_NAME // This is for JOB Name env variable.
Hope it helps!