Jenkins groovy : set environment variable between quote - jenkins

I am trying to set a environment variable to a http request header.
For example
""" --header 'Authorization: "${auth}"' """
But probaly due to the quote '...', the ${auth} is not correctly set.
A simple example:
job(jobName) {
wrappers {
environmentVariables {
env('auth', 'something I want to set')
}
}
steps {
shell(''' echo "${auth}" ''')
}
}
my test:
shell(''' echo "${auth}" ''') --> correctly echo
shell(''' echo '"${auth}"' ''') --> not echo correctly
shell(""" echo '"${auth}"' """) --> not echo correctly

per-character escaping: \"
~ auth="test"
~ echo "\"${auth}\""
"test"
concatenation: '"' ${auth} '"'
~ echo '"'${auth}'"'
"test"

Related

How to change global variable in Jenkins mix pipeline?

I have a script like this [ code below ]
At the end of the stage block under node I get the desired result, but inside pipeline block I am not getting the changed value, instead it is giving me null. I tried all possible ways. Please let me know is there a way to get the changed value inside pipeline block.
def AGENT_LABEL
node('k8s-agent-large-mem-oci') {
stage('Checkout and set agent'){
sh '''
if [ ! -z "`echo ${ADE_LABEL} | grep "BRONZE"`" ]
then
AGENT_LABEL="DB_OCI"
fi
if [ ! -z "`echo ${ADE_LABEL} | grep "SILVER"`" ]
then
AGENT_LABEL="DB_OCI"
fi
if [ ! -z "`echo ${ADE_LABEL} | grep "FUSIONAPPS_11.13"`" ]
then
AGENT_LABEL="DB_ARU"
fi
echo "Final Agent Label is $AGENT_LABEL"
'''
}
}
pipeline {
agent {
label "${AGENT_LABEL}"
}
stages {
stage ('Git Copy to DB VM') {
steps {
echo "Running in ${AGENT_LABEL}"
build job: 'Git_Scripts_DB'
}
}
}
}
Before giving you a pipeline example, where do you set ${ADE_LABEL}?
Try this one:
pipeline {
agent none
environment {
AGENT_LABEL = """${sh(
returnStdout: true,
script: 'if [[ ! -z $(grep -E "BRONZE|SILVER" <<< "${ADE_LABEL}") ]]
then
AGENT_LABEL="DB_OCI"
fi
if [[ ! -z $(grep -E "FUSIONAPPS_11.13" <<< "${ADE_LABEL}") ]]
then
AGENT_LABEL="DB_ARU"
fi
echo "Final Agent Label is ${AGENT_LABEL}"'
).trim()}"""
}
stages {
stage ('Git Copy to DB VM') {
agent {
label "${AGENT_LABEL}"
}
steps {
echo "Running in ${AGENT_LABEL}"
build job: 'Git_Scripts_DB'
}
}
}
}

How to pass variable between jenkins pipeline from shell script conditional result

