Working with Pipeline Steps
1. Using Shell Commands
| Step | Description | Example |
|---|---|---|
| sh | Execute shell commands in the pipeline | sh 'echo "Hello World"' |
| sh (with script) | Execute a multi-line shell script | |
| sh (with return value) | Capture output of shell command | |
Note: The
sh step runs in the context of the Jenkins agent where the pipeline is executed.Warning: Avoid using
sh with user-provided input without proper sanitization to prevent command injection vulnerabilities.2. Using Batch Commands
| Command | Description | Example |
|---|---|---|
| sh | Execute shell commands in the pipeline | sh '''<br> echo "Hello Jenkins"<br> ls -la<br>''' |
| bat | Execute Windows batch commands in the pipeline | bat '''<br> echo Hello Jenkins<br> dir<br>''' |
| script | Execute Groovy code within the pipeline | script {<br> def buildTime = new Date().format("yyyy-MM-dd HH:mm:ss")<br> echo "Build started at: ${buildTime}"<br>} |
Note: The
sh step is used for Unix/Linux systems, while bat is used for Windows systems.3. Using PowerShell Commands
| Property | Values | Description |
|---|---|---|
| powershell | script |
Executes a PowerShell script block |
| powershell | file |
Executes a PowerShell script file |
| script | string |
The PowerShell script to execute (when using script) |
| file | string |
The path to the PowerShell script file (when using file) |
| returnStdout | boolean |
Whether to capture and return the stdout of the script |
| returnStatus | boolean |
Whether to return the exit status of the script |
Example: Running a PowerShell Script
pipeline {
agent any
stages {
stage('Run PowerShell') {
steps {
powershell '''
Write-Output "Hello from PowerShell"
$result = Get-Date
echo "Current date: $result"
'''
}
}
}
}
Example: Running a PowerShell Script File
pipeline {
agent any
stages {
stage('Run PowerShell Script File') {
steps {
powershell file: 'scripts/deploy.ps1', returnStdout: true
}
}
}
}
Note: The
powershell step requires the PowerShell Plugin to be installed and configured in Jenkins.
4. Using Echo for Logging
| Property | Description | Example |
|---|---|---|
| echo | Prints a message to the console log | echo "Building project..." |
Note: The
echo step is primarily used for logging messages during pipeline execution and does not return a value.5. Using Script Block for Groovy
| Property | Description | Example |
|---|---|---|
| script | Defines a block of Groovy code to be executed within the pipeline | |
Example: Basic Script Block Usage
pipeline {
agent any
stages {
stage('Example') {
steps {
script {
def buildNumber = env.BUILD_NUMBER
echo "Building version ${buildNumber}"
}
}
}
}
}
Note: The
script block allows you to use full Groovy syntax, including variables, conditionals, and loops.
6. Using Checkout SCM
| Property | Description | Values | Notes |
|---|---|---|---|
| checkout | Checkout SCM step | scm |
Checks out the source code from SCM |
| branch | Branch to checkout | main |
Optional, defaults to default branch |
| credentialsId | Credentials ID for SCM access | my-credentials |
Required for private repositories |
| workspace | Workspace directory | /var/lib/jenkins/workspace/my-job |
Defaults to Jenkins workspace directory |
Example: Checkout SCM with specific branch
pipeline {
agent any
stages {
stage('Checkout') {
steps {
checkout([
$class: 'GitSCM',
branches: [[name: 'origin/main']],
userRemoteConfigs: [[url: 'https://github.com/myorg/myrepo.git']]
])
}
}
}
}
Example: Checkout SCM with credentials
pipeline {
agent any
stages {
stage('Checkout') {
steps {
checkout([
$class: 'GitSCM',
branches: [[name: 'origin/main']],
userRemoteConfigs: [[
url: 'https://github.com/myorg/myrepo.git',
credentialsId: 'my-github-credentials'
]]
])
}
}
}
}
7. Using File Operations
| Operation | Description | Example |
|---|---|---|
| sh | Execute shell commands | sh '''<br> ls -l<br> echo "Current directory contents"<br>''' |
| writeFile | Write content to a file | writeFile file: 'example.txt', text: 'Hello, Jenkins!' |
| readFile | Read content from a file | def content = readFile 'example.txt'<br>echo "File content: ${content}" |
| delete | Delete files or directories | delete file: 'example.txt'<br>delete dir: 'temp_dir' |
| archiveArtifacts | Archive build artifacts | archiveArtifacts artifacts: 'build/*.jar', fingerprint: true |
Note: File operations in Jenkins pipelines are executed on the agent where the pipeline runs. Ensure proper permissions and paths for file access.
8. Using Archive Artifacts
| Property | Description | Values |
|---|---|---|
| archiveArtifacts | Archives artifacts from the build | artifacts: 'build/**/*.jar' |
| artifacts | Pattern to match files to archive | 'build/**/*.jar' |
| allowEmpty | Whether to allow archiving empty artifacts | false |
| onlyIfSuccessful | Whether to archive only if build is successful | true |
| fingerprint | Whether to fingerprint the archived artifacts | false |
Example: Archive Artifacts in Pipeline
pipeline {
stages {
stage('Build') {
steps {
sh 'mvn clean package'
}
}
stage('Archive') {
steps {
archiveArtifacts artifacts: 'target/*.jar', onlyIfSuccessful: true
}
}
}
}
Note: Archived artifacts are stored in the Jenkins workspace and can be accessed via the UI or API.
9. Using JUnit Test Results
| Property | Description | Default Value |
|---|---|---|
| junit | Declares JUnit test results to be published | None |
Example: Publishing JUnit Test Results
pipeline {
stages {
stage('Build') {
steps {
sh 'mvn clean compile'
}
}
stage('Test') {
steps {
sh 'mvn test'
}
}
stage('Publish Test Results') {
steps {
junit 'target/surefire-reports/*.xml'
}
}
}
}
Note: The path to JUnit XML files should be relative to the workspace root.
| Parameter | Description | Required |
|---|---|---|
| testResults | Path to JUnit XML files (e.g., **/target/surefire-reports/*.xml) |
Yes |
| allowEmptyResults | Whether to allow empty test results without failing the build | No |
| keepLongStdio | Whether to keep long standard output/error in the test results | No |
| healthScaleFactor | Factor to scale health reporting (default is 1.0) | No |
Example: Advanced JUnit Configuration
junit testResults: '**/target/surefire-reports/*.xml',
allowEmptyResults: true,
healthScaleFactor: 2.0
10. Using Directory Operations
| Operation | Description | Example |
|---|---|---|
| dir | Changes the current directory for subsequent steps in the pipeline. | |
| sh | Executes shell commands in the specified directory context. | |
| checkout | Checks out a specific SCM repository or directory into the workspace. | |
Note: The
dir step changes the working directory for all subsequent steps inside its block. It is useful when you need to run commands or check out code from different parts of your project structure.