Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

groovy if statement with regex in variable

Tags:

jenkins

groovy

I want to delete list of Jenkins jobs that begins with AAA (for example)

When i do it with explicit string it works fine

if (item.name ==~ /AAA.*/){  
    item.delete()
 }

but when i try to get the regex from a Jenkins Build property, i fail and the if is not called...

import hudson.model.*
import hudson.node_monitors.*
import hudson.slaves.*
import java.util.concurrent.*

jenkins = Hudson.instance

def thr = Thread.currentThread()

def build = thr?.executable

String REGEX = build.environment.get("Include_Regex")

println "REGEX is " + REGEX

for (item in jenkins.items){
   println("\t ${item.name}");
   println("\t ${item.name.getClass()}");
   if (item.name ==~ REGEX){  
       item.delete()
       println("TEST");
    }

} 

When I run it, i get a list of all jobs: Building in workspace /var/lib/jenkins/jobs/Bulk_Delete_Job/workspace

REGEX is /AAA.*/
     AAA_test_1
     class java.lang.String
     AAA_test_2
     class java.lang.String
     AAA_test_3
     class java.lang.String
     Bulk_Delete_Job
     class java.lang.String
     ConfiguredJob
     class java.lang.String
     JobZ
     class java.lang.String
     TEST_SCM
     class java.lang.String

But nothing is deleted / no "TEST" is printed -> the if is never true....

Assistance is required, Thanks!

like image 671
Doron Shai Avatar asked Mar 14 '23 23:03

Doron Shai


1 Answers

The String should not include the slashes - use AAA.* instead of /AAA.*/.

like image 82
wolfs42 Avatar answered Mar 20 '23 22:03

wolfs42