Skip to content

Instantly share code, notes, and snippets.

@hgomez
Last active November 8, 2021 12:01
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save hgomez/8757649 to your computer and use it in GitHub Desktop.
Save hgomez/8757649 to your computer and use it in GitHub Desktop.
Jenkins Groovy script to set CredentialsId
import hudson.model.*
import hudson.maven.*
import hudson.tasks.*
import hudson.scm.*
def match_url = "http://svn.mycorp.com/svn/devops"
for(item in Hudson.instance.items) {
hasClaim = false;
if (item.scm instanceof SubversionSCM)
{
for(location in item.scm.locations) {
if (location.remote.startsWith(match_url)) {
println("\n@@@@@@@@@@@@@@@@@")
println("\njob $item.name")
println("\n@@@@@@@@@@@@@@@@@")
println("\nlocation $location.remote")
credid = location.credentialsId
if (credid != null)
println("\ncredid $credid")
}
}
}
}
@mjoe
Copy link

mjoe commented Feb 6, 2014

Did you found a way to update the read-only credentialsId property?

@mohamedelhabib
Copy link

import java.util.*
import hudson.model.*
import hudson.matrix.*
import hudson.tasks.*
import hudson.scm.*

def match_url = "http://svn.mycorp.com/svn/devops"

hudson.model.Hudson.instance.items.findAll{job -> job.isBuildable() && job instanceof SCMedItem}.each{
job ->

def scm = job.getScm()
if (scm instanceof hudson.scm.SubversionSCM) {

def locationToDelete = null
for (int i = 0; i < scm.locations.length; i++) {
  def location = scm.locations[i]
  if (location.remote.startsWith("match_url")) {
        println(job.name + " : " + location.credentialsId + " : " + location.remote + " : " + location.local)
            scm.locations[i]  = location.withCredentialsId("d9e7f567-0f02-4e4a-a305-f61114e4f2a7")
            println(job.name + " : " + scm.locations[i].credentialsId + " : " + scm.locations[i].remote + " : " + scm.locations[i].local)
  }
}

}
job.save()
}

@reiabreu
Copy link

@elhabibmed, your script works just fine. Thanks

@mbarczak
Copy link

mbarczak commented Jan 9, 2015

There is a bug in this line :

if (location.remote.startsWith("match_url")) {

There is no $ before variable name. It should be :

if (location.remote.startsWith("$match_url")) {

Also, this check :

&& job instanceof SCMedItem

on Jenkins 1.580.1 LTS caused that only jobs created as "Multi-configuration project" were affected. After fixing bug with "$" and after removing above check from if, script works just fine and changes all jobs matching "$match_url".

@sathishc58
Copy link

Please post the code to set the 'credentials id' as I've been searching for quite sometime now. This code deals with fetching the 'credentials id' Thanks in advnace

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment