On Jenkins Pipeline, is there a way to define a global variable as a Linux command (at *****)? As of now, I need to split one variable under node (at //*) and the other of the same name under environment (at //**). I was trying with the definitions below though they all get errors.
def SECOND_WORD=sh(script : "echo ${JENKINS_PROJECT_NAME} | cut -d'_' -f2", returnStdout: true).trim()
def SECOND_WORD=sh "echo ${JENKINS_PROJECT_NAME} | cut -d'_' -f2"
def SECOND_WORD=$(echo ${JENKINS_PROJECT_NAME} | cut -d'_' -f2)
def JENKINS_PROJECT_NAME="ABC_XYZ-123_QRS"
***** def SECOND_WORD= ??? *****
node('master') {
stage('Set agent'){
def SECOND_WORD=sh(script : "echo ${JENKINS_PROJECT_NAME} | cut -d'_' -f2", returnStdout: true).trim() //*
if (SECOND_WORD ==~ /XYZ.*/) {
AGENT_LABEL = "master"
} else {
AGENT_LABEL = "slave"
}
}
}
pipeline {
agent {
label "${AGENT_LABEL}"
}
environment {
def SECOND_WORD=sh(script : "echo ${JENKINS_PROJECT_NAME} | cut -d'_' -f2", returnStdout: true).trim() //**
}
stages {
stage('Normal build') {
steps {
echo "JENKINS_PROJECT_NAME = ${JENKINS_PROJECT_NAME}"
echo "SECOND_WORD = ${SECOND_WORD}"
echo "Running in ${AGENT_LABEL}"
sh "hostname"
}
}
}
}
Related
I have an issue where the the prompt is allowing user to pick the params value based on what is loaded into the variables. The user can select the value in the variables , but the value of the params is not returning. The echo is blank and also inside the node it is not returning the params value.
+ echo
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // dir
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
java.lang.NullPointerException: Cannot invoke method $() on null object
at org.codehaus.groovy.runtime.NullObject.invokeMethod(NullObject.java:91)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:48)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
Script:
#!/usr/bin/env groovy
stage('Connect Primary') {
node("Primary") {
script {
GET_LISTSTANDBY= sh (script: "sudo cat /pathtofile/samplestandby.txt", returnStdout: true).trim()
println "$GET_LISTSTANDBY"
}
stage('Connect Primary DB Server') {
node("nodename2") {
sh """
sudo su - postgres -c 'repmgr cluster show | grep -i "standby" | sed 's/standby.*//' | sed -r 's/^.{4}//' | cut -d "|" -f 2 | sed 's/^[[:space:]]*//' > samplestandby.txt'
samplestandby=`sudo cat /pathtofile/samplestandby.txt | sed 's/ //g'`
echo "\${samplestandby}"
sudo cp -R /pathtofile/samplestandby.txt ${env.WORKSPACE}/dir-switch
""".stripIndent()
script {
GET_samplestandby= sh (script: "sudo cat /pathtofile/samplestandby.txt", returnStdout: true).trim()
println "$GET_samplestandby"
}
}
}
stage('Prompt to select Standby') {
script {
def nodechosen = input message: 'Choose', ok: 'Next',
parameters: [choice(name: 'standbynode', choices: "${GET_LISTSTANDBY}", description: 'Select the option')]
node(nodechosen) {
echo "Running in Selected node for the choice prompt"
}
}
}
Use ${WORKSPACE} Jenkins environment variable in your getNodeNames() function instead of current directory.
Here is my script to get telnet status
#!/bin/bash
IP=$1;
PORT=$2;
exec 3> /dev/tcp/$IP/$PORT
if [ $? -eq 0 ];then echo "PortOpen";else echo "PortClosed";fi
I am calling the func in my pipeline stage
def telnetTest (namespace, release, port) {
script {
// Getting Service IP
def serviceIP = sh (
returnStdout: true,
script: "kubectl get svc -n ${namespace} | grep ${release} | awk '{print \$4}'"
)
echo "ServiceIP: ${serviceIP}"
// Checking Service IP is Exsisting ?
if (serviceIP.equals('')) {
echo "ERROR: Getting service IP failed"
sh 'exit 1'
}
// Telnet Testing
sh "chmod +x telnetPort.sh"
def telnetTesting = sh (
returnStdout: true,
script: "./telnetPort.sh ${serviceIP} ${port}"
)
echo "${telnetTesting}"
}
}
Pipeline Stage
Pipeline {
environment {
NAMESPACE = default
RELEASE = test
PORT = 9040
}
stages {
stage ('Telnet Test') {
steps {
script {
telnetTest ("${NAMESPACE}", "${RELEASE}", "${PORT}")
}
}
}
}
}
Now its taking only first arg passing to the script
Any one let me know why & where i am going wrong
In your function, you write port, and in the defining line, you wrote PORT.
Hey I'm trying to make changes to the environment variable GIT_BRANCH and parse the right side of the /, i know this can be achieved with cut like this: $(echo ${env.GIT_BRANCH} | cut -d \"/\" -f 2 )
Thing is, cannot make it work in Jenkins pipelines, error: bad substitution
pipeline {
agent any
stages {
stage('Build') {
steps {
sh "docker build -t jpq/jpq:test ."
}
}
stage('Test') {
steps {
sh "docker run jpq/jpq:test python3 tests.py"
}
}
stage('Push') {
steps {
sh '''#!/bin/bash
BRANCH=\$(echo \${env.GIT_BRANCH} | cut -d \"/\" -f 2 )
echo ${BRANCH}
docker tag jpq/jpq:test jpq/jpq:${BRANCH}
docker push jpq/jpq:test
'''
}
}
// stage('Deploy') {
// steps {
// }
// }
}
}
How can I correctly generate the BRANCH variable and pass it to the docker tag?
This should work:
stage('Push') {
steps {
sh '''#!/bin/bash
#printenv
BRANCH=$(echo ${GIT_BRANCH} | cut -d "/" -f2)
echo "Branch: ${BRANCH}"
'''
}
}
Note: To see what all environment variables are available to the shell block, you may use printenv.
I want to monitor a kubernetes pod created after redeploy task and once it is completed, I want to check the liquibase logs. If it is successful, I want to delete the job. How can I achieve this in gradle? I don't want to undeploy immediately after redeploy. So doLast is not an option. The following code doesn't keeps printing ob has not completed yet
task undeployAfterCompleted() {
group "kubernetes"
description "Undeploy the liquibase update job after completion"
def output = new ByteArrayOutputStream()
commandLine "bash", "-c", "kubectl get po -n pbr | grep 'liquibase' | awk '{ print \$3 }'"
while(!output.toString().equals('Completed')) {
sleep(5 * 1000)
println "Job has not completed yet."
commandLine "bash", "-c", "kubectl get po -n pbr | grep 'liquibase' | awk '{ print \$3 }'"
}
tasks.undeploy.execute()
}
I added a doLast block to achieve this:
doLast {
String status = getStatus()
println status.length()
while (status != "Completed") {
println "not"
sleep(5 * 1000)
if (getStatus() == "Completed") {
println "did"
break
}
}
tasks.undeploy.execute()
}
Below is my pipeline snippet and I am trying to assign RSTATE variable a value at run time. This value is basically stored in a text file but we need to grep and cut it. So a shell command output should be its value.
pipeline
{
agent any
environment
{
RSTATE = 'R4C'
ISO_REV = 'TA'
BuildSource = '18'
}
stages
{
stage('get Rstate')
{
echo env.RSTATE
}
}
}
I am trying to assign RSTATE value like:
RSTATE = sh ( script: 'grep RSTATE /proj/MM/scm/com/iv_build/mm18_1/rstate/next_rstate.txt
|cut -d "=" -f2', returnStdout: true).trim()
But this is not working.
I also tried to run a shell script but that also not works. Only hard coded value is working. Please suggest.
I tested and worksm you need to validate if your script return the value you want.
pipeline
{
agent any
environment
{
RSTATE = 'R4C'
ISO_REV = 'TA'
BuildSource = '18'
}
stages
{
stage('get Rstate')
{
steps {
script {
def RSTATE2 = sh ( script: 'echo \${RSTATE}', returnStdout: true).trim()
echo env.RSTATE
echo RSTATE2
}
}
}
}
}