How to change a Git URL in all Jenkins jobs

耗尽温柔 提交于 2019-12-10 10:11:52

问题


I have more than 100 jobs in Jenkins and I have to change a Git URL in each and every job since we changed the git server. I must traverse each job and change the Git URL. Can anyone help me with a groovy script?

I was able to traverse each job, but not able to get the Git URL or change it:

import hudson.plugins.emailext.*
import hudson.model.*
import hudson.maven.*
import hudson.maven.reporters.*
import hudson.tasks.*

// For each project
for(item in Hudson.instance.items) {
 println("JOB : " + item.name);
}

I badly need help in this, please someone help me.


回答1:


The script below will modify all Git URL. You will need to fill the modifyGitUrl method. Script is written for Git plugin version 2.3.2. Check the git plugin source code to adjust it to the version you need e.g. the constructor parameters might have changed.

import hudson.plugins.git.*
import jenkins.*
import jenkins.model.*

def modifyGitUrl(url) {
  // Your script here
  return url + "modified"
}

Jenkins.instance.items.each {
  if (it.scm instanceof GitSCM) {
    def oldScm = it.scm
    def newUserRemoteConfigs = oldScm.userRemoteConfigs.collect {
      new UserRemoteConfig(modifyGitUrl(it.url), it.name, it.refspec, it.credentialsId)
    }
    def newScm = new GitSCM(newUserRemoteConfigs, oldScm.branches, oldScm.doGenerateSubmoduleConfigurations,
                            oldScm.submoduleCfg, oldScm.browser, oldScm.gitTool, oldScm.extensions)
    it.scm = newScm 
    it.save()
  }
}



回答2:


I would have shut the server down and edited all the config.xml files with a script(sed/awk perl or something) and then restarted jenkins to load the new configurations.

If shutting down jenkins is not an option it is posible to get edit and post every config.xml with something like this

GET http://myserver/job/config.xml| sed s/oldurl/newurl/g |POST http://myserver/job/config.xml


来源:https://stackoverflow.com/questions/21640907/how-to-change-a-git-url-in-all-jenkins-jobs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!