📖 Scenario: You are working on a Jenkins pipeline for a software project. You want to create reusable steps to avoid repeating the same code multiple times. This will make your pipeline cleaner and easier to maintain.
🎯 Goal: Build a Jenkins pipeline script that defines a reusable step called greet which prints a greeting message with a given name. Then use this step twice with different names.
📋 What You'll Learn
Define a reusable step called greet that takes a parameter name
The greet step should print 'Hello, <name>!'
Call the greet step twice with names 'Alice' and 'Bob'
Use declarative pipeline syntax
💡 Why This Matters
🌍 Real World
Reusable pipeline steps save time and reduce errors by avoiding repeated code in Jenkins pipelines.
💼 Career
DevOps engineers often create reusable pipeline steps to maintain clean, efficient CI/CD workflows.
Progress0 / 4 steps
1
Create a basic Jenkins pipeline
Write a Jenkins declarative pipeline with a pipeline block and an empty stages section.
Jenkins
Hint
Start with pipeline { agent any stages { } structure.
2
Define a reusable step called greet
Inside the pipeline block but outside stages, define a def greet(name) function that prints 'Hello, <name>!'.
Jenkins
Hint
Use def greet(name) { echo "Hello, ${name}!" } syntax.
3
Call the greet step twice in a stage
Add a stage named GreetUsers inside stages. Inside its steps, call greet('Alice') and greet('Bob').
A. Parameter name mismatch: 'env' vs 'environment' inside echo
B. Missing 'def' keyword before function name
C. Incorrect pipeline syntax: missing agent label
D. Function call missing parentheses
Solution
Step 1: Check parameter usage inside function
The function defines parameter env but uses ${environment} inside the echo, which is undefined.
Step 2: Identify the mismatch causing error
This mismatch causes a runtime error because environment is not declared or passed.
Final Answer:
Parameter name mismatch: 'env' vs 'environment' inside echo -> Option A
Quick Check:
Parameter names must match exactly [OK]
Hint: Match parameter names exactly inside function body [OK]
Common Mistakes:
Using different variable names inside function
Omitting 'def' keyword (not the issue here)
Incorrect pipeline syntax unrelated to function
5. You want to create a reusable step notifyBuild that sends different messages based on build status. Which code snippet correctly implements this using parameters and conditional logic?
hard
A. def notifyBuild(String status) {
match (status) {
'SUCCESS' -> echo 'Build succeeded!'
'FAILURE' -> echo 'Build failed!'
}
}
B. def notifyBuild(status) {
switch (status) {
case 'SUCCESS': echo 'Build succeeded!'
case 'FAILURE': echo 'Build failed!'
}
}
C. def notifyBuild(String status) {
if status = 'SUCCESS' {
echo 'Build succeeded!'
} else {
echo 'Build failed!'
}
}