Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 910
semural Avatar asked Nov 21 '25 21:11

semural


1 Answers

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 ...
                }
            }
        }
like image 118
fredericrous Avatar answered Nov 23 '25 11:11

fredericrous



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!