You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Groovy脚本批量更新所有Jenkins节点的标签?

批量更新Jenkins节点标签的Groovy脚本实现

我之前也碰到过给几百个Jenkins节点批量加标签的需求,用主节点的脚本控制台跑Groovy确实是最省事的办法,不用一个个手动点。下面给你几个实用的脚本方案,根据你的需求选就行:

1. 给所有节点添加额外标签

这个是最基础的场景,不管节点在线与否,都给它们加上指定的新标签(比如new-batch-tag):

// 遍历Jenkins实例下的所有节点
Jenkins.instance.nodes.each { node ->
    // 将当前节点的标签字符串拆分为列表,并转为可变的ArrayList(默认数组不可修改)
    def currentLabels = new ArrayList(node.getLabelString().split(/\s+/))
    // 定义要添加的新标签
    def newLabel = "new-batch-tag"
    
    // 检查标签是否已存在,避免重复添加
    if (!currentLabels.contains(newLabel)) {
        currentLabels.add(newLabel)
        // 将更新后的标签列表重新拼接为字符串,设置回节点
        node.setLabelString(currentLabels.join(" "))
        // 保存节点配置变更
        node.save()
        println "已给节点 ${node.name} 添加标签: ${newLabel}"
    } else {
        println "节点 ${node.name} 已存在标签 ${newLabel},跳过"
    }
}
println "=== 批量标签更新操作完成 ==="

2. 仅给在线节点添加标签

如果只想给当前处于在线状态的节点加标签,过滤掉离线节点,可以用这个脚本:

Jenkins.instance.nodes.each { node ->
    // 检查节点对应的计算机是否在线
    if (node.toComputer()?.isOnline()) {
        def currentLabels = new ArrayList(node.getLabelString().split(/\s+/))
        def newLabel = "online-node-mark"
        
        if (!currentLabels.contains(newLabel)) {
            currentLabels.add(newLabel)
            node.setLabelString(currentLabels.join(" "))
            node.save()
            println "已给在线节点 ${node.name} 添加标签: ${newLabel}"
        } else {
            println "在线节点 ${node.name} 已存在标签 ${newLabel},跳过"
        }
    } else {
        println "节点 ${node.name} 处于离线状态,跳过"
    }
}
println "=== 在线节点标签更新操作完成 ==="

3. 给特定名称匹配的节点添加标签

比如你只想给名称以prod-开头的生产节点添加专属标签,可以用正则匹配过滤节点:

// 定义要匹配的节点名称正则(这里匹配以prod-开头的节点)
def nodeNamePattern = ~/prod-.*/
def newLabel = "production-environment"

Jenkins.instance.nodes.each { node ->
    if (node.name ==~ nodeNamePattern) {
        def currentLabels = new ArrayList(node.getLabelString().split(/\s+/))
        
        if (!currentLabels.contains(newLabel)) {
            currentLabels.add(newLabel)
            node.setLabelString(currentLabels.join(" "))
            node.save()
            println "已给节点 ${node.name} 添加标签: ${newLabel}"
        } else {
            println "节点 ${node.name} 已存在标签 ${newLabel},跳过"
        }
    } else {
        println "节点 ${node.name} 不匹配目标名称规则,跳过"
    }
}
println "=== 指定节点标签更新操作完成 ==="

重要注意事项

  • 先测试再批量执行:建议先在测试环境或者选择少量节点验证脚本效果,避免误操作影响生产节点。
  • 脚本控制台入口:Jenkins主页 → 系统管理 → 脚本控制台(Manage Jenkins → Script Console)
  • 如果需要替换所有原有标签(不是添加),直接用node.setLabelString(newLabel)即可,但一定要谨慎,这会清空原有所有标签。
  • 脚本运行完成后,刷新节点列表确认标签是否正确更新。

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:31:04