Skip to main content

Implementing Pipeline Scripts

1. Using Groovy Scripts in Pipelines

Jenkins pipelines can be defined using either Declarative Pipeline syntax or Scripted Pipeline syntax, both of which are based on the Groovy scripting language. The Scripted Pipeline syntax allows for more flexibility and control, as it uses standard Groovy code blocks.

Feature Description Usage Example
Scripted Pipeline Syntax Uses Groovy syntax with a node block to define stages.
node {
    stage('Build') {
        sh 'make'
    }
}
Declarative Pipeline Syntax Uses a structured syntax with pipeline block and stages.
pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                sh 'make'
            }
        }
    }
}

Example: Basic Scripted Pipeline

node {
    stage('Checkout') {
        git 'https://github.com/example/repo.git'
    }
    stage('Build') {
        sh 'mvn clean package'
    }
    stage('Test') {
        sh 'mvn test'
    }
}
Note: Scripted pipelines provide more control but are more verbose than declarative pipelines.

Key Features of Groovy in Jenkins Pipelines

  • Control Flow: Use Groovy's control structures like if/else, for, and while.
  • Functions: Define custom functions to encapsulate logic.
  • Variables: Use Groovy variables to store and manipulate data.
  • Error Handling: Implement try/catch blocks for error handling.

2. Calling External Scripts

Property Description Example
sh Executes shell commands in the Jenkins environment sh 'ls -la'
script Allows running Groovy code inside a pipeline script { def result = sh(script: 'echo "Hello"', returnStdout: true) }
withEnv Sets environment variables for a block of steps withEnv(['MY_VAR=value']) { sh 'echo $MY_VAR' }

Example: Running External Script

pipeline {
    agent any
    stages {
        stage('Run Script') {
            steps {
                sh 'chmod +x ./deploy.sh'
                sh './deploy.sh'
            }
        }
    }
}

Example: Using Script Block to Capture Output

pipeline {
    agent any
    stages {
        stage('Capture Output') {
            steps {
                script {
                    def output = sh(script: 'echo "Hello World"', returnStdout: true)
                    echo "Output: ${output}"
                }
            }
        }
    }
}
Note: Ensure that external scripts have proper permissions and are executable in the Jenkins environment.

3. Using Script Block in Declarative

The script block in Jenkins Declarative Pipeline allows you to execute arbitrary shell commands or Groovy code within the pipeline. It's particularly useful when you need functionality that isn't directly supported by the Declarative syntax.

Property Description Usage
script Executes a block of Groovy or shell commands script { sh 'echo "Hello World"' }

Example: Running Shell Commands

pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                script {
                    sh 'echo "Starting build process"'
                    sh 'ls -la'
                    sh 'mkdir -p build/output'
                }
            }
        }
    }
}

Example: Using Groovy Code

pipeline {
    agent any
    stages {
        stage('Example') {
            steps {
                script {
                    def currentTime = new Date().format('yyyy-MM-dd HH:mm:ss')
                    echo "Current time: ${currentTime}"
                    
                    // Conditional logic
                    if (env.BRANCH_NAME == 'main') {
                        sh 'echo "Building main branch"'
                    } else {
                        sh 'echo "Building feature branch"'
                    }
                }
            }
        }
    }
}
Note: The script block is not recommended for use in stages where other steps are available, as it can make pipelines harder to read and maintain. Prefer using built-in Declarative steps when possible.

4. Implementing Custom Functions

Function Description Parameters Return Type
customBuildScript() Executes a custom build script scriptPath (string) void
validateEnvironment() Validates environment variables requiredVars (array of strings) boolean
sendNotification() Sends a notification to Slack message (string), channel (string) void

Example: Custom Build Script

def customBuildScript(scriptPath) {
    sh "chmod +x ${scriptPath}"
    sh "${scriptPath}"
}

customBuildScript("./scripts/deploy.sh")

Example: Environment Validation

def validateEnvironment(requiredVars) {
    for (var in requiredVars) {
        if (!env."${var}") {
            error "Environment variable ${var} is not set"
        }
    }
    return true
}

validateEnvironment(["NODE_VERSION", "JAVA_HOME"])

Example: Slack Notification

def sendNotification(message, channel = "#jenkins") {
    withCredentials([string(credentialsId: "slack-webhook-url", variable: "WEBHOOK_URL")]) {
        sh "curl -X POST -H 'Content-type: application/json' --data '{\"text\": \"${message}\"}' ${WEBHOOK_URL}"
    }
}

sendNotification("Build completed successfully", "#deployments")

5. Using Global Variables

Variable Description Example Value
BUILD_NUMBER Unique number for each build 123
BUILD_ID Build ID (timestamp) 2025-04-05_14:30:00
JOB_NAME Name of the job my-pipeline
WORKSPACE Workspace directory path /var/lib/jenkins/workspace/my-pipeline
JENKINS_URL Base URL of Jenkins instance http://localhost:8080/
NODE_NAME Name of the node executing the build master

