buildResults variable isn't accessible from outside of catchError block. Any idea how I can access it? build job might get aborted so I want the rest of the script block to continue but I get the error groovy.lang.MissingPropertyException: No such property: buildResults for class: groovy.lang.Binding
catchError {
buildResults = build job: 'Test', parameters: [string(name: 'BRANCH', value:'main')], wait: true
}
sh """ curl -u 123:123 -X POST \
-H "Content-Type: application/json" \
--url 'http://10.10.10.10:8080/rest/api/2/issue/${env.TASK_KEY}/comment' \
-d '{ "body": "[Test] Full Pipeline result is: ${buildResults.getResult()}"}'
"""
If you downstream job will be aborted, the build function will threw an exception, which means the buildResults parameter will not be set and you will get the MissingPropertyException error.
To overcome it you can define the buildResults parameter with a default value, prior to calling the build function, which will make it available regardless of the build function execution:
def buildResults = ''
catchError {
buildResults = build job: 'Test', parameters: [string(name: 'BRANCH', value:'main')], wait: true
}
In addition you will have to update the usage of the build result as it may not contain a result object if the downstream was aborted, and in that case buildResults.getResult() will fail.
You can use something like to solve it:
def buildResults = ''
catchError {
buildResults = build job: 'Test', parameters: [string(name: 'BRANCH', value:'main')], wait: true
}
def results = buildResults ? buildResults.getResult() : "Downstream job did not return results"
sh """curl -u 123:123 -X POST \
-H "Content-Type: application/json" \
--url 'http://10.10.10.10:8080/rest/api/2/issue/${env.TASK_KEY}/comment' \
-d '{ "body": "[Test] Full Pipeline result is: ${results}"}'
"""
Related
I want to be able to call the parameters value from the shell and use it in my shell script. My priority is to not use If for every value selected in the params, but rather it choose the active choice. Is it possible as am having issue with this error?
line 4: ${params.prime_server}: bad substitution
#!/usr/bin/env groovy
properties([
parameters([
choice(
name: 'prime_server',
choices: ['','choice1', 'choice2', 'choice3','choice4'],
description: 'Name choice'
),
choice(
name: 'old_server',
choices: ['','choice1', 'choice2', 'choice3','choice4'],
description: 'Name choice'
)
])
])
stage('stage1') {
environment{
}
node("master") {
sh '''
echo -e "-------------------------------Calling the params value into shell----------------------------"
echo "${params.prime_server}"
echo "${params.old_server}"
oldserver="${params.old_server}"
primeserver="${params.prime_server}"
echo "${oldserver}"
echo "${primeserver}"
sed -i -e "0,/${oldserver}/ s/${oldserver}/${primeserver}/g" test.xml
'''.stripIndent()
}
}
Is there anyway to call this param value and assign it to variables in shell
Shell block with single quotes does not take variables into consideration, so double quotes must be used.
Example:
sh """
<your code>
"""
You should be using double quotes if you want Groovy to do string interpolation. So change your shell block like below.
sh """
echo -e "-------------------------------Calling the params value into shell----------------------------"
echo "${params.prime_server}"
echo "${params.old_server}"
oldserver="${params.old_server}"
primeserver="${params.prime_server}"
echo "\${oldserver}"
echo "\${primeserver}"
sed -i -e "0,/${oldserver}/ s/${oldserver}/${primeserver}/g" test.xml
""".stripIndent()
I call createItem in a function, from a loop derived from the list of git's currentBuild.changeSets
Here is the function:
def boolean shCreateJob(jobName) {
jobName = jobName.toString()
command = "curl -s -XPOST '$JENKINS_URL/createItem?name=$jobName' -u user:secret --data-binary ${TEMPLATE_FILE} -H 'Content-Type:text/xml'"
command = command.toString()
println("In shCreateJob, command=$command")
println("In shCreateJob, command.getClass()=${command.getClass()}")
try {
sh "curl $command"
}
catch (err) {
echo 'Exception during job creation : ' + err
}
return true
}
As you can see, in the function, I'm trying to cast the name and the command to String to ensure the sh command doesn't get anything exotic.
Here is the output:
In shCreateJob, command=curl -s -XPOST 'http://10.128.128.168:8080//createItem?name=cz_AAA' -u user:secret --data-binary #//var/lib/jenkins/jobs/_upload_template/config.xml -H 'Content-Type:text/xml'
[Pipeline] echo
In shCreateJob, command.getClass()=class java.lang.String
[Pipeline] sh
[Pipeline] echo
Exception during job creation : java.io.NotSerializableException: java.util.LinkedHashMap$Entry
And yet, the job ends in success, and also the new job is created as expected!
What's the deal?
My Jenkins pipeline is as follows
pipeline{
agent any
stages{
stage{
script{
res1=sh(returnStdout:true, script: 'curl -o /dev/null -sf -w "%{http_code}" http://xyz1.jsp').replace(' ','').toInteger()
echo "${res1}"
res2=sh(returnStdout:true, script: 'curl -o /dev/null -s -w "%{http_code}" http://xyz2.jsp').replace(' ','').toInteger()
echo "${res2}"
}
}
}
}
When 1st curl request returns a status code of 000, script is returning exit code 7 and build is failing. But I want the 2nd curl request also to run and then fail?
I have the following Jenkinsfile
def ARTIFACTS_JOB_ID;
def ARTIFACTS_URL;
node('CentOs') {
checkout scm
stage('Example') {
echo 'Download artifacts'
sh 'curljson --header "PRIVATE-TOKEN: tdzis3" "https://gitlab-sample.com/api/v4/projects/63/jobs" > jobs.json'
ARTIFACTS_JOB_ID = sh(returnStdout: true, script: 'python GetID.py').trim()
ARTIFACTS_URL = "https://gitlab-sample.com/api/v4/projects/63/jobs/${ARTIFACTS_JOB_ID}/artifacts"
echo "======> $ARTIFACTS_URL"
sh 'echo $ARTIFACTS_URL'
sh 'curl --output artifacts.zip --header "PRIVATE-TOKEN: tdzis3" "$ARTIFACTS_URL"'
}
}
while trying to get the artifact, it's calling
'curl --output artifacts.zip --header "PRIVATE-TOKEN: tdzis3" ""' with empty url
Similarly
echo "======> $ARTIFACTS_URL" //works fine
sh 'echo $ARTIFACTS_URL' // shows empty string, tried with ${ARTIFACTS_URL} aswell.
is there a way I can run it as below (so I don't have to use sh)
def ARTIFACTS_JOB_ID;
def ARTIFACTS_URL;
node('CentOs') {
checkout scm
stage('Example') {
script {
echo 'Download artifacts'
curljson --header "PRIVATE-TOKEN: tdzis3" "https://gitlab-sample.com/api/v4/projects/63/jobs" > jobs.json
}
}
}
without sh I am getting invalid syntax error while doing
curljson --header
The variable declaration ARTIFACTS_URL = "https://..." is a Groovy global variable. Hence, it is not naturally available to the sh step as a shell variable.
You need to wrap the commands inside the sh step with double quotes instead of single quotes as sh "echo $ARTIFACTS_URL" for Groovy to interpolate it as a Groovy variable.
Have you tried
sh "curl --output artifacts.zip --header 'PRIVATE-TOKEN: tdzis3' '{$ARTIFACTS_URL}'"
?
for multiple sh commands you could also use
sh """
curl command here
cd command next
etc
"""
I have written a jenkins scripted pipeline which has 3 stages in it. And in each stage i am calling a curl command to start a jenkins job which is on my remote server. But, the problem is 2nd stage is getting executed before 1st stage completes its execution.
Please help me how to resolve this?
node{
properties([
disableConcurrentBuilds()
])
stage('stage1'){
sh 'curl -X POST -H "Content-Type: application/json" -d "{ "tagname": "$tagname" }" -vs http://pkg.rtbrick.com:8080/generic-webhook-trigger/invoke?token=qwerty'
}
stage('stage2'){
sh 'curl -X POST -H "Content-Type: application/json" -d "{ "tagname": "$tagname" }" -vs http://image.rtbrick.com:8080/generic-webhook-trigger/invoke?token=1234'
}
stage('stage3'){
sh 'curl -X POST -H "Content-Type: application/json" -d "{ "tagname": "$tagname" }" -vs http://image.rtbrick.com:8080/generic-webhook-trigger/invoke?token=1804'}
}
}
"Stage2" should start only if "stage1" is completed.
It's doable using the Jenkins REST API and the waitUntil step in combination with timeout (without a timeout it could hang forever):
def response
timeout(30) {
waitUntil {
response = sh(
script: 'curl http://pkg.rtbrick.com:8080/view/job/my-job/lastBuild/api/json | grep "\"result\":\"SUCCESS\""',
returnStatus: true
)
return (response == 0)
}
}
if (response != 0) {
build.result = 'ERROR'
}