Can not find or read the content from variables returning null from params - jenkins-pipeline

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.

Related

Create .tfvars file using Bash from Jenkins pipeline

i'm trying to create ".tfvars" file on the fly using Bash script with Jenkins parameters as arguments, here is what I did already :
Jenkins pipeline file
pipeline {
agent { label "${params.environment}_slave" }
parameters {
string(name: 'branch', defaultValue:"main")
choice(name: 'environment',choices: ['nonprod','prod'],description:'Describe where you want this pipeline to run')
booleanParam(name: 'bool', defaultValue:"false")
string(name: 'string', defaultValue:"value")
text(name: 'blabla', defaultValue:'''test\test-api\nmlflow''')
string(name: 'int', defaultValue:"1234")
}
environment {
SCM_URL = "https://my_git/my_repo"
}
stages {
stage("Test if prerequisites have been executed") {
steps {
git branch: "$params.branch" ,url: "${SCM_URL}"
sh "chmod +x -R ${env.WORKSPACE}"
sh "./script.sh \"${params}\""
}
}
}
}
Bash script :
params=$1
modified=${params:1:-1}
res=$(echo $modified | sed 's/:/=/g')
while IFS='=' read -r key value; do
array["$key"]="$value"
done <<< "$res"
for key in "${!array[#]}"; do
echo "$key=${array[$key]}" >> terraforms.tfvars;
done
printf "terraforms.tfvars ======== \n"
cat terraforms.tfvars
and when I run everything in Jenkins, here is the result :
+ chmod +x -R /home/jenkins/workspace/my_repo
[Pipeline] sh
+ ./script.sh '[environment:nonprod, bool:false, string:value, blabla:test
test-api
mlflow, branch:main, int:1234]'
terraforms.tfvars ========
0=nonprod, bool=false, string=value, blabla=test test-api mlflow, branch=main, int=1234
I don't understand why I have 0=nonprod instead of environment=nonprod
any ideas ? or suggestions about the whole thing ?
thank you very much
I had 0=nonprod because I didn't instantiate the array first :
declare -A array

Bash Script is Not Taking 2nd Argument in Jenkins Declarative Pipeline

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.

Pass environment variable to jenkins pipeline bash script

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.

Why is Jenkins pipeline returning -#tmp/durable-56090643/script.sh 4: FSUM7728 bad ${} modifier for shell command?

I have this stage in my Jenkins pipeline that runs a command and stores the output in a variable. I'm trying to get the id number from the stored string but getting the error bad ${} modifier. Should have printed 00062100. It works correctly in the console.
stage('test') {
agent {node 'test'}
steps{
sh "string=$(onetstat -a -P 1111)"
sh "echo ${string:6:8}"
}
}
output from the command("BUILD 00062100 Listen")
**Update:**
stage('server2') {
agent {node 'test'}
steps{
sh '''
var="$(onetstat -a -P 1111)"
echo ${var:6:8}
'''
}
}
**log of the run**
[Pipeline] sh
+ + onetstat -a -P 1111
+ 1<TMP> /tmp/shGgcEdAGgA
var=
BUILDER8 00069B50 Listen
Local Socket: 127.0.0.1..1111
Foreign Socket: 0.0.0.0..0
/Build#tmp/durable-a93a2921/script.sh 3: FSUM7728 bad ${} modifier
There are two misunderstandings in your example. When you use double quotes in the Jenkinsfile, you construct a Groovy String that substitutes variables (defined using $ sign) with associated values (or expressions.)
Another misunderstanding is creating a bash variable in one sh step and accessing it in another sh step. It won't work that way. Each sh step runs in its own shell process, and any local variable created in one shell cannot be accessed in another.
You can solve both issues. Firstly, you need to replace double quotes with single quotes in sh step. Secondly, you need to define shell script in a single sh step. You can use Groovy multiline string for that (triple quotes.) Consider the following example:
pipeline {
agent any
stages {
stage("Test") {
steps {
// Below code prints nothing
sh 'something="BUILD 00062100 Listen"'
sh 'echo ${something:6:8}'
// Below code prints 00062100
sh '''
something="BUILD 00062100 Listen"
echo ${something:6:8}
'''
}
}
}
}
Output:
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Test)
[Pipeline] sh
+ something='BUILD 00062100 Listen'
[Pipeline] sh
+ echo
[Pipeline] sh
+ something='BUILD 00062100 Listen'
+ echo 00062100
00062100
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
Used this solution to get the id from the command output
var=$(onetstat -a -P 1111)
var=$(echo $var | cut -b 6-10)

Jenkins build output set as current build description

I want to set current build description in my jenkins job from #bash output
Jenkins build output set as current build description
For example to set revision and branch from string and choice parameters I do it like this:
parameters {
string(defaultValue: "", description: '11.00', name: 'REVISION')
choice(name: 'BRANCH', choices: 'trunk\nupdate', description: 'Branch')
}
stage('Set build') {
steps {
script {
// Set build parameters
currentBuild.description = "$REVISION $BRANCH"
}
}
}
Let's say that I want get my diskspace % #bash execution and put it in the description...
stage('bash') {
steps {
script {
sh '''
DISK_SIZE="$(df -h --output='pcent' /mnt | grep -v "Use%")
}
currentBuild.description = "$DISK_SIZE"
}
}
I want in the build description for example to put my disk%. In this case I expect to in the description %30
Or to put some other staff that are generated from current build.
You can tell your sh command to return its stdout using the returnStdout option.
myOutput = sh(script: '$(df -h --output='pcent' /mnt | grep -v "Use%")', returnStdout: true)
currentBuild.description = myOutput

Resources