Bird
Raised Fist0
Jenkinsdevops~5 mins

Branch-specific pipeline behavior in Jenkins - Commands & Configuration

Choose your learning style10 modes available
Introduction
Sometimes you want your Jenkins pipeline to do different things depending on which branch of your code you are working on. This helps you test new features safely or deploy only from the main branch.
When you want to run tests only on feature branches but deploy only from the main branch.
When you want to build a different version of your app for development and production branches.
When you want to skip certain steps like deployment on pull request branches.
When you want to notify different teams depending on the branch being built.
When you want to run security scans only on release branches.
Config File - Jenkinsfile
Jenkinsfile
pipeline {
  agent any
  stages {
    stage('Build') {
      steps {
        echo "Building on branch ${env.BRANCH_NAME}"
      }
    }
    stage('Test') {
      when {
        anyOf {
          branch 'feature/*'
          branch 'develop'
        }
      }
      steps {
        echo 'Running tests on feature or develop branches'
      }
    }
    stage('Deploy') {
      when {
        branch 'main'
      }
      steps {
        echo 'Deploying from main branch'
      }
    }
  }
}

This Jenkinsfile defines a pipeline with three stages: Build, Test, and Deploy.

The when condition controls which branches run each stage:

  • Test runs only on branches named like feature/* or develop.
  • Deploy runs only on the main branch.

This lets you customize pipeline behavior based on the branch name.

Commands
Create and switch to a new feature branch named 'feature/new-ui' to simulate working on a feature.
Terminal
git checkout -b feature/new-ui
Expected OutputExpected
Switched to a new branch 'feature/new-ui'
Push the new feature branch to the remote repository so Jenkins can detect it and run the pipeline.
Terminal
git push origin feature/new-ui
Expected OutputExpected
Enumerating objects: 3, done. Counting objects: 100% (3/3), done. Writing objects: 100% (3/3), 250 bytes | 250.00 KiB/s, done. Total 3 (delta 0), reused 0 (delta 0), pack-reused 0 remote: remote: Create a pull request for 'feature/new-ui' on GitHub by visiting: remote: https://github.com/example/repo/pull/new/feature/new-ui remote: To https://github.com/example/repo.git * [new branch] feature/new-ui -> feature/new-ui
Trigger the Jenkins pipeline manually for the 'feature/new-ui' branch to see branch-specific behavior.
Terminal
jenkins build example-pipeline -p BRANCH_NAME=feature/new-ui
Expected OutputExpected
[Pipeline] Start of Pipeline [Pipeline] echo Building on branch feature/new-ui [Pipeline] echo Running tests on feature or develop branches [Pipeline] End of Pipeline
→
-p BRANCH_NAME=feature/new-ui - Sets the branch name environment variable for the pipeline
Trigger the Jenkins pipeline manually for the 'main' branch to see the deploy stage run.
Terminal
jenkins build example-pipeline -p BRANCH_NAME=main
Expected OutputExpected
[Pipeline] Start of Pipeline [Pipeline] echo Building on branch main [Pipeline] echo Deploying from main branch [Pipeline] End of Pipeline
→
-p BRANCH_NAME=main - Sets the branch name environment variable for the pipeline
Key Concept

If you remember nothing else from this pattern, remember: use the 'when' directive in Jenkins pipelines to run different steps based on the branch name.

Common Mistakes
Not setting the BRANCH_NAME environment variable when testing locally.
The pipeline uses BRANCH_NAME to decide which stages to run, so missing it causes all stages to run or fail conditions.
Always set BRANCH_NAME when triggering the pipeline manually or in scripts.
Using exact branch names without wildcards for feature branches.
Feature branches often have different names, so exact matches miss many branches.
Use wildcard patterns like 'feature/*' to match all feature branches.
Placing 'when' conditions inside 'steps' instead of at the stage level.
'when' only works at the stage level and will be ignored or cause errors if used inside steps.
Always put 'when' directly under the stage, not inside steps.
Summary
Use the 'when' directive in Jenkinsfile stages to control execution based on branch names.
Test stages can run on feature or develop branches using wildcard branch patterns.
Deploy stages should run only on the main branch to avoid accidental deployments.

Practice

(1/5)
1.

Which Jenkins pipeline syntax runs a stage only on the main branch?

easy
A. branch == 'main' { runStage() }
B. if (branch == 'main')
C. onlyIf branch == 'main'
D. when { branch 'main' }

Solution

  1. Step 1: Understand Jenkins branch condition syntax

    Jenkins uses when { branch 'branchName' } to run stages on specific branches.
  2. Step 2: Match syntax to run on main branch

    The correct syntax is when { branch 'main' } to target the main branch.
  3. Final Answer:

    when { branch 'main' } -> Option D
  4. Quick Check:

    Branch condition = when { branch 'main' } [OK]
Hint: Use 'when { branch "branchName" }' for branch-specific stages [OK]
Common Mistakes:
  • Using if statements instead of 'when' block
  • Incorrect syntax like 'onlyIf' or inline conditions
  • Confusing branch name quotes or missing quotes
2.

Which snippet correctly uses Jenkins declarative pipeline syntax to run a stage only on branches dev or feature/*?

stage('Test') {
  when {
    ???
  }
  steps {
    echo 'Running tests'
  }
}
easy
A. anyOf { branch 'dev'; branch 'feature/*' }
B. branch 'dev' && branch 'feature/*'
C. allOf { branch 'dev'; branch 'feature/*' }
D. branch 'dev' || branch 'feature/*'

Solution

  1. Step 1: Identify correct syntax for multiple branch conditions

    Jenkins uses anyOf { branch 'name'; branch 'pattern' } to run if any branch matches.
  2. Step 2: Choose syntax matching either 'dev' or 'feature/*'

    Using anyOf { branch 'dev'; branch 'feature/*' } runs the stage on either branch.
  3. Final Answer:

    anyOf { branch 'dev'; branch 'feature/*' } -> Option A
  4. Quick Check:

    Multiple branches = anyOf with branch conditions [OK]
Hint: Use anyOf { branch 'x'; branch 'y' } for multiple branches [OK]
Common Mistakes:
  • Using logical operators like || or && directly inside when
  • Using allOf which requires all conditions true
  • Incorrect syntax without braces or semicolons
3.

Given this Jenkins pipeline snippet, what will be the output if the branch is feature/login?

pipeline {
  agent any
  stages {
    stage('Build') {
      when { branch 'main' }
      steps { echo 'Building main branch' }
    }
    stage('Test') {
      when { branch 'feature/*' }
      steps { echo 'Testing feature branch' }
    }
  }
}
medium
A. Testing feature branch
B. Building main branch
C. Building main branch\nTesting feature branch
D. No output

Solution

  1. Step 1: Check branch conditions for each stage

    'Build' runs only on 'main' branch; 'Test' runs on branches matching 'feature/*'.
  2. Step 2: Match current branch 'feature/login'

    'feature/login' matches 'feature/*', so only 'Test' stage runs and prints 'Testing feature branch'.
  3. Final Answer:

    Testing feature branch -> Option A
  4. Quick Check:

    Branch 'feature/login' matches 'feature/*' only [OK]
Hint: Match branch patterns carefully to predict stage execution [OK]
Common Mistakes:
  • Assuming 'main' stage runs on all branches
  • Ignoring wildcard pattern matching
  • Expecting both stages to run always
4.

Identify the error in this Jenkins pipeline snippet that tries to run a stage only on the release branch:

stage('Deploy') {
  when {
    branch release
  }
  steps {
    echo 'Deploying release branch'
  }
}
medium
A. Steps block should be outside the stage
B. Incorrect stage name 'Deploy'
C. Missing quotes around branch name in when condition
D. Branch condition should be inside steps

Solution

  1. Step 1: Review syntax for branch condition in when block

    The branch name must be a string inside quotes: branch 'release'.
  2. Step 2: Identify missing quotes causing syntax error

    Here, branch release lacks quotes, causing a syntax error.
  3. Final Answer:

    Missing quotes around branch name in when condition -> Option C
  4. Quick Check:

    Branch names need quotes in when { branch 'name' } [OK]
Hint: Always quote branch names in when { branch 'name' } [OK]
Common Mistakes:
  • Omitting quotes around branch names
  • Placing steps outside stage block
  • Misplacing branch condition inside steps
5.

You want a Jenkins pipeline stage to run on all branches except main and develop. Which when condition correctly implements this?

hard
A. allOf { not branch 'main'; not branch 'develop' }
B. not { anyOf { branch 'main'; branch 'develop' } }
C. anyOf { not branch 'main'; not branch 'develop' }
D. branch != 'main' && branch != 'develop'

Solution

  1. Step 1: Understand negation of multiple branches

    To exclude branches, wrap the branches in anyOf and negate with not.
  2. Step 2: Apply correct syntax for excluding 'main' and 'develop'

    not { anyOf { branch 'main'; branch 'develop' } } runs on all branches except these two.
  3. Final Answer:

    not { anyOf { branch 'main'; branch 'develop' } } -> Option B
  4. Quick Check:

    Exclude branches = not { anyOf { ... } } [OK]
Hint: Use not { anyOf { branch 'x'; branch 'y' } } to exclude branches [OK]
Common Mistakes:
  • Using allOf with negations incorrectly
  • Using logical operators like && directly
  • Misplacing not inside anyOf instead of outside
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard