How to disable all jobs in a specific folder?

Article ID:226478907
2 minute readKnowledge base

Issue

I would like to disable all the jobs under a folder. Is there a way to do this?

Resolution

Currently, there is JENKINS-27735 tracking this.

In the meantime, you can use the following script from the Jenkins Script Console (JENKINS_URL/script)

To explain this.

Say I have a job hierarchy like this:

.
├── folder-a
│   └── jobs
│       ├── a_freestyle
│       ├── a_maven
│       ├── a_pipeline
│       └── folder-a_b
│           └── jobs
│               ├── a_b_freestyle
│               ├── a_b_maven
│               └── a_b_pipeline
├── folder-b
│   └── jobs
│       └── b_freestyle
├── freestyle
├── maven
└── pipeline

If I traverse this and print the full name of each job (folders are jobs as well), I get:

folder-a/a_freestyle
folder-a/a_maven
folder-a/folder-a_b/a_b_freestyle
folder-a/folder-a_b/a_b_maven
folder-b/b_freestyle
freestyle
maven

So using the following script, if I wanted to disable all jobs in folder-a I would specify folderName="folder-a", as its a top level folder.

If I wanted to disable all jobs in nested folder folder-a/folder-a_b, I would specify folderName="folder-a/folder-a_b".

NOTE: Only item types that support disabling are disabled, i.e., if item implements API that enables disabling. This should include most of the classic types like Freestyle or Maven projects as well as Pipeline and Computable Folders like Multibranch Pipeline or Organization Folder.

NOTE: Make sure your user has run script permissions.

NOTE: Change folderName value for the full name of the folder you want to disable jobs in.

Example that does not traverse child folders:

import com.cloudbees.hudson.plugins.folder.AbstractFolder

folderName="folder-a" // change value `folder-a` for the full name of the folder you want to disable all jobs in

Jenkins.instance.getItemByFullName(folderName, AbstractFolder).getItems()
    .findAll { it instanceof ParameterizedJobMixIn.ParameterizedJob || it instanceof AbstractFolder }
    .each {
        it.makeDisabled(true)
        println("Disabled job: [$it.fullName]")
    }
null

Example that does traverse child folders:

import com.cloudbees.hudson.plugins.folder.AbstractFolder

folderName="folder-a" // change value `folder-a` for the full name of the folder you want to disable all jobs in

Jenkins.instance.getItemByFullName(folderName, AbstractFolder).getAllItems()
    .findAll { it instanceof ParameterizedJobMixIn.ParameterizedJob || it instanceof AbstractFolder }
    .each {
        it.makeDisabled(true)
        println("Disabled job: [$it.fullName]")
    }
null

You can perform a dry run by commenting out the disable line, i,e:

      //it.makeDisabled(true)

This will result in the names of the jobs that would be disabled being printed, but not disabled.

Tested product/plugin versions