Bird
Raised Fist0
Jenkinsdevops~10 mins

Creating reusable pipeline steps in Jenkins - Visual Walkthrough

Choose your learning style10 modes available
Process Flow - Creating reusable pipeline steps
Define reusable step as function
↓
Call reusable step in pipeline
↓
Step executes with given parameters
↓
Pipeline continues or ends
First, define a reusable step as a function. Then call it in the pipeline with parameters. The step runs and the pipeline continues.
Execution Sample
Jenkins
def greet(name) {
  echo "Hello, ${name}!"
}

pipeline {
  agent any
  stages {
    stage('Greet') {
      steps {
        script {
          greet('Alice')
        }
      }
    }
  }
}
This pipeline defines a reusable step 'greet' and calls it with 'Alice' to print a greeting.
Process Table
StepActionEvaluationResult
1Define function greet(name)Function storedgreet available
2Start pipeline executionAgent allocatedPipeline running
3Enter stage 'Greet'Stage startedReady to run steps
4Call greet('Alice')Substitute name='Alice'echo "Hello, Alice!"
5Execute echoPrint messageConsole shows: Hello, Alice!
6Stage endsStage completePipeline continues or ends
💡 Pipeline finishes after all stages complete
Status Tracker
VariableStartAfter Step 4After Step 5Final
nameundefined'Alice''Alice''Alice'
Key Moments - 3 Insights
Why do we define the reusable step outside the pipeline block?
Defining the function outside the pipeline block makes it available to all stages and steps, as shown in Step 1 of the execution_table.
What happens if we call the reusable step with a different name?
The function uses the passed parameter each time, so the greeting changes accordingly, as seen in Step 4 where 'Alice' is substituted.
Can we reuse the step multiple times in the pipeline?
Yes, you can call the function multiple times with different parameters, each call executing the echo with the new value.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at Step 4. What is the value of 'name' when greet is called?
Aundefined
B'Alice'
C'greet'
D'Hello, Alice!'
💡 Hint
Check the 'Evaluation' column in Step 4 where name='Alice' is substituted.
At which step does the message 'Hello, Alice!' appear in the console?
AStep 5
BStep 3
CStep 4
DStep 6
💡 Hint
Look at the 'Result' column in Step 5 where the echo prints the message.
If we define the function inside the pipeline block, what likely happens?
APipeline runs faster
BFunction is available globally
CFunction is not recognized when called
DPipeline skips the function
💡 Hint
Refer to key_moments about function scope and Step 1 in execution_table.
Concept Snapshot
Creating reusable pipeline steps in Jenkins:
- Define a function outside the pipeline block
- Call the function inside pipeline steps
- Pass parameters to customize behavior
- Function runs and outputs results
- Reuse functions to avoid repeating code
Full Transcript
In Jenkins pipelines, you create reusable steps by defining functions outside the pipeline block. These functions take parameters and can be called inside pipeline stages. When the pipeline runs, it calls the function with given arguments, executes the code inside, and continues. This helps avoid repeating code and makes pipelines cleaner and easier to maintain.

Practice

(1/5)
1. What is the main benefit of creating reusable pipeline steps in Jenkins?
easy
A. It automatically fixes syntax errors.
B. It makes the pipeline run faster.
C. It reduces code duplication and simplifies maintenance.
D. It disables pipeline notifications.

Solution

  1. Step 1: Understand the purpose of reusable steps

    Reusable steps are designed to avoid repeating the same code multiple times in pipelines.
  2. Step 2: Identify the main advantage

    By reusing code, maintenance becomes easier because changes are made in one place, reducing errors and effort.
  3. Final Answer:

    It reduces code duplication and simplifies maintenance. -> Option C
  4. Quick Check:

    Reusable steps = less duplication [OK]
Hint: Think about saving time and effort by reusing code [OK]
Common Mistakes:
  • Confusing speed improvement with code reuse
  • Assuming reusable steps fix errors automatically
  • Believing reusable steps control notifications
