0
0
Jenkinsdevops~30 mins

Groovy methods in pipelines in Jenkins - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Groovy Methods in Jenkins Pipelines
📖 Scenario: You are setting up a Jenkins pipeline to automate a simple build process. To keep your pipeline clean and reusable, you want to define a Groovy method inside the pipeline script that prints a welcome message with the project name.
🎯 Goal: Build a Jenkins pipeline script that defines a Groovy method called printWelcome which takes a project name as input and prints a welcome message. Then call this method in the pipeline to display the message.
📋 What You'll Learn
Create a Groovy method named printWelcome that accepts one parameter projectName
Inside the method, print the message: "Welcome to the project: <projectName>"
Call the printWelcome method inside the pipeline script with the project name "MyApp"
Use a pipeline block with agent any and a stage named "Greeting"
Print the output to the Jenkins console log
💡 Why This Matters
🌍 Real World
In real Jenkins pipelines, defining Groovy methods helps organize repeated tasks like notifications, validations, or formatting logs.
💼 Career
Knowing how to write and call Groovy methods in Jenkins pipelines is essential for DevOps engineers to create maintainable and scalable CI/CD workflows.
Progress0 / 4 steps
1
Create the Groovy method printWelcome
Define a Groovy method called printWelcome that takes one parameter named projectName. Inside the method, use echo to print the message "Welcome to the project: <projectName>".
Jenkins
Need a hint?

Use def to define the method and echo to print inside Jenkins pipeline.

2
Set up the Jenkins pipeline skeleton
Create a pipeline block with agent any and a stage named "Greeting". Inside the stage, add a steps block.
Jenkins
Need a hint?

Use the pipeline syntax with agent any and define a stage called Greeting.

3
Call the printWelcome method inside the pipeline
Inside the steps block of the Greeting stage, call the printWelcome method with the argument "MyApp".
Jenkins
Need a hint?

Use a script block inside steps to call the Groovy method.

4
Run the pipeline and display the output
Run the pipeline script. The Jenkins console log should display the message Welcome to the project: MyApp. Add a print statement if needed to show the output.
Jenkins
Need a hint?

Check the Jenkins console output after running the pipeline to see the welcome message.