Example: Using Global Variables in Pipeline Script

pipeline {
    agent any
    stages {
        stage('Print Info') {
            steps {
                echo "Build Number: ${BUILD_NUMBER}"
                echo "Job Name: ${JOB_NAME}"
                echo "Workspace: ${WORKSPACE}"
            }
        }
    }
}

6. Handling String Interpolation

Method Description Example
Groovy String Interpolation Uses double quotes and ${variable} for interpolation
def name = "Jenkins"
def message = "Welcome, ${name}!"
echo message
Single Quote Interpolation Single quotes do not support interpolation; use + for concatenation
def name = "Jenkins"
def message = 'Welcome, ' + name + '!'
echo message
Multiline Strings Use triple quotes for multiline strings with interpolation support
def project = "Pipeline"
def description = """
Project: ${project}
Status: Running
"""
echo description

Example: Using Interpolated Variables in Script

def project = "WebApp"
def version = "1.0.0"
def buildNumber = "B001"

echo "Building ${project} version ${version} (Build: ${buildNumber})"
Note: Jenkins Pipeline scripts are written in Groovy, which supports string interpolation using double quotes and ${} syntax.

7. Using Collections

Collection Type Description Usage Example Notes
List Ordered collection of elements that allows duplicates def mylist = [1, 2, 3] Elements can be accessed by index
Set Unordered collection of unique elements def myset = [1, 2, 2, 3].toSet() Useful for removing duplicates
Map Key-value pairs with unique keys def mymap = [name: 'John', age: 30] Values can be accessed by key

Example: Working with Lists

def fruits = ['apple', 'banana', 'orange']
fruits.add('grape')
println(fruits[0]) // apple

Example: Using Maps

def person = [name: 'Alice', age: 25, city: 'New York']
println("Name: ${person.name}")
Note: Collections in Jenkins pipelines are based on Groovy syntax and behavior.

8. Implementing File Operations

Operation Description Example
sh 'ls -l' List files in directory sh 'ls -l'
sh 'mkdir newdir' Create a new directory sh 'mkdir newdir'
sh 'rm -rf olddir' Remove directory recursively sh 'rm -rf olddir'
sh 'cp file1 file2' Copy a file sh 'cp file1 file2'
sh 'cat file.txt' Display content of a file sh 'cat file.txt'
sh 'echo "text" > file.txt' Write text to a file sh 'echo "text" > file.txt'
sh 'grep "pattern" file.txt' Search for a pattern in a file sh 'grep "pattern" file.txt'
sh 'find . -name "*.log"' Find files with a specific extension sh 'find . -name "*.log"'
Note: Use sh step to execute shell commands in Jenkins Pipeline.

9. Using Regular Expressions

Method Description Example
find Finds the first match of a regex pattern in a string
def text = "Hello world 123"
def matcher = text =~ /(\w+) (\w+) (\d+)/
def match = matcher.find()
println match[0] // "Hello world 123"
findAll Find all matches of a regex pattern in a string
def text = "Numbers: 123, 456, 789"
def numbers = text.findAll(/\d+/)
println numbers // ["123", "456", "789"]
replaceFirst Replace the first occurrence of a regex pattern with a replacement string
def text = "Hello world"
def result = text.replaceFirst(/world/, "Jenkins")
println result // "Hello Jenkins"
replaceAll Replace all occurrences of a regex pattern with a replacement string
def text = "Hello world, world"
def result = text.replaceAll(/world/, "Jenkins")
println result // "Hello Jenkins, Jenkins"
Note: In Jenkins Pipeline scripts, regex patterns are typically used with the =~ operator to create a java.util.regex.Matcher object, which provides methods like find(), findAll(), and others.

Example: Extracting Build Numbers

def logText = "Build #12345 started at 2024-01-01"
def buildNumber = logText.find(/Build #(\d+)/)
if (buildNumber) {
    println "Build number: ${buildNumber[1]}"
} else {
    println "No build number found"
}

10. Handling JSON and XML Parsing

Method Description Usage Notes
jsonParse() Parses a JSON string into a Groovy object def parsedJson = jsonParse(jsonString) Available in Jenkins Pipeline DSL
xmlParse() Parses an XML string into a Groovy object def parsedXml = xmlParse(xmlString) Available in Jenkins Pipeline DSL

Example: Parsing JSON

def json = '{"name": "Jenkins", "version": "2.401"}'
def parsed = jsonParse(json)
echo "Name: " + parsed.name
echo "Version: " + parsed.version

Example: Parsing XML

def xml = '<root><name>Jenkins</name><version>2.401</version></root>'
def parsed = xmlParse(xml)
echo "Name: " + parsed.name
echo "Version: " + parsed.version

Was this article helpful?