0
0
Jenkinsdevops~30 mins

Stage conditions with when directive in Jenkins - Mini Project: Build & Apply

Choose your learning style9 modes available
Stage conditions with when directive
📖 Scenario: You are setting up a Jenkins pipeline for a simple project. You want to control which stages run based on the branch name. This helps avoid running unnecessary steps on branches where they are not needed.
🎯 Goal: Build a Jenkins pipeline script with two stages. The first stage always runs. The second stage runs only when the branch is main. You will use the when directive to add this condition.
📋 What You'll Learn
Create a Jenkins pipeline with two stages named Build and Deploy
The Build stage should always run
The Deploy stage should run only when the branch is main
Use the when directive with branch 'main' condition
Print simple messages in each stage to show they ran
💡 Why This Matters
🌍 Real World
In real projects, controlling which stages run based on branch names helps save time and resources by skipping unnecessary steps on feature or development branches.
💼 Career
Understanding Jenkins pipeline conditions is essential for DevOps roles to automate builds and deployments efficiently and safely.
Progress0 / 4 steps
1
Create the basic pipeline with a Build stage
Write a Jenkins pipeline script that defines a pipeline block with an agent any and a single stage named Build. Inside the Build stage, add a steps block that runs echo 'Building the project'.
Jenkins
Need a hint?

Use pipeline and agent any to start. Then add one stage named Build with steps that echo a message.

2
Add a Deploy stage with a when condition
Add a second stage named Deploy after the Build stage. Inside the Deploy stage, add a when directive that runs the stage only when the branch is main. Use branch 'main' inside when. Add a steps block that runs echo 'Deploying to production'.
Jenkins
Need a hint?

Use when { branch 'main' } inside the Deploy stage to run it only on the main branch.

3
Add an environment variable for the branch name
Inside the pipeline block but outside stages, add an environment block that defines a variable BRANCH_NAME set to env.BRANCH_NAME. This will hold the current branch name.
Jenkins
Need a hint?

Use environment { BRANCH_NAME = env.BRANCH_NAME } inside the pipeline block to capture the branch name.

4
Print the branch name in the Build stage
Inside the Build stage's steps block, add a line to print the branch name using echo "Building branch: ${BRANCH_NAME}".
Jenkins
Need a hint?

Use echo "Building branch: ${BRANCH_NAME}" inside the Build stage's steps to show the branch name.