GitLab Webhook触发Jenkins带参项目仅执行最后阶段问题排查
问题原因分析
手动触发时,你通过Extended Choice Parameter传入的action参数是build、burn、test,所以_build、_burn、_test能匹配到对应值,对应阶段会正常执行。但Webhook触发时,GitLab合并事件传递的$.object_attributes.action并不是build,而是GitLab自身的动作标识(比如merge),导致_build被设为error,所有依赖_build、_burn、_test的阶段都被跳过,只有无执行条件的mail report阶段会运行。
解决方案
方案1:Webhook触发时强制指定action为build
修改GenericTrigger配置,给action参数添加默认值,同时调整环境变量逻辑,优先识别Webhook触发的主分支合并场景:
pipeline { agent any environment { SRCCODE_DIR = "/var/jenkins_home/workspace/tmptest" // 优先判断是否是Webhook触发的主分支合并,是则强制_build为build _build = (env.target_branch == 'main' && env.action_status == 'merged') ? 'build' : sh(script: 'echo $action | grep -w -o "build" || echo "error"', returnStdout: true).trim() _burn = sh(script: 'echo $action | grep -w -o "burn" || echo "error"', returnStdout: true).trim() _test = sh(script: 'echo $action | grep -w -o "test" || echo "error"', returnStdout: true).trim() } triggers { GenericTrigger( genericVariables: [ [key: 'source_branch', value: '$.object_attributes.source_branch', expressionType: 'JSONPath'], [key: 'target_branch', value: '$.object_attributes.target_branch', expressionType: 'JSONPath'], // 给action设置默认值,Webhook触发时如果获取不到对应值则用build [key: 'action', value: '$.object_attributes.action', expressionType: 'JSONPath', defaultValue: 'build'], [key: 'action_status', value: '$.object_attributes.state', expressionType: 'JSONPath'], ], token: 'tmptest', regexpFilterText: '$target_branch_$action_status', regexpFilterExpression: 'main_merged', causeString: 'new code merge to main', printContributedVariables: true, // 开启后可在构建日志查看传入的变量值,方便调试 printPostContent: true ) } stages { // 原stage逻辑保持不变 stage("pull code") { when { environment name: '_build', value: 'build' } steps { println "pull code" } } stage("build image") { when { environment name: '_build', value: 'build' } steps { println "build image" } } stage("deploy image") { when { environment name: '_build', value: 'build' } steps { println "deploy image" } } stage("send message") { when { environment name: '_build', value: 'build' } steps { println "send msg" } } stage("burn image") { when { environment name: '_burn', value: 'burn' } steps { println "burn image" } } stage("smoketest") { when { environment name: '_test', value: 'test' } steps { println "smoke test" } } stage("mail report") { steps { println "send testreport" } } } }
方案2:直接在阶段条件中判断Webhook触发场景
不依赖action参数,直接在build相关阶段的when条件里添加Webhook触发的判断:
stage("pull code") { when { anyOf { environment name: '_build', value: 'build' // 直接判断是否是主分支合并的Webhook触发 allOf { environment name: 'target_branch', value: 'main' environment name: 'action_status', value: 'merged' } } } steps { println "pull code" } } // 其他build相关阶段(build image、deploy image、send message)的when条件做同样修改
调试建议
开启printContributedVariables: true后,触发一次Webhook构建,在Jenkins的构建日志中可以看到所有从GitLab传递过来的变量值,能更直观地确认action、target_branch等参数的实际内容,帮助调整逻辑。
内容的提问来源于stack exchange,提问作者Mr.Bingo
相关产品推荐
相关产品推荐

