Code-your-life DevOps Jenkins

Updating Jenkins job's Git url

June 8, 2018

So today I had the task of figuring out how many jobs we have in our Jenkins server that was collecting code from our old, Git server bitbucket.com (since the customer is migrating to an internal server). So I created this little script that lists Jenkins jobs with a specific SCM URL, it also handles folders recursively.

This was developed on a Jenkins 2.126, so if you are on another Jenkins version, some of this might not work, if you have any improvement’s feel free to make a merge request at jesstruck@github/jenkinsMaintinance (Yeah, I have not done the #movingtogitlab thing yet 😉 )

/**
The intention of this script is to loop through all jobs on the server and print the job name and URL if the URL matches the $url_regex. This is intended for SCM configurations of type hudson.plugins.git.GitSCM.

If find a Folder object it recursively loops through this also.

If you are not looking for "bitbucket.com", just change the url_regex, to a regular expression,
that matches your search criteria.
*/

url_regex = 'bitbucket.com'

def checkBitbucker(job, scm){
    if (scm.class.name == 'hudson.plugins.git.GitSCM') {
      if (scm.getUserRemoteConfigs() =~ /${url}/ ){
        println "Job '${job.name}' uses the following git configuration"
          println "\tRemote:     ${scm.getUserRemoteConfigs()[0].getUrl()}"
      }
    }
}

def printJobInfo(job){
  if (job.class.name =='com.cloudbees.hudson.plugins.folder.Folder'){
    job.getAllJobs().each{ child ->
      //Recursively call it self every time it finds a Folder object
      printJobInfo(child) 
    }
  }else if(job.class.name =='org.jenkinsci.plugins.workflow.job.WorkflowJob'){
    job.getSCMs().each{ scm ->
        checkBitbucker(job, scm)
    }
  }else{
    checkBitbucker(job, job.scm)
  }
}

hudson.model.Hudson.instance.items.each{ job ->
  printJobInfo(job)
}

Tagged: #Jenkins #Jenkins-Maintenance #Groovy