How to Use Steps in Jenkins Pipeline: Syntax and Examples
In Jenkins Pipeline,
steps define the individual tasks executed inside a stage. You use the steps block to list commands like sh, echo, or checkout that Jenkins runs sequentially during the build.Syntax
The steps block is placed inside a stage in a Jenkins Declarative Pipeline. It contains one or more commands that Jenkins executes in order.
Each step is a command like sh to run shell scripts, echo to print messages, or checkout to get source code.
Example structure:
pipeline: The main block defining the pipeline.stage: A phase in the pipeline.steps: Commands to run in that stage.
groovy
pipeline {
agent any
stages {
stage('Example') {
steps {
echo 'Hello, Jenkins!'
sh 'echo Running shell command'
}
}
}
}Example
This example shows a simple Jenkins Declarative Pipeline with two stages. Each stage uses steps to run commands: printing messages and running shell commands.
groovy
pipeline {
agent any
stages {
stage('Build') {
steps {
echo 'Starting build...'
sh 'echo Building project'
}
}
stage('Test') {
steps {
echo 'Running tests...'
sh 'echo Tests passed!'
}
}
}
}Output
[Pipeline] echo
Starting build...
[Pipeline] sh
+ echo Building project
Building project
[Pipeline] echo
Running tests...
[Pipeline] sh
+ echo Tests passed!
Tests passed!
Common Pitfalls
Common mistakes when using steps include:
- Placing
stepsoutside astageblock, which causes syntax errors. - Using unsupported commands inside
stepsin Declarative Pipeline. - Forgetting to use
shorbatfor shell commands, leading to errors.
Always ensure steps are inside stage and use supported step commands.
groovy
pipeline {
agent any
stages {
stage('Wrong') {
// Missing steps block - this is wrong
echo 'This will cause an error'
}
}
}
// Correct way:
pipeline {
agent any
stages {
stage('Right') {
steps {
echo 'This works fine'
}
}
}
}Quick Reference
| Element | Description | Example |
|---|---|---|
| pipeline | Defines the whole pipeline | pipeline { ... } |
| agent | Specifies where to run the pipeline | agent any |
| stage | Defines a phase in the pipeline | stage('Build') { ... } |
| steps | Contains commands to execute in a stage | steps { echo 'Hi' } |
| sh | Runs shell commands | sh 'echo Hello' |
| echo | Prints messages to console | echo 'Message' |
Key Takeaways
Use the steps block inside a stage to define commands Jenkins runs.
Each step is a command like echo or sh executed in order.
Always place steps inside a stage to avoid syntax errors.
Use sh or bat to run shell commands within steps.
Declarative Pipeline requires this structured syntax for clarity.