Declarative Pipeline Syntax in Jenkins
1. Introduction
Declarative Pipeline Syntax is a simplified, structured syntax introduced in Jenkins 2.x. It allows users to define their CI/CD pipeline in a more readable format compared to the traditional Scripted Pipeline. This lesson will cover the essential aspects of Declarative Pipeline Syntax, its structure, and best practices.
2. Key Concepts
- **Pipeline**: A series of steps that automate the process of building, testing, and deploying software.
- **Stage**: A distinct phase in the pipeline, such as build, test, and deploy.
- **Agent**: A directive that specifies where the pipeline or stage runs (e.g., on a specific node or Docker container).
- **Steps**: Individual tasks that are executed within a stage.
3. Pipeline Structure
Note: The Declarative Pipeline Syntax is enclosed within a `pipeline` block.
pipeline {
agent any
stages {
stage('Build') {
steps {
echo 'Building...'
}
}
stage('Test') {
steps {
echo 'Testing...'
}
}
stage('Deploy') {
steps {
echo 'Deploying...'
}
}
}
}
4. Code Example
Here's a complete example of a Declarative Pipeline:
pipeline {
agent {
label 'docker'
}
stages {
stage('Checkout') {
steps {
checkout scm
}
}
stage('Build') {
steps {
sh 'make build'
}
}
stage('Test') {
steps {
sh 'make test'
}
}
stage('Deploy') {
steps {
sh 'make deploy'
}
}
}
}
5. Best Practices
- Keep your pipeline code simple and readable.
- Use stages to clearly define the flow of your pipeline.
- Implement error handling using the `post` section.
- Use parameters to make your pipeline more flexible.
- Leverage shared libraries for reusable code.
6. FAQ
What is the difference between Declarative and Scripted Pipeline?
Declarative Pipeline is more structured and easier to read, while Scripted Pipeline provides more flexibility with Groovy scripting.
Can I use both Declarative and Scripted syntax in the same pipeline?
No, a pipeline must be entirely in either Declarative or Scripted syntax, not a mix of both.
What does the 'agent any' directive do?
It allows the pipeline to run on any available agent.