Jenkinsfile的when语句未匹配分支,tf-apply阶段被跳过
问题分析与解决方案
你的问题根源在于Jenkins流水线的branch条件默认匹配的是BRANCH_NAME环境变量,但当前流水线中该变量的值并非你预期的分支名——当直接检出远程分支的特定提交时,Git处于分离HEAD状态,此时BRANCH_NAME通常会是提交哈希或HEAD,而非check-branch或origin/check-branch。你echo输出的origin/check-branch实际来自GIT_BRANCH变量(存储远程分支名),而非BRANCH_NAME。
步骤1:确认环境变量值
先添加一个调试阶段,明确两个关键分支变量的实际内容:
stage('Debug Branch Variables') { steps { script { echo "BRANCH_NAME: ${env.BRANCH_NAME}" echo "GIT_BRANCH: ${env.GIT_BRANCH}" } } }
步骤2:调整when条件
根据调试结果选择以下方案之一:
方案A:匹配远程分支名(适用于分离HEAD状态)
改用expression条件直接匹配GIT_BRANCH变量:
stage('tf-apply') { when { expression { env.GIT_BRANCH == 'origin/check-branch' } } steps { dir('dr') { input message: 'Do you want to apply this plan ? ', ok: 'Deploy' sh 'terraform apply -input=false -auto-approve plan.out' } } }
方案B:创建本地分支后匹配
如果希望继续使用branch条件,需在检出代码时创建本地分支,确保BRANCH_NAME为预期值:
stage('Checkout') { steps { // 直接检出并创建本地check-branch分支 git branch: 'check-branch', url: 'https:/serv/repo.git' } } stage('tf-apply') { when { branch 'check-branch' } steps { dir('dr') { input message: 'Do you want to apply this plan ? ', ok: 'Deploy' sh 'terraform apply -input=false -auto-approve plan.out' } } }
内容的提问来源于stack exchange,提问作者Jason Stanley
相关产品推荐
相关产品推荐

