0
0
Jenkinsdevops~30 mins

Jenkinsfile per branch - Mini Project: Build & Apply

Choose your learning style9 modes available
Jenkinsfile per branch
📖 Scenario: You work in a team where each Git branch needs its own Jenkins pipeline configuration. This helps run different build steps depending on the branch.
🎯 Goal: Create a Jenkinsfile that runs different stages based on the current Git branch name.
📋 What You'll Learn
Create a variable to hold the current Git branch name
Create a variable to hold the build stage name based on the branch
Use a when condition to run a stage only on the main branch
Print the branch name and the selected build stage
💡 Why This Matters
🌍 Real World
Teams often need different build or test steps for different branches, like main, develop, or feature branches. This Jenkinsfile setup helps automate that.
💼 Career
Knowing how to customize Jenkins pipelines per branch is a key skill for DevOps engineers and CI/CD pipeline developers.
Progress0 / 4 steps
1
Get the current Git branch name
Create a variable called branchName that gets the current Git branch name using env.BRANCH_NAME.
Jenkins
Need a hint?

The current branch name is stored in env.BRANCH_NAME.

2
Set build stage name based on branch
Add a variable called buildStage in the environment section. Set it to "Build Main" if branchName is "main", otherwise set it to "Build Feature".
Jenkins
Need a hint?

Use a ternary operator to set buildStage based on branchName.

3
Add a stage that runs only on main branch
Add a stage named Build Main that runs only when branchName is "main". Use the when directive with expression { branchName == 'main' }. Inside the stage, add a steps block with a echo command that prints "Building main branch".
Jenkins
Need a hint?

The when directive controls if a stage runs. Use expression { branchName == 'main' } to check the branch.

4
Print the branch and build stage
Add a stage named Print Info that runs on all branches. Inside steps, add two echo commands: one to print "Current branch: ${branchName}" and another to print "Selected build stage: ${buildStage}".
Jenkins
Need a hint?

Use echo inside steps to print variables with ${} syntax.