CodyK
CodyK

Reputation: 3657

How can I delete a job and run cleanup code with JobDSL in Jenkins?

Similar to this question: https://stackoverflow.com/questions/33784488/how-can-i-delete-a-job-using-job-dsl-pluginscript-in-jenkins#=

The issue is if I add removeAction('DELETE') to the DSL, the job will be deleted which is what I want, but I'd also like to run some cleanup code. Is there a way to query JobDSL, or get a delta of the new jobs being created vs what previously existed last run?

The context is, I am using JobDSL to create a pipeline job for each branch that exists in a GIT repository. When the branch is deleted, I want to remove the job and run some cleanup code.

Upvotes: 0

Views: 1169

Answers (1)

daspilker
daspilker

Reputation: 8194

Each build of the seed job stores the names of the generated jobs in a GeneratedJobsBuildAction. If you compare the generated jobs of the last build with the previous build, you get the names of the jobs that have been deleted.

You can try the following example in Jenkins Script Console to get the names of the jobs that have been deleted with the last run of the seed job:

import javaposse.jobdsl.dsl.GeneratedJob
import javaposse.jobdsl.plugin.actions.GeneratedJobsBuildAction

FreeStyleProject seedJob = Jenkins.instance.getItem('seed')

FreeStyleBuild lastBuild = seedJob.lastBuild
FreeStyleBuild previousBuild = lastBuild.previousBuild

Set<GeneratedJob> lastGeneratedJobs = lastBuild.getAction(GeneratedJobsBuildAction).modifiedObjects
Set<GeneratedJob> previousGeneratedJobs = previousBuild.getAction(GeneratedJobsBuildAction).modifiedObjects

print previousGeneratedJobs*.jobName - lastGeneratedJobs*.jobName

Upvotes: 1

Related Questions