Jenkins multibranch pipeline triggers pipeline on unrelated branches Jenkins multibranch pipeline triggers pipeline on unrelated branches jenkins jenkins

Jenkins multibranch pipeline triggers pipeline on unrelated branches


I use this plugin - https://github.com/lachie83/jenkins-pipeline and it works fine for me. You need to have separate if blocks for each branch and then the stage block inside it. Example below:

#!/usr/bin/groovy@Library('https://github.com/lachie83/jenkins-pipeline@master')def pipeline = new io.estrado.Pipeline()def cloud = pipeline.getCloud(env.BRANCH_NAME)def label = pipeline.getPodLabel(cloud)// deploy only the staging branchif (env.BRANCH_NAME == 'staging') {    stage ('deploy to k8s staging') {      //Deploy to staging    }}// deploy only the master branchif (env.BRANCH_NAME == 'master') {    stage ('deploy to k8s production') {      //Deploy to production    }}


I think you have some logical omissions in your Jenkinsfile. As it currently stands, you poll SCM for changes. If any change is detected, first stage 'Git Checkout' will checkout staging branch (always). Then you have another stage which does something if the branch is 'staging' (which it is, because it's hardcoded to checkout that branch above) etc. This will be the first thing to fix - if SCM changes are detected, checkout the right branch. How - there are a few options. I usually use 'skipDefaultCheckout()' in 'options' together with explicit checkout in my first pipeline stage:

        steps {            sshagent(['github-creds']) {                git branch: "${env.BRANCH_NAME}", credentialsId: 'github-creds', url: 'git@github.com:x/y.git'            }        }

The second thing is that you try to squeeze handling two different branches into a single Jenkinsfile. This is not how it should be done. Jenkins wil use Jenkinsfile from a given branch - just make sure Jenkinsfile on staging contains what you want it to contain, same with Jenkinsfile on master.

Hope it helps.