Logesh Sakthivel
Posted on July 12, 2023
In this article, we are going to write a simple Jenkins Pipeline script using some variables and functions that runs on the Agent we specify using the label.
The main goal of this article is to use variables,functions and agent labels in the Pipeline script.
There are two ways of defining the Pipeline script in the Pipeline project.
- Directly writing the Script in the Pipeline section while creating the Pipeline Project.
- Pipeline Script from SCM (Source Code Management) using Jenkinsfile.
In this article we will be following the First way(Pipeline script).
Pipeline Script
Create Pipeline
In the Jenkins Dashboard, click New Item and create a Pipeline Project.
Scroll down, in the Pipeline section we are going to write our Pipeline Script(Groovy).
Pipeline Script
Simple pipeline script that executes bash commands in the agent that I specified.
pipeline {
agent {
label "ubuntu"
}
environment {
def myString = "Hello World"
def myNumber = 10
def myBool = true
}
stages{
stage("Node Info") {
steps {
echo "Node name $NODE_NAME and the labels: $NODE_LABELS"
}
}
stage("Basic shell cmds") {
steps {
executeBasicShellCmds()
}
}
stage("Variables") {
steps {
echo "myString: ${myString}"
echo "myNumber: ${myNumber}"
echo "myBool: ${myBool}"
}
}
}
}
def executeBasicShellCmds(){
sh """
pwd
ls -a
uname
whoami
"""
}
Pipeline Script breakdown
All the pipeline related stuffs comes within the pipeline block. Fucntions will be written outside the pipeline block.
To define a Pipeline,
pipeline{
....
}
To define variables,
environment {
def myString = "Hello World"
def myNumber = 10
def myBool = true
}
To define the stages(Pipeline stages),
stages{
stage("Stage 1") {
steps {
...
}
}
stage("Stage 2") {
steps {
...
}
}
}
The functions should be defined outside the pipeline block.
To define a function with and without parameters,
def func1(){
echo "function 1"
}
def func2(String a){
echo "${a}"
}
Click save.
Build Now
In the Project's page click on Build Now to build the Project.
You can see the Build status on Stage view or in the Build history
Click on the each stage to view the logs.
In this article, we have learned how to use the Pipeline script in the Pipeline project with the simple pipeline script.
Happie Learning :)
Keep Learning!!!
Posted on July 12, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
February 25, 2023