2. Which syntax correctly defines a reusable step named buildApp in a Jenkins pipeline?
easy
A. def buildApp() { echo 'Building app...' }
B. buildApp() { echo 'Building app...' }
C. function buildApp { echo 'Building app...' }
D. step buildApp() { echo 'Building app...' }

Solution

  1. Step 1: Recall Groovy function syntax in Jenkins

    Reusable steps are defined as Groovy functions using the def keyword followed by the function name and parentheses.
  2. Step 2: Match the correct syntax

    def buildApp() { echo 'Building app...' } uses def buildApp() { ... } which is the correct Groovy function definition.
  3. Final Answer:

    def buildApp() { echo 'Building app...' } -> Option A
  4. Quick Check:

    Groovy functions start with def [OK]
Hint: Look for 'def' keyword to define functions in Jenkinsfile [OK]
Common Mistakes:
  • Omitting 'def' keyword
  • Using JavaScript or shell syntax
  • Using unsupported keywords like 'step' or 'function'
3. Given the reusable step below, what will be the output when calling buildApp('Test')?
def buildApp(String env) {
  echo "Building for ${env} environment"
}

pipeline {
  agent any
  stages {
    stage('Build') {
      steps {
        script {
          buildApp('Test')
        }
      }
    }
  }
}
medium
A. No output
B. Building for Test environment
C. Error: Missing parameter
D. Building for env environment

Solution

  1. Step 1: Understand the function call with parameter

    The function buildApp takes a string parameter env and prints a message including it.
  2. Step 2: Substitute the parameter value

    Calling buildApp('Test') replaces ${env} with 'Test', so the output is 'Building for Test environment'.
  3. Final Answer:

    Building for Test environment -> Option B
  4. Quick Check:

    Parameter substitution = correct output [OK]
Hint: Replace variables with passed arguments to find output [OK]
Common Mistakes:
  • Ignoring parameter substitution
  • Assuming default or missing parameter error
  • Thinking no output occurs without explicit return
4. Identify the error in this reusable step definition:
def deployApp(env) {
  echo "Deploying to ${environment}"
}

pipeline {
  agent any
  stages {
    stage('Deploy') {
      steps {
        script {
          deployApp('production')
        }
      }
    }
  }
}
medium
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

  1. Step 1: Check parameter usage inside function

    The function defines parameter env but uses ${environment} inside the echo, which is undefined.
  2. Step 2: Identify the mismatch causing error

    This mismatch causes a runtime error because environment is not declared or passed.
  3. Final Answer:

    Parameter name mismatch: 'env' vs 'environment' inside echo -> Option A
  4. 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!' } }
D. def notifyBuild(String status) { if (status == 'SUCCESS') { echo 'Build succeeded!' } else { echo 'Build failed!' } }

Solution

  1. Step 1: Review correct Groovy conditional syntax

    Groovy uses if (condition) { ... } with double equals == for comparison.
  2. Step 2: Analyze each option

    def notifyBuild(String status) { if (status == 'SUCCESS') { echo 'Build succeeded!' } else { echo 'Build failed!' } } uses correct parameter typing, if-else structure, and comparison operator.
    def notifyBuild(status) { switch (status) { case 'SUCCESS': echo 'Build succeeded!' case 'FAILURE': echo 'Build failed!' } } misses breaks in switch, causing fall-through.
    def notifyBuild(String status) { match (status) { 'SUCCESS' -> echo 'Build succeeded!' 'FAILURE' -> echo 'Build failed!' } } uses invalid 'match' syntax in Groovy.
    def notifyBuild(String status) { if status = 'SUCCESS' { echo 'Build succeeded!' } else { echo 'Build failed!' } } uses single equals = instead of == in if condition, causing assignment error.
  3. Final Answer:

    def notifyBuild(String status) { if (status == 'SUCCESS') { echo 'Build succeeded!' } else { echo 'Build failed!' } } -> Option D
  4. Quick Check:

    Use if (condition == value) for Groovy conditionals [OK]
Hint: Use if with double equals (==) for conditions in Groovy [OK]
Common Mistakes:
  • Using single equals (=) instead of double (==) in conditions
  • Using unsupported 'match' syntax
  • Missing breaks in switch causing fall-through
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard