Complete the code to use a parameter instead of a hard-coded value in Jenkins pipeline.
pipeline {
agent any
parameters {
string(name: 'BRANCH', defaultValue: '[1]', description: 'Git branch to build')
}
stages {
stage('Build') {
steps {
echo "Building branch: ${params.BRANCH}"
}
}
}
}The default branch name is usually 'master' in many repositories. Using a parameter allows changing it without editing the pipeline code.
Complete the code to read the environment variable instead of hard-coding the Docker image name.
pipeline {
agent any
environment {
IMAGE_NAME = '[1]'
}
stages {
stage('Build') {
steps {
echo "Using image: ${env.IMAGE_NAME}"
}
}
}
}Environment variables are usually uppercase with underscores. Using 'DOCKER_IMAGE' follows this convention and avoids hard-coding.
Fix the error in the code by replacing the hard-coded timeout value with a parameter.
pipeline {
agent any
parameters {
string(name: 'TIMEOUT_MINUTES', defaultValue: '30', description: 'Timeout in minutes')
}
stages {
stage('Test') {
steps {
timeout(time: [1], unit: 'MINUTES') {
echo 'Running tests'
}
}
}
}
}To use a parameter value in Jenkins pipeline, you access it via 'params.PARAM_NAME'. This replaces the hard-coded timeout value.
Fill both blanks to replace hard-coded credentials with Jenkins credentials binding.
pipeline {
agent any
environment {
USERNAME = credentials('[1]')
PASSWORD = credentials('[2]')
}
stages {
stage('Deploy') {
steps {
echo "Deploying with user ${env.USERNAME}"
}
}
}
}Jenkins credentials are referenced by their IDs, which are usually uppercase with underscores. Using 'DEPLOY_USER' and 'DEPLOY_PASS' avoids hard-coding sensitive data.
Fill all three blanks to create a map of environment variables avoiding hard-coded values.
pipeline {
agent any
environment {
vars = [
'[1]': params.BRANCH,
'[2]': env.DOCKER_IMAGE,
'[3]': credentials('DEPLOY_PASS')
]
}
stages {
stage('Print Vars') {
steps {
echo "Branch: ${vars.BRANCH_NAME}, Image: ${vars.IMAGE_NAME}, Password: ${vars.PASSWORD}"
}
}
}
}The keys in the map should be descriptive environment variable names. Using 'BRANCH_NAME', 'IMAGE_NAME', and 'PASSWORD' avoids hard-coded strings and improves clarity.