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
相关产品推荐
相关产品推荐

