How to set the output of sh to a Groovy variable? [duplicate] - jenkins

This question already has answers here:
Is it possible to capture the stdout from the sh DSL command in the pipeline
(7 answers)
Closed 6 years ago.
Is it possible to have the output of the sh command be set to a Groovy variable? It seems to be setting it to the status of the command instead.
Example input:
node {
stage "Current Date"
def curDate = sh "date"
echo "The current date is ${curDate}"
}
Results in the following output:
Entering stage Current Date
Proceeding
[Pipeline] sh
[workspace] Running shell script
+ date
Tue May 10 01:15:05 UTC 2016
[Pipeline] echo
The current date is 0
It is showing The current date is 0, I want it to show The current date is Tue May 10 01:15:05 UTC 2016 which you can see has been output by the sh command. Am I going about this all wrong?

Yes, sh is returning the exit status. Currently your best bet is:
sh 'date > outFile'
curDate = readFile 'outFile'
echo "The current date is ${curDate}"
ADDENDUM: after this answer was written a new option was added to the sh step, use returnStdout: true to get the result string from the sh call.

Related

SYSDATE with TimeStamp Format need to include in Jenkins Build

Anyone know how to get SYSDATE while running Jenkins build, it should be in this format: 24Aug20221005 (sysdatewithtimestamp)
please let me know.
Thanks,
Harish.
You can use the command date +%d%b%Y%H%M to get a date like 25Aug20221431
If you want to change the date you can simply look this up yourself with date --help.
You can get this in the Jenkinsfile as a environment variable like this:
env.MY_DATE = sh(
script: """
date +%d%b%Y%H%M
""", returnStdout: true
)
or in a bash script like this:
sh '''
MY_DATE=$(date +%d%b%Y%H%M)
echo $MY_DATE
'''

Jenkins - Writing variable to log file

Running my jenkins pipeline I am able to have it output the commit message correctly using
gitnotes = sh ("git log -1 --pretty=%h%x09%an%x09%ad%x09%s")
8c65c33 NAME HERE Tue Nov 13 16:30:00 2018 -0500 Adjusted search/reset buttons' size in dashboard panel
However I now want to store those commit notes to a log file, but even when I use an echo it comes back as null.
echo "${gitnotes}"
I might be losing my mind, but how would I go about writing the above notes to a log file? I'm having a super bad day apparently as this is something I am just not looking at correctly.
Try setting returnStdout: true
Eg: gitnotes = sh script: "git log -1 --pretty=%h%x09%an%x09%ad%x09%s" , returnStdout: true

Can we define a variable inside a Jenkins parameterized build

My scenario is, I have parameterized build and inside the build section, I have executed shell where I define a variable and then echo to print it. But it doesn't print anything in the console output.
I hope I have made myself clear. Could anyone please answer my question?
current_folder=`date +%Y%m%d-%H%M%S`
echo $current_folder
enter image description here
I'm using Jenkins ver. 2.32.3 and a simple freestyle job, running on mac OS, using an execute shell build step of:
current_folder=`date +%Y%m%d-%H%M%S`
echo $current_folder
Gives output of:
$ /bin/sh -xe /var/folders/kh/4fl0eeldofefmmsfd/T/hudson89388543547899686.sh
++ date +%Y%m%d-%H%M%S
+ current_folder=20180613-081712
+ echo 20180613-081712
20180613-081712
Finished: SUCCESS
In a similar fashion, setting the shell:
#!/bin/bash
current_folder=`date +%Y%m%d-%H%M%S`
echo $current_folder
Gives:
$ /bin/bash /var/folders/kh/by0kd93dfew5fgjhy000h6/T/hudson62702345565786787.sh
20180613-081655
Finished: SUCCESS
The same applies to a parameter that is defined as part of the Jenkins job, underneath the
This project is parameterized checkbox once set. For example, if you have a string parameter called userName with a default value of User1, then you can print it's value in an Execute Shell build step using:
echo $userName
echo ${userName}
echo "In a string ${userName}"
Giving:
User1
User1
In a string User1

Jenkins2.0 pipeline script reject date arithmetic

I have the following code in groovy Jenkinsfile:
def current = new SimpleDateFormat('yyyy-MM-dd HH:mm:ss.SSSZ').parse(currenttime.trim())
println current
def end_date = new SimpleDateFormat('yyyy-MM-dd HH:mm:ss.SSSZ').parse(scheduled_end_date.trim())
println end_date
schedule_grace_period_validity = current - end_date > 5 ? false : true
the output for this is :
Tue Feb 27 13:20:54 EST 2018
[Pipeline] echo
Mon Dec 18 18:00:00 EST 2017
[Pipeline] echo
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use staticMethod org.codehaus.groovy.runtime.DateGroovyMethods minus java.util.Date java.util.Date
This works just fine in my local box but in sandbox mode in Jenkins, this fails and I can't turn off the sandbox mode in Jenkins.
IS there any workaround for this ?
The simplest way is to go to /scriptApproval/ page in your Jenkins instance and approve the signature. When you get this exception after running your script you will see something like this in the script approval page:
Just click Approve and run your script again.
Alternatively you could try calculating difference between two dates in days as:
int diff = BigDecimal.valueOf((current.time - end_date.time) / 86400000).setScale(0, java.math.RoundingMode.UP).intValue()
but in this case you may also run into RejectedAccessException. I tried to run it in Groovy sandbox in my local Jenkins instance and I got this:
[Pipeline] End of Pipeline
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use method java.util.Date getTime
at org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.StaticWhitelist.rejectMethod(StaticWhitelist.java:175)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor$6.reject(SandboxInterceptor.java:261)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:381)
at org.kohsuke.groovy.sandbox.impl.Checker$6.call(Checker.java:284)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checke

How to export a variable from sh to groovy in a jenkins pipeline?

How is it possible to export a variable from the sh context of sh context to the groovy context of the jenkins pipline job?
Pipeline Code:
node {
echo 'Hello World'
sh 'export VERSION="v$(date)"'
echo env.VERSION
}
outupt:
[Pipeline] sh
[test-pipeline] Running shell script
++ date
+ export 'VERSION=vThu Dec 1 12:14:40 CET 2016'
+ VERSION='vThu Dec 1 12:14:40 CET 2016'
[Pipeline] echo`enter code here`
null
i am using Jenkins ver. 2.34
update:
there is the possibility to write the variable to a temporary file and read it later. This looks totally like a hack to me. It is not "thread-safe" by default when using parallel builds and does not scale if you need to export multiple variable in one run. Is there a proper way to do this?
I hope this will help.
node('master'){
stage('stage1'){
def commit = sh (returnStdout: true, script: '''echo hi
echo bye | grep -o "e"
date
echo lol''').split()
echo "${commit[-1]} "
}
}

Resources