I am trying to find a way to disable automatic job execution on all jenkins jobs on a stage instance.
We are using jenkins-job-builder to create and update more than 1000 jobs and I want to populate a staging instance with the same jobs I have on production but I want to avoid triggering them on schedulers.
So far I identified two sources that need to be disabled:
timer schedule
gerrit trigger
I do know what disabling jobs does have this effect but this also prevents people from manually triggering these jobs, and for staging instance that's in fact the only kind of job triggering that I want to keep enabled.
Is there a way to achieve this?
I just wrote 2 groovy scripts for the exact use case.
Stop TimerTrigger and PeriodicTrigger jobs:
/**
*
* This script disables all jobs that have TimerTrigger or PeriodicFolderTrigger (WorkflowMultiBranchProject)
*
* */
import jenkins.model.Jenkins
import hudson.model.*
import hudson.triggers.*
import com.cloudbees.hudson.plugins.folder.computed.PeriodicFolderTrigger
def items = Jenkins.instance.getAllItems()
items.each { item ->
if(item.hasProperty('triggers')){
item.triggers.values().each { trigger ->
if(trigger instanceof TimerTrigger || trigger instanceof PeriodicFolderTrigger) {
println "Disabling project with timer trigger: ${item.name}"
item.setDisabled(true)
}
}
}
}
Stop SCMTrigger jobs (same idea, different Trigger class)
/**
*
* This script disables all jobs with SCM trigger
*
* */
import jenkins.model.Jenkins
import hudson.model.*
import hudson.triggers.*
def items = Jenkins.instance.getAllItems()
items.each { item ->
if(item.hasProperty('triggers')){
item.triggers.values().each { trigger ->
if(trigger instanceof SCMTrigger) {
println "Disabling project with SCM trigger: ${item.name}"
item.setDisabled(true)
}
}
}
}
Related
I am using the below Configure block for the scan by webhook functionality in Jenkins Job DSL.
Environment: Jenkins and Bitbucket
traits << 'com.igalg.jenkins.plugins.mswt.trigger.ComputedFolderWebHookTrigger' {
token("TEST_HOOK")
}
The above block is not working.
But the below periodic trigger syntax is working with out any issues.
it / 'triggers' << 'com.cloudbees.hudson.plugins.folder.computed.PeriodicFolderTrigger'{
spec '* * * * *'
interval "60000"
}
As we want to use the scan by webhook functionality. Kindly correct my scan by webhook syntax
The Job DSL Pipeline provides some declarative Parts for triggering a job either on changes or scheduled.
Another case can be the Multibranch Pipeline, where any branch is configured by the included Jenkinsfile. In order to create Jobs for a new branch, the Task "Scan Multibranch Pipeline Now" has to be executed either manually or scheduled. This can be programmatically(schedule) done via the configure block inside the Multibranch Pipeline Job:
multibranchPipelineJob("JobName") {
...
configure { node ->
def periodicFolderTrigger = node / triggers / 'com.cloudbees.hudson.plugins.folder.computed.PeriodicFolderTrigger' {
spec('H H * * *')
//4 hours (60000(Milliseconds)*60(Minutes)*4(hours)
interval(60000*60*4)
}
}
}
The webhook Solution, is more elegant, but you need the Jenkins plugin https://plugins.jenkins.io/multibranch-scan-webhook-trigger/ to be installed. Programmatically you can activate this via the following way:
multibranchPipelineJob("JobName") {
...
configure { node ->
def webhookTrigger = node / triggers / 'com.igalg.jenkins.plugins.mswt.trigger.ComputedFolderWebHookTrigger' {
spec('')
token("TESTTOKEN")
}
}
}
I have hundreds of jenkins jobs(multibranch pipeline) with trigger enabled to periodically scan respective repositories every 5 mins. I'm trying to disable "scan multibranch pipeline triggers" on all the existing jobs in a particular folder(development/microservice). I'm running below script from Jenkins script console and getting exception at removeTrigger
import hudson.model.*
import hudson.triggers.*
import jenkins.model.*
import com.cloudbees.hudson.plugins.folder.Folder
for (it in Jenkins.instance.getAllItems(jenkins.branch.MultiBranchProject.class)) {
if(it.fullName.length() > 25 && it.fullName.substring(0,25) ==
'development/microservice/' && it.fullName.split("/").length == 3) {
println it.fullName
it.triggers.each { descriptor, trigger ->
it.removeTrigger(descriptor)
it.save()
}
}
}
Can someone please help me how to disable triggers on multibranch pipeline jobs programmatically.
It seems one just needs to iterate over the triggers, and pass the right part to removeTrigger(); that means passing the trigger rather than the descriptor:
for (p in Jenkins.instance.getAllItems(jenkins.branch.MultiBranchProject.class)) {
p.triggers.each { descriptor, trigger ->
//println descriptor
//println trigger
p.removeTrigger(trigger)
}
}
Output sample for a single trigger, when println statements are not commented out:
com.cloudbees.hudson.plugins.folder.computed.PeriodicFolderTrigger$DescriptorImpl#30f35b28
com.cloudbees.hudson.plugins.folder.computed.PeriodicFolderTrigger#3745f994
Many thanks for your question, your almost working code helped me a lot. ;)
I have a Jenkins Multijob project (https://wiki.jenkins.io/display/JENKINS/Multijob+Plugin), with let's say 10 child jobs. Each of these jobs has console output that is essential for me to watch. Rather than open 10 tabs and jump between them to watch the output, is there a way I can funnel all the console output of each job into one? Can I perhaps send all this output to the console of the master/Multijob, instead of it simply listing [SUCCESS] or [FAILURE] of each of the child jobs?
I was looking for something similar and I found that post Jenkins hierarchical jobs and jobs status aggregation
Base on that I did something similar to my multijob with only one level of phase jobs
import hudson.model.*
import com.tikal.jenkins.plugins.multijob.*;
void log(msg) {
manager.listener.logger.println(msg)
}
threshold = Result.SUCCESS
void aggregate_results() {
failed = false
mainJob = manager.build.getProject().getName()
job = hudson.model.Hudson.instance.getItem(mainJob)
log "---------------------------------------------------------------------------------------------------------------"
log "Aggregated status report"
log "---------------------------------------------------------------------------------------------------------------"
log("${mainJob} #${manager.build.getNumber()} - ${manager.build.getResult()}")
job.getLastBuild().getSubBuilds().each { subBuild->
subJob = subBuild.getJobName()
subJobNumber = subBuild.getBuildNumber()
job = hudson.model.Hudson.instance.getItem(subBuild.getJobName())
log "${subJob} #${subJobNumber} - ${job.getLastCompletedBuild().getResult()}"
log job.getLastCompletedBuild().getLog()
}
}
try {
aggregate_results()
} catch(Exception e) {
log("ERROR: ${e.message}")
log("ERROR: Failed Status report aggregation")
}
I need to add the next build time scheduled in a build email notification after a build in Jenkins.
The trigger can be "Build periodically" or "Poll SCM", or anything with schedule time.
I know the trigger info is in the config.xml file e.g.
<triggers>
<hudson.triggers.SCMTrigger>
<spec>8 */2 * * 1-5</spec>
<ignorePostCommitHooks>false</ignorePostCommitHooks>
</hudson.triggers.SCMTrigger>
</triggers>
and I also know how to get the trigger type and spec with custom scripting from the config.xml file, and calculate the next build time.
I wonder if Jenkins has the API to expose this information out-of-the-box. I have done the search, but not found anything.
I realise you probably no longer need help with this, but I just had to solve the same problem, so here is a script you can use in the Jenkins console to output all trigger configurations:
#!groovy
Jenkins.instance.getAllItems().each { it ->
if (!(it instanceof jenkins.triggers.SCMTriggerItem)) {
return
}
def itTrigger = (jenkins.triggers.SCMTriggerItem)it
def triggers = itTrigger.getSCMTrigger()
println("Job ${it.name}:")
triggers.each { t->
println("\t${t.getSpec()}")
println("\t${t.isIgnorePostCommitHooks()}")
}
}
This will output all your jobs that use SCM configuration, along with their specification (cron-like expression regarding when to run) and whether post-commit hooks are set to be ignored.
You can modify this script to get the data as JSON like this:
#!groovy
import groovy.json.*
def result = [:]
Jenkins.instance.getAllItems().each { it ->
if (!(it instanceof jenkins.triggers.SCMTriggerItem)) {
return
}
def itTrigger = (jenkins.triggers.SCMTriggerItem)it
def triggers = itTrigger.getSCMTrigger()
triggers.each { t->
def builder = new JsonBuilder()
result[it.name] = builder {
spec "${t.getSpec()}"
ignorePostCommitHooks "${t.isIgnorePostCommitHooks()}"
}
}
}
return new JsonBuilder(result).toPrettyString()
And then you can use the Jenkins Script Console web API to get this from an HTTP client.
For example, in curl, you can do this by saving your script as a text file and then running:
curl --data-urlencode "script=$(<./script.groovy)" <YOUR SERVER>/scriptText
If Jenkins is using basic authentication, you can supply that with the -u <USERNAME>:<PASSWORD> argument.
Ultimately, the request will result in something like this:
{
"Build Project 1": {
"spec": "H/30 * * * *",
"ignorePostCommitHooks": "false"
},
"Test Something": {
"spec": "#hourly",
"ignorePostCommitHooks": "false"
},
"Deploy ABC": {
"spec": "H/20 * * * *",
"ignorePostCommitHooks": "false"
}
}
You should be able to tailor these examples to fit your specific use case. It seems you won't need to access this remotely but just from a job, but I also included the remoting part as it might come in handy for someone else.
I have a project, named Demo, which doesn't do anything in particular.
I have a DSL script, like the following:
def gitUrl = 'GIT_URL'
job('unit-tests') {
scm {
git(gitUrl)
}
triggers {
buildResult('H/* * * * *') {
combinedJobs()
triggerInfo('Demo', BuildResult.SUCCESS, BuildResult.UNSTABLE)
}
}
}
Now what I'm wanting to do, is that when the Demo project runs successfully (it checks out a PHP application from Github), I want the unit-tests job to run.
Currently, when the Demo project is built, the unit-tests job never gets run.
I'm guessing my DSL script is incorrect, but I'm not sure why
I can reproduce your problem. The check box is not set when running the seed job for the first time. But it's set after running the seed job a second time. Must be a problem in the BuildResultTrigger plugin. Please file a bug report in the Jenkins JIRA: https://issues.jenkins-ci.org/projects/JENKINS
But you do not necessarily need to use the BuildResultTrigger plugin. You can use the built-in "Build after other projects are built" option, see https://jenkinsci.github.io/job-dsl-plugin/#path/job-triggers-upstream.
job('unit-tests') {
triggers {
upstream('Demo', 'UNSTABLE')
}
}
Use upstream which adds the "Build after other projects are built" trigger. see https://jenkinsci.github.io/job-dsl-plugin/#path/job-triggers-upstream
def gitUrl = 'GIT_URL'
job('unit-tests') {
scm {
git(gitUrl)
}
triggers {
buildResult('H/* * * * *') {
upstream('Demo', 'UNSTABLE')
}
}
}