DevOps Tool Series: Jenkins pipeline
A Jenkinsfile is a text file that contains the definition of a Jenkins Pipeline. It’s written in Groovy DSL (Domain Specific Language) and is used to automate the building, testing, and deployment of code in Jenkins.
Below is a simple example of a Jenkinsfile for a basic pipeline:
Different types of Jenkins pipeline:
Declarative Pipeline Syntax:
The declarative syntax is a new feature that uses code for the pipeline. It provides a limited pre-defined structure. Thereby, it offers an easy &simple continuous delivery pipeline. Moreover, it uses a pipeline block.
Scripted Pipeline Syntax:
Unlike declarative syntax, the scripted pipeline syntax is the old traditional way to write the Jenkins file on Jenkins webUI. Moreover, it strictly follows the groovy syntax and helps to develop a complex pipeline as code.
Sample Declarative pipeline
This Jenkinsfile defines a simple pipeline with four stages: Checkout, Build, Test, and Deploy. It uses Maven as the build tool, but you can replace it with the appropriate commands for your project. Adjust the commands, tools, and stages based on the specific requirements of your project. Make sure to have the necessary plugins installed in your Jenkins instance to support your chosen tools and technologies.
pipeline {
agent any
stages {
stage('Checkout') {
steps {
// This stage checks out the code from a version control system like Git
checkout scm
}
}
stage('Build') {
steps {
// This stage builds the project (e.g., compiling code)
sh 'mvn clean install' // Use the appropriate build tool and command for your project
}
}
stage('Test') {
steps {
// This stage runs tests for the project
sh 'mvn test' // Use the appropriate test command for your project
}
}
stage('Deploy') {
steps {
// This stage deploys the application (e.g., to a server)
sh './deploy.sh' // Use the appropriate deployment script or command
}
}
}
post {
success {
// This block is executed if the pipeline succeeds
echo 'Pipeline succeeded! Deploying to production...'
}
failure {
// This block is executed if the pipeline fails
echo 'Pipeline failed. Notify the team and rollback changes if necessary.'
}
}
}
How to create Jenkins pipeline:
Go to Dashboard → New Items
Select the Pipeline →
In new page left panel select pipeline:
From Dropdown → Select pipeline script from scm
ADD the Repository details
SAVE the configuration.
Pipeline job is now created:
INSTALL Plugins:
Dashboard → Manage Jenkins → Plugins