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

Jenkins Pipeline如何根据deploy参数控制Copy file阶段是否执行

Jenkins Pipeline 条件执行阶段配置修正

错误原因

配置不生效是两处语法问题导致:

  • 变量赋值错误:deploy = yes 中的yes未加引号,会被Jenkins识别为未定义变量而非你预期的"yes"字符串,变量取值本身就不符合预期
  • when条件语法错误:声明式Pipeline的when指令中,自定义判断逻辑必须放在expression {}块内,不能直接写判断语句

修正后代码(硬编码deploy取值场景)

servers =['100.1.1.1', '100.1.1.2']
// 修正1:给yes加引号,定义为字符串类型
deploy = 'yes'

pipeline {
    agent { label 'server-1' }

    stages {
        stage('Connect to git') {
            steps {
                    git branch: 'xxxx', credentialsId: 'yyy', url: 'https://zzzz'
            }
        }
        stage ('Copy file') {
            when {
                // 修正2:用expression块包裹自定义判断逻辑
                expression { deploy == 'yes' }
            }
            steps {
                dir('folder_a') {
                    file_copy(servers)
                }
            }
        }
    }
}

def file_copy(list) {
    list.each { item ->
        sh "echo Copy file"
        sh "scp 11.txt user@${item}:/data/"
    }
}

可选优化:将deploy配置为运行时参数

如果希望无需修改代码即可控制是否执行部署阶段,可以在pipeline中添加参数配置,运行流水线时手动选择取值:

servers =['100.1.1.1', '100.1.1.2']

pipeline {
    agent { label 'server-1' }
    // 新增参数配置项
    parameters {
        choice(name: 'deploy', choices: ['no', 'yes'], description: '是否执行文件拷贝部署阶段')
    }

    stages {
        stage('Connect to git') {
            steps {
                    git branch: 'xxxx', credentialsId: 'yyy', url: 'https://zzzz'
            }
        }
        stage ('Copy file') {
            when {
                // 引用参数变量判断
                expression { params.deploy == 'yes' }
            }
            steps {
                dir('folder_a') {
                    file_copy(servers)
                }
            }
        }
    }
}

def file_copy(list) {
    list.each { item ->
        sh "echo Copy file"
        sh "scp 11.txt user@${item}:/data/"
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 08:36:03