I have written a Jenkins Pipeline but it's failing on the following step:-
script {
attachments="<a href='https://xxxxx.xxxxx.net/wiki/pages/viewpageattachments.action?pageId=${idValue}'>ATTACHMENTS</a>"
echo '=========================URL===================' + attachments
echo '{"id":"'${idValue}'","type":"page","title":"'${releaseVersion}'","space":{"key":"~xxxxxx"},"body":{"storage":{"value":"'${attachments}'","representation":"storage"}},"version":{"number":"2"}}' > update1.json
//content = sh(script: "curl -u 'xxxxxxx#xxxxxx.xxx:xxxxxxxx' -X PUT -H 'Content-Type: application/json' -d '#update1.json' https://xxxxxx.xxxxxx.xxxxx/wiki/rest/api/content/${idValue}", returnStdout: true)
//rm update1.json
}
It gives the following error
WorkflowScript: 37: expecting '}', found '","representation":"storage"}},"version":{"number":"2"}}' # line 37, column 164.
2021-11-02 18:40:23.964 age":{"value":"'${attachments}'","repres
Try this way:
def my_json = """
{
"id":"${idValue}",
"type":"page",
"title":"${releaseVersion}",
"space": {
"key":"~xxxxxx"
},
"body":{
"storage":{
"value":"${attachments}",
"representation":"storage"
}
},
"version":{
"number":"2"
}
}
"""
echo "${my_json}" > update1.json
Related
Please check what to write for just update password change not replace file kindly check.
Not all passwords change every time so it should only change passwords which are different
2)password file should be provided along with email
That's here I am stuck that how it is possible to do that because every time I run this it gets back with replacing the passwords file. It should have to update the changes just.
def json = 'initial_value'
def token = 'initial_value'
def count = 0
def csvContent = 'initial_value'
def ocpUrl ="https://api.nonprod.ocp.dev.ppr.gvv:6443"
def ocpRegistry="registry.apps.nonprod.ocp.dev.ppr.gvv"
pipeline {
agent any
environment {
VAULT_ADDR = credentials('VAULT_ADDR')
ROLE_ID = credentials('ROLE_ID')
SECRET_ID = credentials('SECRET_ID')
}
stages {
stage('Upload parameters and FILE') {
steps {
script {
//Load the csv file
def inputCSVPath = input message: 'Upload file', parameters: [file(name: 'Credentials.csv', description: 'Upload only CSV file')]
csvContent = readFile "${inputCSVPath}"
//Delete csv file
sh(""" rm -rf "$inputCSVPath" """)
json = '{"data":{'
csvContent.split('\n').each { line ->
if (count > 0) {
def fields = line.split(',',2)
def key = fields[0]
def pass = fields[1]
key = key.replaceAll(' ', '')
key=key.replaceAll('"', '')
pass=pass.replaceAll('"', '')
def item_data = '"'+key.trim()+'":"'+pass.trim()+'",'
json += item_data
}
count += 1
enter code here
}
count -= 1
json = json.substring(0, json.length() - 1)
json += '},"options":{}}'
//println(json)
//delete file
}
}
}
stage('Validate file'){
steps{
script {
csvContent = csvContent.trim()
csvContent = csvContent.replaceAll("\\S","")
println csvContent.length()
if(csvContent.equals("")){
currentBuild.result = "FAILURE"
echo "error"
exit o
}
}
}
}
stage('Authentication into vault'){
when {
expression { currentBuild.result != "FAILURE" }
}
steps{
script {
//Authentication Method
def response = sh(script: """curl --insecure -X PUT -H "X-Vault-Request: true" -d '{"role_id":"${ROLE_ID}","secret_id":"${SECRET_ID}"}' ${VAULT_ADDR}/v1/auth/approle/login""", returnStdout: true)
def responseObject = readJSON text: response
token = "$responseObject.auth.client_token"
}
}
}
stage('Update secrets into vault'){
when {
expression { currentBuild.result != "FAILURE" }
}
steps{
script{
// Updating the secret into vault
sh """
set +x
curl --insecure -X PUT -H "X-Vault-Request: true" -H "X-Vault-Token: "${token}"" -d '${json}' ${VAULT_ADDR}/v1/dev/data/db
set -x
"""
}
}
}
stage('Openshift delete Pods') {
steps{
withCredentials([usernamePassword(credentialsId: 'ocp-dev', usernameVariable: 'OCP_CREDS_USR', passwordVariable: 'OCP_CREDS_PSW')]) {
sh """
/usr/local/bin/oc login --insecure-skip-tls-verify -u '${OCP_CREDS_USR}' -p '${OCP_CREDS_PSW}' ${ocpUrl}
sudo docker login -u system -p \$(/usr/local/bin/oc whoami -t) ${ocpRegistry}
/usr/local/bin/oc delete --all pods --namespace md-dev
"""
}
}
}
}
post{
success{
emailext to: "${email}",
subject: "Jenkins Result",
body: "Password updated successfully",
attachLog: true
}
failure{
emailext to: "${email}",
subject: "Jenkins Result",
body: "Password updated failed with the error",
attachLog: true
}
}
}
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
I have following Jenkinsfile which will grep for a string from URL, it will send a notification to Slack depends upon the output.
stage('Check if present') {
steps {
script{
sh """
if curl -s http://example.foo.com:9000 | grep -q "ERROR"
then
slackSend channel: '#team', message: "Pipeline has been failed due to due to an error, please investigate:${env.BUILD_URL} : http://example.foo.com:9000", teamDomain: 'example', tokenCredentialId: 'foo'
echo "Scan result: ERROR" && exit 1
elif curl -s http://example.foo.com:9000 | grep -q "WARN"
then
slackSend channel: '#team', message: "Pipeline is in WARN state due to a warning, please investigate:${env.BUILD_URL} : http://example.foo.com:9000", teamDomain: 'example', tokenCredentialId: 'foo'
fi"""
}
}
}
Absolutely the slackSend notification won't work, as it is a plugin.
I am looking for ways to do the same in Groovy so that I can implement slackNotification.
I tried the following logic in Groovy, as an example.
But it didn't work, as even if the line is not present is is printing line is found.
stage('test logic'){
steps{
script{
if ('curl -s http://example.foo.com:9000'.execute() | 'grep foo'.execute())
println("The line is found")
else {
println("The line is not found")
exit 1
}
}
}}
You can just use Groovy's (to be more accurate Java's) .contains(String) method to check if some string contains other string. Also when you execute command in pipeline you can capture stdout of that command.
Code:
stage('test logic'){
steps{
script{
def commandStdout = sh(returnStdout: true, script: "curl -s http://example.foo.com:9000"
if (commandStdout.contains("foo")) {
println("The line is found")
}else {
println("The line is not found")
exit 1
}
}
}
}
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
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"