Jenkinsfile copy variable to file - jenkins

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')

Related

Jenkins script how to compare two string variables

def pname = "netstat -ntlp|grep 8080|awk '{printf \$7}'|cut -d/ -f2"
sh "echo $pname" \ java
if ("java".equals(pname)) { sh "echo 1111" }
The process corresponding to port 8080 is a java process, and the 2nd line print "java". But the body of the if statement just doesn't execute.
You seem to be not executing the command correctly. Please refer to the following sample. Please note the returnStdout: true to return output of the command.
pipeline {
agent any
stages {
stage('Test') {
steps {
script {
def pname = sh(returnStdout: true, script: "netstat -ntlp|grep 8080|awk '{printf \$7}'|cut -d/ -f2").trim()
if (pname == "java") {
echo "echo 1111"
}
}
}
}
}
}
try
"==" for equal
or you can read doc.
https://groovy-lang.org/operators.html#_relational_operators

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/

How to use Jenkins Pipeline global variable on another stages?

I have defined global variable in Jenkins pipeline
def BUILDNRO = '0'
pipeline { ...
Then i manipulate variable with shell script to enable running builds parallel by using job build number as identifier so we don't mix different docker swarms.
stage('Handle BUILD_NUMBER') {
steps {
script {
BUILDNRO = sh( script: '''#!/bin/bash
Build=`echo ${BUILD_NUMBER} | grep -o '..$'`
# Check if BUILD first character is 0
if [[ $Build:0:1 == "0" ]]; then
# replace BUILD first character from 0 to 5
Build=`echo $Build | sed s/./5/1`
fi
echo $Build
''',returnStdout: true).trim()
}
}
}
i get value out from previos stage and trying to get global variable on next stage
stage('DOCKER: Init docker swarm') {
steps {
echo "BUILDNRO is: ${BUILDNRO}" --> Value is here.
sh '''#!/bin/bash
echo Buildnro is: ${BUILDNRO} --> This is empty.
...
}
}
This will out give global variable empty. why? in previous stage there was value in it.
EDIT 1.
Modified code blocks to reflect current status.
I managed to figure it out. Here is solution how i managed to did it.
BUILDNRO is groovy variable and if wanting to used in bash variable it have to pass using withEnv. BUILD_NUMBER in first stage is bash variable hence it can be used directly script in first stage.
def BUILDNRO = '0'
pipeline {
....
stages {
stage('Handle BUILD_NUMBER') {
steps {
script {
BUILDNRO = sh( script: '''#!/bin/bash
Build=`echo ${BUILD_NUMBER} | grep -o '..$'`
''',returnStdout: true).trim()
}
}
}
stage('DOCKER: Init docker swarm') {
steps {
dir("prose_env/prose_api_dev_env") {
withEnv(["MYNRO=${BUILDNRO}"]) {
sh(returnStdout: false, script: '''#!/bin/bash
echo Buildnro is: ${MYNRO}`
'''.stripIndent())
}
}
}
}
}
}
If you are using single quotes(```) in the shell module, Jenkins treats every variable as a bash variable. The solution is using double quotes(""") but then if you made bash variable you have to escape it. Below an example with working your use case and escaped bash variable
pipeline {
agent any
stages {
stage('Handle BUILD_NUMBER') {
steps {
script {
BUILDNRO = sh(script: 'pwd', returnStdout: true).trim()
echo "BUILDNRO is: ${BUILDNRO}"
}
}
}
stage('DOCKER: Init docker swarm') {
steps {
sh """#!/bin/bash
echo Buildnro is: ${BUILDNRO}
variable=world
echo "hello \${variable}"
sh """
}
}
}
}
output of the second stage:
Buildnro is: /var/lib/jenkins/workspace/stack1
hello world

How to use global variable in If condition in a Jenkinsfile?

I am new to Jenkins and am confused between variables. I have tried to write a Jenkinsfile where I am simply using an If condition to deploy a file. Following is the file:
def checker = "Trial"
pipeline{
agent any
stages{
stage('Stage 1'){
steps{
script{
checker = sh(returnStdout: true, script: 'echo "Trial" ')
if (checker == 'Trial'){ echo "Hello"}
else {echo "Hi"}
}
}
}
}
}
The output should ideally be "Hello", however I get "Hi" always. How do I get the If condition working?? Thanks
You missed the trim() to remove the newline at the end of output of the bash.
checker = sh(returnStdout: true, script: 'echo "Trial" ').trim()

when use jenkins pipeline shared library ,the function parameters in sh ''' ''' will be null

/var/coverityCompile.groovy
#!groovy
def java(String DIR) {
compile_dir="${WORKSPACE}/${DIR}"
echo "complie_dir:${compile_dir}"
sh "echo complie_dir:${compile_dir}"
sh '''
echo complie_dir:${compile_dir}
'''
}
/src/org/coverity/JenkinsFile
#!groovy
#Library('shared-library') _
pipeline {
agent { label 'dev_ci_env_dm' }
stages {
stage('coverity'){
steps{
script{
coverityCompile.java("DM")
}
}
}
}
}
The Jenkins log will be:
complie_dir:/home/ci/workspace/test_coverity/DM
[Pipeline] sh
[test_coverity] Running shell script
+ echo complie_dir:/home/ci/workspace/test_coverity/DM
complie_dir:/home/ci/workspace/test_coverity/DM
complie_dir:
when I use echo "complie_dir:${compile_dir}"
and sh "echo complie_dir:${compile_dir}"
the result will be printed as expected. But, when I use
sh '''
echo complie_dir:${compile_dir}
'''
The result of ${compile_dir} will be null.
Now, I want to execute multiline of shell,so is there any other way to replace sh ''' '''?

Resources