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

Jenkins Pipeline:如何将两个不同参数的值合并到一个字段中?

在Jenkins Pipeline中合并字段到buildName的实现方法

基础字符串拼接实现

如果build_label和app_name是已定义的变量(比如流水线参数、环境变量或脚本内变量),可以直接通过字符串拼接将两者合并,赋值给buildName参数:

pipeline {
    agent any
    options {
        // 用分隔符(横线/下划线等)拼接两个字段,按需调整格式
        buildName "${app_name}-${build_label}"
    }
    stages {
        stage('验证构建名称') {
            steps {
                echo "当前构建名称: ${currentBuild.displayName}"
            }
        }
    }
}

处理字段为空的场景

如果担心其中某个字段可能为空,可添加空值判断,避免出现多余的分隔符:

pipeline {
    agent any
    options {
        buildName getCombinedBuildName()
    }
    stages {
        stage('验证构建名称') {
            steps {
                echo "当前构建名称: ${currentBuild.displayName}"
            }
        }
    }
}

def getCombinedBuildName() {
    def nameParts = []
    if (app_name) nameParts.add(app_name)
    if (build_label) nameParts.add(build_label)
    // 若两个字段都为空,返回默认名称
    return nameParts.join('-') ?: '默认构建'
}

动态获取字段值的场景

如果build_label或app_name是流水线执行过程中动态生成的(比如从命令输出、文件读取),可先将值存入变量再拼接:

pipeline {
    agent any
    environment {
        // 从shell命令获取app_name,从文件读取build_label
        APP_NAME = sh(script: 'echo my-service', returnStdout: true).trim()
        BUILD_LABEL = readFile('version.txt').trim()
    }
    options {
        buildName "${APP_NAME}_${BUILD_LABEL}"
    }
    stages {
        stage('验证构建名称') {
            steps {
                echo "当前构建名称: ${currentBuild.displayName}"
            }
        }
    }
}

补充:如果需要在流水线执行阶段动态修改构建名称,可直接更新currentBuild.displayName:

currentBuild.displayName = "${app_name}-${build_label}"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 15:54:57