Consider this Jenkins pipeline script snippet that decides deployment based on branch name:
pipeline {
agent any
stages {
stage('Deploy') {
when {
expression { env.BRANCH_NAME == 'main' }
}
steps {
echo 'Deploying to production!'
}
}
}
}If the pipeline runs on branch feature-xyz, what will be the output?
pipeline {
agent any
stages {
stage('Deploy') {
when {
expression { env.BRANCH_NAME == 'main' }
}
steps {
echo 'Deploying to production!'
}
}
}
}Think about the when condition and the branch name.
The when condition checks if BRANCH_NAME is 'main'. Since the branch is 'feature-xyz', the condition is false, so the 'Deploy' stage is skipped and nothing is printed.
You want to deploy your application only when a Git tag starts with the letter 'v' (e.g., 'v1.0'). Which when condition snippet achieves this?
Tags can be matched with regex patterns in Jenkins when conditions.
Option A uses the tag condition with a regex pattern to match tags starting with 'v'. Option A would fail if TAG_NAME is undefined. Options B and D are invalid syntax for tags.
Given a Jenkins pipeline with stages for build, test, and deploy, you want to deploy only if tests pass and the branch is 'release'. Which snippet correctly implements this logic?
Use a single expression combining both conditions for clarity.
Option A correctly uses a single expression checking both that the build succeeded and the branch is 'release'. Option A uses allOf but currentBuild.result may not be set at that point. Option A uses anyOf which allows deployment if either condition is true, which is incorrect. Option A mixes not and branch incorrectly.
Look at this Jenkins pipeline snippet:
pipeline {
agent any
stages {
stage('Deploy') {
when {
branch 'main'
}
steps {
echo 'Deploying to production'
}
}
}
}Even when running on the 'main' branch, the 'Deploy' stage is skipped. What is the most likely cause?
pipeline {
agent any
stages {
stage('Deploy') {
when {
branch 'main'
}
steps {
echo 'Deploying to production'
}
}
}
}Check if the pipeline environment has the branch name variable set.
The branch condition depends on the BRANCH_NAME environment variable, which Jenkins sets automatically for multibranch pipelines. If running a simple pipeline without this variable, the condition always fails, skipping the stage.
To avoid accidental deployments, you want to deploy only when all tests pass, the branch is 'main', and a manual approval is given. Which Jenkins pipeline snippet best implements this?
Manual approval should be a step, not part of the when condition.
Option B correctly places the manual approval input step inside steps after the when condition. Option B incorrectly places when inside steps. Option B tries to use input inside when, which is invalid. Option B requests approval after deployment, which is unsafe.