You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何用Groovy查找Jenkins中使用指定仓库URL的所有任务并禁用

Fix: Groovy Script to Disable Jenkins Jobs in Folders Using Specific Git Repo URL

Your original script works for top-level projects but misses jobs nested inside folders because getAllItems(hudson.model.AbstractProject.class) doesn’t traverse folder hierarchies. Let’s update it to recursively scan every corner of your Jenkins instance, including subfolders.

Updated Groovy Script

// Define a recursive function to traverse all items including folders
def scanItems(items) {
    items.each { item ->
        // If the item is a folder, recursively scan its contents
        if (item instanceof com.cloudbees.hudson.plugins.folder.Folder || 
            item instanceof jenkins.branch.OrganizationFolder) {
            scanItems(item.getItems())
        }
        // Check if the item is a buildable project
        else if (item instanceof hudson.model.AbstractProject) {
            def scm = item.getScm()
            // Verify it's a Git SCM configuration
            if (scm instanceof hudson.plugins.git.GitSCM) {
                // Check all remote repo URLs (not just the first one)
                scm.getUserRemoteConfigs().each { remoteConfig ->
                    def repoUrl = remoteConfig.getUrl()
                    if (repoUrl.contains('XXXXXXXX')) { // Replace with your target URL fragment
                        println "Found matching repo URL: ${repoUrl}"
                        println "Disabling job: ${item.fullName}" // Shows full path including folders
                        item.makeDisabled(true)
                    }
                }
            }
        }
    }
}

// Start scanning from the root Jenkins instance
scanItems(Jenkins.instance.getItems())

println "Done! All matching jobs (including those in folders) have been disabled."

Key Improvements Over the Original Script

  • Recursive Folder Traversal: The scanItems function checks if an item is a folder (supports both standard CloudBees Folders and Organization Folders for multibranch pipelines) and digs into its contents.
  • Full Job Path: Uses item.fullName instead of just item.name to show the complete path to the job (e.g., ParentFolder/SubFolder/MyJob), making it easier to verify which jobs were modified.
  • Checks All Remote URLs: Instead of only looking at the first remote config, it iterates through all Git remotes attached to the job—handles cases where a job has multiple repo URLs.

Notes

  • Make sure you have the CloudBees Folder Plugin installed if you’re using folder structures (most modern Jenkins setups do).
  • Run this script from Jenkins Script Console (Manage Jenkins > Script Console).
  • Always test on a non-production instance first, or add a dry-run flag (comment out item.makeDisabled(true) and just print results) to verify which jobs will be affected.

内容的提问来源于stack exchange,提问作者raghu

火山引擎 最新活动