paul
paul

Reputation: 4487

Jenkins: Delete a job if job name contains

I have gone through the solution here

hudson CI: how to delete all jobs?

for(j in jenkins.model.Jenkins.theInstance.getAllItems()) {
    j.delete()
}

but I am afraid to run this because I don't want to delete all jobs. Is it possible I can run it based on condition,

for(j in jenkins.model.Jenkins.theInstance.getAllItems()) {
    if(j.contains("demo")){
         j.delete();
        }
}

I don't know if contains works or not, but for sake of example, to explain my requirement in a better way.

Also, what all functions we can perform using this j variable.

Jenkins ver. 2.176.2

Upvotes: 0

Views: 588

Answers (1)

elandoncb
elandoncb

Reputation: 56

You can implement conditional statements. To delete jobs that contains a specific string, you can use:

for(j in jenkins.model.Jenkins.theInstance.getAllItems()){
    if((j.fullName).contains("demo")){
        j.delete()
    }
}

Note: If you had 3 jobs in your Jenkins instance named "demo", "demo1", and "example", then this script would delete "demo" AND "demo1" but not "example". To only delete "demo" use the conditional:

if((j.fullName).equals("demo"))

Lastly, you can leverage this link that describes how to list the specific methods available for an object referenced in the script.

Upvotes: 2

Related Questions