in the first stage, i've shell script to check directory in the remote server and the results will be sent to the next stage. I have tried the following way but it seems the variable is not read in the execute stage, is there another proper way?
pipeline {
agent any
stages
{
stage("validate")
{
steps
{
sh '''
dir_path="/home/servicenamedir"
ssh username#host bash -c "'
if [ -d "$dir" ]
then
checkdir="true"
else
checkdir="false"
fi
'"
'''
}
}
stage("execute")
{
steps
{
sh '''
if [ "$checkdir" == "true" ]
then
echo "directory already exist, please double check";
exit;
elif [ "$checkdir" == "false" ]
then
echo "execute ./install-service.sh"
fi
'''
}
}
}
create variable
def var
use options returnStdout: true. And parse output
Def var = sh ( script " ls -la", returnStdout: true).split("\n")
use var in stage 'execute'
If (var[0] =="true"){...} else {...}
https://www.jenkins.io/doc/pipeline/steps/workflow-durable-task-step/

Passing minion list to Jenkins pipeline, Error: workflowScript: 15: illegal string body character after dollar sign;

Below is the Jenkins pipeline. which runs a state against the list of minions stored in a .txt file on the salt master server. The below command runs fine on the salt master cli:
salt --list `awk -vORS=, '{ print $1 }' /srv/salt/TMjenkins/minions.txt | sed 's/,$/\n/'` test.ping
However, when I run it through the Jenkins pipeline, I get illegal string body character after dollar sign. The salt master is in a remote server, hence I can't execute the cmd natively.
so, far i have tried with passing the cmd in """ """ and ''' ''', also { print \"${1}\" }. Nothing has worked so far. Any suggestion, appreciated.
pipeline = {
ansiColor('xterm') {
def remote = [:]
remote.name = 'saltmaster'
remote.host = 'xx.xxx.xx.x'
remote.allowAnyHosts = true
withCredentials([usernamePassword(credentialsId: 'saltmaster', passwordVariable: 'password', usernameVariable: 'ops')]) {
remote.user = 'xxx'
remote.password = password
stage('Filetransfer') {
sshCommand remote: remote, command: " salt -L `awk -vORS=, '{ print \"${1}\" }' /srv/salt/TMjenkins/minions.txt | sed 's/,$/\n/'` test.ping "
}
}
sh '/home/jenkins/jenkins-data/slack_notification.sh " ${minionid}" "Deployment finished successfully" "good" ":jenkins:"'
}
}
postFailure = {
sh '/home/jenkins/jenkins-data/slack_notification.sh " ${minionid}" "Unfortunately deployment was unsuccessful this time" "danger" ":jenkinserror:"'
}
postAlways = {
echo 'Cleaning Workspace now'
env.WORKSPACE = pwd()
sh "rm ${env.WORKSPACE}/* -fr"
}
node{
properties([
parameters([
string(name: 'Region', defaultValue: '', description: 'Region for which the process should run. ')
])
])
try {
pipeline()
} catch (e) {
postFailure()
throw e
} finally {
postAlways()
}
}
You need to escape your $ sign if you want to pass it over. So:
awk -vORS=, '{ print $1 }' /srv/salt/TMjenkins/minions.txt
becomes
sh "awk -vORS=, '{ print \$1 }' /srv/salt/TMjenkins/minions.txt "
and
sed 's/,$/\n/'
becomes
sh "sed 's/,\$/\n/'"
Finally, instead of using bash scripts to send Slack notifications, you should use Slack plugin for Jenkins, like this:
slackSend color: "danger", text: "Failed"
See also

Error while executing 'curl' inside jenkins groovy

I'm trying to use Groovy and curl to create a ServiceNow change ticket using their REST API. I get the below error every time I run the Jenkins pipeline
{"error":{"message":"Exception while reading request","detail":"Cannot decode: java.io.StringReader#90e4d8"},"status":"failure"}
What am I doing wrong here?
Jenkins version 2.150.2
{
node(){
stage ('Create Change Request') {
echo("Creating Change Request")
sh(script: """curl ${SERVICENOW_URL}/table/change_request \
--request POST \
--header 'Accept:application/json' \
--header 'Content-Type:application/json' \
--data '{"requested_by": "${params.requested_by}",
"u_verifier":"${params.u_verifier}",
"assigned_to":"${params.assigned_to}",
"reason":"${params.reason}",
"type":"${params.type}",
"start_date":"${params.start_date}",
"end_date":"${params.end_date}",
"change_plan":"${params.change_plan}",
"short_description":"${SHORT_DESCRIPTION}",
"description":"${DESCRIPTION}",
"backout_plan":"${BACKOUT_PLAN}",
"u_verification_plan":"${U_VERIFICATION_PLAN}",
"u_department_subsidiary":"${U_DEPARTMENT_SUBSIDIARY}",
"u_tested":"${U_TESTED}",
"u_have_verification_plan":"${U_HAVE_VERIFICATION_PLAN}",
"u_have_implementation_plan":"${U_HAVE_IMPLEMENTATION_PLAN}",
"u_have_backout_plan":"${U_HAVE_BACKOUT_PLAN}",
"assignment_group":"${U_ASSIGNMENT_GROUP}",
"category":"${CATEGORY}",
"cmdb_ci":"${CMDB_CI}",
"u_approval_group":"${U_APPROVAL_GROUP}",
"approval":"requested",
"state":"${_STATE}"
}' \
--user 'xxxx':'password' > CREATE_CHG_REQUEST_OUTPUT
""")
}
stage ('Parsing Change Result') {
def REQUEST_OUTPUT = ""
REQUEST_OUTPUT = readFile ('CREATE_CHG_REQUEST_OUTPUT').trim()
//var jsonStr = JSON.stringify(REQUEST_OUTPUT);
echo "REQUEST_OUTPUT:"
echo REQUEST_OUTPUT
def jsonSlurper = new JsonSlurper()
def object = jsonSlurper.parseText(REQUEST_OUTPUT)
NEW_CHANGE_NUMBER = object.result.number
NEW_SYS_ID = object.result.sys_id
echo("New Change Number is : " + NEW_CHANGE_NUMBER )
echo("New sys_id for Change Number : " + NEW_SYS_ID )
}
}
} catch(e) {
echo e.message
} finally {
}
The data has certain variables declared using . in the variable name. Groovy doesn't support the replacement of the variables declared inside the double quotes "". Replace all the variable names having . in them with single quotes ''.
Hope so this helps

Jenkinsfile copy variable to file

I am trying to copy the contents of a variable into a file as part of my pipeline build, I am unable to access the variable it seems
This example will work
stage('Copy Var') {
sh 'echo "This is my string" >> /path/to/file'
string = sh(script: 'cat /path/to/file', returnStdout: true)
echo "string is ${string}"
}
// outputs: "string is This is my string"
However as soon as i start to use a variable then i get nothing returned
string = sh(script: 'cat /path/to/test.txt', returnStdout: true)
stage('Copy Var') {
sh 'echo "${string}" >> /path/to/file'
echo "${string}"
// outputs: test txt
copy_string = sh(script: 'cat /path/to/file', returnStdout: true)
echo "string is ${copy_string}"
}
// outputs string is
Is there something i am missing here?
Thanks
Yes, you are missing the readFile step:
copy_string = readFile('/path/to/file')

Resources