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

如何在声明式Jenkins Pipeline中按分支启用/禁用Jenkinsfile属性?

转换为声明式Jenkinsfile的实现方案

声明式流水线可通过动态配置选项实现分支差异化的并发构建控制,以下是对应转换后的代码:

@Library('shared-library') _

pipeline {
  agent { label 'linux-node' }
  
  options {
    // 所有分支共用的日志保留策略
    buildDiscarder(logRotator(numToKeepStr: '50', artifactNumToKeepStr: '20'))
    // 根据分支判断是否禁用并发构建
    script {
      if (!env.BRANCH_NAME.equals(env.PROD_BRANCH)) {
        disableConcurrentBuilds()
      }
    }
  }
  
  parameters {
    editableChoice(name: 'BUILD_NODE', choices: ['linux-ubuntu', 'ec2-fleet-0'], description: 'Build node to use')
    choice(name: 'AWS_REGION', choices: ['us-east-1', 'eu-north-1'], description: 'AWS region to build at')
    booleanParam(name: 'CONFIRM', defaultValue: true, description: 'Actually do the build?')
    choice(name: 'DEBUG_LEVEL', choices: ['0', '1', '2', '3'], description: 'Debugger verbosity.')
  }
  
  stages {
    stage('Do build') {
      steps {
        script {
          // 执行具体构建逻辑
          // do something
        }
      }
    }
  }
}

核心优化点

  • 抽离公共配置(日志保留、构建参数),避免重复代码,仅针对并发控制做分支判断
  • 在options块中嵌入script逻辑,实现根据分支动态启用disableConcurrentBuilds()
  • 声明式原生支持参数定义,无需嵌套在properties中
  • 用声明式agent块替代原脚本式的node块,更符合声明式语法规范

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 03:21:00