How to delete multiple jobs?

Issue

How do I delete multiple jobs simultaneously?

Environment

  • CloudBees Jenkins Enterprise

Resolution

You can run the following from the Script Console ( $JENKINS_URL/script):

import hudson.model.*

jobsToDelete = ["aFolder/aJobInFolder","topLevelJob"]

deleteChildren(Hudson.instance.items)

def deleteChildren(items) {
  items.each { item ->
    if (item.class.canonicalName != 'com.cloudbees.hudson.plugins.folder.Folder') {
      if (jobsToDelete.contains(item.fullName)) {
        println(item.fullName)
        //item.delete()
      }
    } else {
    deleteChildren(((com.cloudbees.hudson.plugins.folder.Folder) item).getItems())
    }
  }
}

Replace jobsToDelete values with your job names. Note that for jobs in folders use / separator with folder names, i.e. aFolder/aJobInFolder.

Running with //item.delete() allows you to see a list of jobs that would be deleted without actually deleting any (dry run). Once you are happy with the job list uncomment item.delete(), i.e. //item.delete() -> item.delete().

NOTE: There is no undo for this once you have deleted the jobs. Recommend taking a backup before deleting anything to be safe.

Have more questions? Submit a request

4 Comments

  • 0
    Avatar
    Imran Khan

    Why is this line called if the item is not a folder?

    deleteChildren(((com.cloudbees.hudson.plugins.folder.Folder) item).getItems())

    edit:

    Nevermind.  I understand recursion. I swear. 

    Edited by Imran Khan
  • 0
    Avatar
    Allan Burdajewicz

    This line is in the `else {...}` block and therefore is called when the item IS a folder:

        else {
        deleteChildren(((com.cloudbees.hudson.plugins.folder.Folder) item).getItems())
        }

    The indentation is confusing though...

  • 0
    Avatar
    Luke Chalmers

    I am going to be refreshing a large number of jobs from one environment to another.  Unfortunately this had been done once in the past and the new environment wasnt used.  As a result theres a bunch of old copies of the jobs in on the new system and I am thinking I should delete them before migrating the fresh copies over.  

    1) if I copy the jobs over at the file system level and force an overwrite is that known to be problematic? 

    2) if I use this command to delete the jobs first, and I delete all jobs in a folder but that the folder is nested several layers down what would be the correct syntax? 

    i.e. 

    jobsToDelete = [Root_Folder/Sub_Folder/FolderWithOldJobs] 
    ?
  • 0
    Avatar
    Denys Digtiar

    Hi Luke,

    If you need to delete all the Projects in a Folder, you don't necessary need this script. You can just delete a folder which will delete all its content as well. You can recreate the Folder again if you still need it afterward.

Please sign in to leave a comment.