jenkinsjenkins-pipeline

Jenkinsfile is not respecting when statement to choose correct branch


I have a jenkins file stage which should run only when the branch is check-branch branch.

        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'
                }
            }
        }

The jenkins pipeline output for git checkout is

Fetching changes from the remote Git repository
 > git rev-parse --resolve-git-dir /home/jenkins/workspace/tempp/.git # timeout=10
 > git config remote.origin.url https:/serv/repo.git # timeout=10
Fetching upstream changes from https:/serv/repo.git
 > git --version # timeout=10
 > git --version # 'git version 2.43.5'
using GIT_ASKPASS to set credentials 
 > git fetch --tags --force --progress -- https:/serv/repo.git +refs/heads/*:refs/remotes/origin/* # timeout=10
Checking out Revision b92c212294863de300ddf5232ed635798999c71b (origin/check-branch)
Seen branch in repository origin/check-branch
Seen branch in repository origin/fix-branch
Seen branch in repository origin/main
Seen branch in repository origin/run-apply
Seen 4 remote branches
 > git show-ref --tags -d # timeout=10
Commit message: "Update Jenkinsfile"

The jenkins pipeline output for that specific stage is

[Pipeline] stage
[Pipeline] { (Print Branch Name)
[Pipeline] script
[Pipeline] {
[Pipeline] echo
Current branch is: origin/check-branch
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (tf-apply)
Stage "tf-apply" skipped due to when conditional
[Pipeline] getContext
[Pipeline] }
[Pipeline] // stage
[Pipeline] }

I have also tried to do

        stage('tf-apply') {
            when {
                    branch 'origin/check-branch'
            }

But that also gets skipped. What am I missing here ?


Solution

  • You are probably using a normal pipeline job, not a multibranch pipeline? See the documentation

    Note that this only works on a multibranch Pipeline.