semural
semural

Reputation: 4631

Jenkins Declarative Pipeline Using When Condition For Branch Name

I am using Jenkins declarative pipeline and I would like to deploy my application according to the git branch. Even branch information in Jenkins and when condition matches, Jenkins says: *"skipped Deploy to dev stage due to when conditional" It is same as for test branch when the branch is test. How should I fix this issue?

Note: Branches to build in project configuration settings set like */develop , */test , */master and and Jenkins can trigger when I push my code to dev or test branch.

stage('Deploy to dev'){
        when{
            beforeAgent true
            anyOf{
                branch "origin/develop"
            }
        }
    stage('Deploy to staging'){
        when{
            beforeAgent true
            anyOf{
                branch "origin/test"
            }
        }

Console Output

           +refs/heads/*:refs/remotes/origin/*
            Seen branch in repository origin/develop
            Seen branch in repository origin/master
            Seen branch in repository origin/test
            Seen 3 remote branches
             > git show-ref --tags -d # timeout=10
            Checking out Revision 5ebda79eb3a50a578786e75587f7d92dfc399122 (origin/develop)

           [Pipeline] { (Deploy to dev)
           Stage "Deploy to dev" skipped due to when conditional

           Stage "Deploy to staging" skipped due to when conditional

Upvotes: 3

Views: 5978

Answers (1)

fredericrous
fredericrous

Reputation: 3038

is variable BRANCH_NAME defined? This variable is used by the when step.

Did you use the (github) multibranch plugin that sets this variable automatically? Do a println to see if it is defined.

to set this variable, here is what I do in my build stage

  stage('Build') {
            steps {
                script {
                    def commit = checkout scm
                    // we set BRANCH_NAME to make when { branch } syntax work without multibranch job
                    env.BRANCH_NAME = commit.GIT_BRANCH.replace('origin/', '')

                    //actually build ...
                }
            }
        }

Upvotes: 2

Related Questions