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
Related
I'm using the below code to trigger a remote job in a a jenkins pipeline. After the job is trigger, I'd need to parse the logs and retrieve few information. The below code used handle.lastLog() function, but its returning null. Is there a way to get the logs from triggerRemoteJob ?
def handle = triggerRemoteJob (
auth: TokenAuth(apiToken:....'),...,
job: build_job,
parameters: parameters1,
useCrumbCache: true,
useJobInfoCache: true,
overrideTrustAllCertificates: false,
trustAllCertificates: true
)
def status = handle.getBuildStatus()
echo "--------------------------------------------------------------------------------"
echo "Log: " + handle.lastLog()
echo "--------------------------------------------------------------------------------"
You have many ways to parse the remote job console log by saving the output to a file as follows:
One way is to use the handle object to get the remote build URL:
def remoteBuildOutput = handle.getBuildUrl().toString()+"consoleText"
sh "curl -o remote_build_output.txt ${remoteBuildOutput} && cat remote_build_output.txt"
Another way is to output the last build log:
sh "curl -o remote_last_build_output.txt ${env.JENKINS_URL}/job/build_job/lastBuild/consoleText && cat remote_last_build_output.txt"
You can use env.JENKINS_URL if it's set. If not, you can replace it by your Jenkins URL.
build_job is the name of your remote job.
Note that if you're using the /lastBuild/ api call, you can't garantee that the last build is the same build that was triggered by your job (if the build_job is triggered by another system/person at the same time)
One last way is to enable the Parameterized Remote Trigger Plugin logging via the enhancedLogging option.
If set to true, the console output of the remote job is also logged.
def handle = triggerRemoteJob (
job: build_job,
enhancedLogging: true
...
)
You can then save the current job output in a file and parse what ever you want:
sh "curl -o current_build_output.txt ${env.JENKINS_URL}job/${env.JOB_NAME}/${currentBuild.number}/consoleText && cat current_build_output.txt"
${currentBuild.number} can also be replaced by the ${env.BUILD_NUMBER} variable
I don't need cron job because the build is needed to run only once in production and not periodically.Is there a way to build the pipeline at a scheduled time without cron.
You can schedule a build using Groovy via script console or job using: scheduleBuild2:
def waittime = 100 // in secs
def jobName = 'folder/jobname' //aka it.fullName
Jenkins.instance.getItemByFullName(jobName).scheduleBuild2(waittime)
quietPeriod - seconds to wait before starting (normally 0)
public QueueTaskFuture<R> scheduleBuild2(int quietPeriod, Action... actions)
Description copied from interface:
ParameterizedJobMixIn.ParameterizedJob Provides a standard
implementation of SCMTriggerItem.scheduleBuild2(int,
hudson.model.Action...) to schedule a build with the ability to wait
for its result. That job method is often used during functional tests
(JenkinsRule.assertBuildStatusSuccess).
Specified by: scheduleBuild2 in interface
ParameterizedJobMixIn.ParameterizedJob<P extends
AbstractProject<P,R>,R extends AbstractBuild<P,R>> Parameters:
quietPeriod - seconds to wait before starting (normally 0) actions -
various actions to associate with the scheduling, such as
ParametersAction or CauseAction Returns: a handle by which you may
wait for the build to complete (or just start); or null if the build
was not actually scheduled for some reason
One way to do is - You can trigger it remotely
https://www.jenkins.io/doc/book/using/remote-access-api/
Let's say you got a Linux box, you can schedule it by using the "at" command
at 9:30 PM Fri
curl -X POST JENKINS_URL/job/JOB_NAME/build \
--data token=TOKEN \
--data-urlencode json='{"parameter": [{"name":"id", "value":"123"},\
{"name":"verbosity", "value":"high"}]}'
job 2 at Fri Jan 29 21:30:00 2016
Then look at it with
at -c 2
I would like to read the revision number from Jenkins job when the job fails
Revision number:
Job script:
failure {
echo 'JENKINS PIPELINE FAILED'
notifyBitbucket
commitSha1: "${env.SVN_REVISION}",
considerUnstableAsSuccess: false,
credentialsId: 'UFCBitbucket',
disableInprogressNotification: true,
ignoreUnverifiedSSLPeer: true,
includeBuildNumberInKey: false,
prependParentProjectKey: false,
projectKey: '',
stashServerBaseUrl: 'https://bitbucket.url.local:8080'
}
I have trouble with Jenkins environment variable - "${env.SVN_REVISION}". This variable returns null value.
I can not solve this problem. Please help to solve this problem
Thanks in advance
I don't think the env-variable SVN_REVISION does even exist.
All available Git-plugin env-variables can be seen here (and the Jenkins' ones here).
I would suggest you use the following environment-variable to get the revision:
GIT_COMMIT - SHA1 of the commit used in this build
On the other hand you can get the revision also by executing the git command directly per sh / bash:
git rev-parse HEAD
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
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.