I have the below piece of code in groovy to schedule the job at 12 am IST.
I am using Job DSL plugin to seed the job.
Initial code-
triggers{
cron{
spec("TZ=Asia/Calcutta\n0 0 * * *")
}
}
For the same even though it works, I get depreciation warnings.
Warning: (jobName.groovy, line 18) triggers is deprecated
Second code-
void nightly(String schedule = 'H 0 * * *') {
job.properties {
pipelineTriggers {
triggers{
cron{
spec("TZ=Asia/Calcutta\nH 0 * * *")
}
}
}
}
}
The second one got failed with the below error message.
JobScriptsSpec > test script fr_oms_core_unit_perf_sanity_job.groovy FAILED
org.spockframework.runtime.UnallowedExceptionThrownError at JobScriptsSpec.groovy:24
Caused by: javaposse.jobdsl.dsl.DslException at JobScriptsSpec.groovy:21
Caused by: org.codehaus.groovy.control.MultipleCompilationErrorsException at JobScriptsSpec.groovy:21
How can I avoid the same?
Am I using the correct format?
Thanks in advance.
The new syntax uses the pipelineTriggers directive under the properties directive instead of the deprecated triggers directive:
pipelineJob('MyPipelineJob') {
properties {
pipelineTriggers {
triggers {
cron{
spec("TZ=Asia/Calcutta\n0 0 * * *")
}
}
}
}
}
The documentation for the pipelineTriggers is available in your own Jenkins server in the following URL:
https://your.jenkins.domain/plugin/job-dsl/api-viewer/index.html#path/javaposse.jobdsl.dsl.DslFactory.pipelineJob-properties-pipelineTriggers
Related
I'm using jobdsl 1.76 and trying to migrate to 1.77: from triggers to pipelineTriggers:
pipelineJob('testPipelineTriggers'){
properties {
pipelineTriggers {
triggers {
cron{
spec("* * * * *")
}
}
}
}
}
This simple code giving me below error which I couldnt understand:
No signature of method: javaposse.jobdsl.dsl.helpers.properties.PropertiesContext.pipelineTriggers() is applicable for argument types: (XXX$__clinit__closure1$_closure2$_closure7$_closure9) values: [XXX$__clinit__closure1$_closure2$_closure7$_closure9#3c818ac4]
note: I replaced our groovy filename with 'XXX'
some days ago I bumped into a code snippet used to override the default configuration of the Jenkins plugin "GitHub SCM Source" (unknown author):
Closure configOverride(String repo, int id, String cred) {
return {
it / sources / 'data' / 'jenkins.branch.BranchSource' << {
source(class: 'org.jenkinsci.plugins.github_branch_source.GitHubSCMSource') {
id(id)
scanCredentialsId(cred)
checkoutCredentialsId('SAME')
repoOwner('owner')
repository(repo)
includes('*')
buildOriginBranch('true')
buildOriginBranchWithPR('true')
buildOriginPRMerge('false')
buildOriginPRHead('false')
buildForkPRMerge('true')
buildForkPRHead('false')
}
}
}
}
All it's good except that I can't understand the following line:
it / sources / 'data' / 'jenkins.branch.BranchSource' << { ... }
I tried to find some explanation about the use of '/' in groovy but no luck. Maybe I don't know what exactly to search.
Could someone help me please with a link to the docs or a short explanation.
This is overloading of
operators
Groovy allows you to overload the various operators so that they can be used with your own classes. Consider this simple class:
class Bucket {
int size
Bucket(int size) { this.size = size }
Bucket plus(Bucket other) {
return new Bucket(this.size + other.size)
}
}
Just by implementing the plus() method, the Bucket class can now be used with the + operator like so:
def b1 = new Bucket(4)
def b2 = new Bucket(11)
assert (b1 + b2).size == 15
For / one would override T div(T x)
This code snippet is used in Jenkins DSL for the "multibranchPipelineJob". The closure configOverride is used to generate an XML object which replace the default configuration in config.xml on the following path "sources/data/jenkins.branch.BranchSource".
I have created the parameter but i am unable to pass that variable while creating the cron job.
job("dev_testing")
{
parameters
{
booleanParam('security_scan', true)
choiceParam('OPTION', ['false (default)', 'true',])
}
triggers
{
cron('H 23 * * 6 %security_scan; true')
}
}
Following is the error:
ERROR: Scripts not permitted to use method groovy.lang.GroovyObject invokeMethod java.lang.String java.lang.Object (javaposse.jobdsl.dsl.helpers.triggers.TriggerContext parameterizedTimerTrigger script$_run_closure1$_closure2$_closure3)
I dont know which plugins you have installed, but the Parameterized Scheduler plugin should help you with your use case.
Per their documentation, the below should work:
triggers {
parameterizedCron('''H 23 * * 6 %security_scan=true''')
}
This also worked for me:
triggers {
parameterizedTimerTrigger {
parameterizedSpecification('H 23 * * 6 %security_scan=true')
}
}
I know this is an old thread - but I just ran into this lately and couldn't get multiple triggers to work for the life of me. Finally I got it working so:
triggers {
parameterizedTimerTrigger {
parameterizedSpecification('''H 21 * * 0-4 %APPLICATION=php
H 23 * * 0-4 %APPLICATION=java''')
}
}
I have Jenkins pipeline set up for Git branches with the last optional step of deploying to stage:
stage('Stage') {
if (gitBranch != "master") {
timeout(time: 1, unit: 'DAYS') {
input message: "Do you want to deploy ${shortCommit} from branch ${gitBranch} to STAGE?"
}
}
node {
stage('Deploy Stage') {
echo("Deploying to STAGE ${gitCommit}")
sh "NODE_ENV=stage yarn lerna-run --since ${sinceSha} deploy"
}
}
}
The problem is deploying a branch to stage is optional, but Jenkins doesn't return a success code to Github until it's done.
Is there any syntax to mark it as optional?
You can combine the timeout step with the input step, like we have it here:
/**
* Generates a pipeline {#code input} step that times out after a specified amount of time.
*
* The options for the timeout are supplied via {#code timeoutOptions}.
* The options for the input dialog are supplied via {#code inputOptions}.
*
* The returned Map contains the following keys:
*
* - proceed: true, if the Proceed button was clicked, false if aborted manually aborted or timed out
* - reason: 'user', if user hit Proceed or Abort; 'timeout' if input dialog timed out
* - submitter: name of the user that submitted or canceled the dialog
* - additional keys for every parameter submitted via {#code inputOptions.parameters}
*
* #param args Map containing inputOptions and timoutOptions, both passed to respective script
* #return Map containing above specified keys response/reason/submitter and those for parameters
*/
Map inputWithTimeout(Map args) {
def returnData = [:]
// see https://go.cloudbees.com/docs/support-kb-articles/CloudBees-Jenkins-Enterprise/Pipeline---How-to-add-an-input-step,-with-timeout,-that-continues-if-timeout-is-reached,-using-a-default-value.html
try {
timeout(args.timeoutOptions) {
def inputOptions = args.inputOptions
inputOptions.submitterParameter = "submitter"
// as we ask for the submitter, we get a Map back instead of a string
// besides the parameter supplied using args.inputOptions, this will include "submitter"
def responseValues = input inputOptions
echo "Response values: ${responseValues}"
// BlueOcean currently drops the submitterParameter
// https://issues.jenkins-ci.org/browse/JENKINS-41421
if (responseValues instanceof String) {
echo "Response is a String. BlueOcean? Mimicking the correct behavior."
String choiceValue = responseValues
String choiceKey = args.inputOptions.parameters.first().getName()
responseValues = [(choiceKey): choiceValue, submitter: null]
}
echo "Submitted by ${responseValues.submitter}"
returnData = [proceed: true, reason: 'user'] + responseValues
}
} catch (FlowInterruptedException err) { // error means we reached timeout
// err.getCauses() returns [org.jenkinsci.plugins.workflow.support.input.Rejection]
Rejection rejection = err.getCauses().first()
if ('SYSTEM' == rejection.getUser().toString()) { // user == SYSTEM means timeout.
returnData = [proceed: false, reason: 'timeout']
} else { // explicitly aborted
echo rejection.getShortDescription()
returnData = [proceed: false, reason: 'user', submitter: rejection.getUser().toString()]
}
} catch (err) {
// try to figure out, what's wrong when we manually abort the pipeline
returnData = [proceed: false, reason: err.getMessage()]
}
returnData
}
In addition to your requirements, this also returns, who submitted the dialog.
I have the following Quartz job running in my application:
class ScraperJob {
def scraperService
static triggers = {
cron name: 'scraperTrigger', cronExpression: "0 0 * * * ?" // run every minute
}
def execute(){
try {
scraperService.storing()
log.info "${new Date()} - Scraping went smoothly."
}
catch(IOException) { // Connexion problem
log.error "${new Date()} - Method: parsing >> Connexion down or interrupted while parsing !"
}
catch(SAXException) { // Any SAXParser exception
log.error "${new Date()} - Method: parsing >> Parser error."
}
finally { // if not closed, the application crashes when the connexion fails
scraperService.slurper.finalize()
scraperService.parser.finalize()
}
}
}
I would like to know if it is possible to set the triggers property from the Config.groovy file. If it is, could you explain how?
I have no idea if this would actually work because i'm not sure when the quartz jobs get configured but in theory it would seem to work. You could probably see how you could also make this much more dynamic if you have more than one job.
Config.groovy
quartz.yourCronJobName="0 0 * * * ?"
BootStrap.groovy
import org.codehaus.groovy.grails.commons.ConfigurationHolder as ConfigHolder
...
def cronExpression = ConfigHolder.config.yourCronJobName
ScraperJob.triggers.cronExpression = cronExpression
Good luck. Let me know if it helps.
Here is how I eventually did it:
Config.groovy
scraperJob= "0 * * * * ?"
ScraperJob.groovy
import org.codehaus.groovy.grails.commons.ConfigurationHolder as ConfigHolder
class ScraperJob {
static triggers = {
cron cronExpression: ConfigHolder.config.scraperJob // Calling the ScraperJob set in Config.groovy
}
def execute(){ ... }
}