Jenkins is one of the famous CICD tool (Continuous Integration and Continuous Delivery).
Before Jenkins, Hudson used to be a popular tool for the same.
The alternate to Jenkins CICD is Azure DevOps.
Jenkins Pipeline (Scripted):
This is an old way of writing Jenkins scripts.
Create a file named- Jenkinsfile, without any file extension and add below content to it.
node { stage('Build') { echo "Build" } stage('Test') { echo "Test" } }
Once you push your code to Git, and a Jenkins build is run succefully one can see various stages in the console output.
“node” refers to a machine where your jenkins is executed.
“stage” blocks are optional you can rewrite the above script like below:
node { echo "Build" echo "Test" }
Jenkins Pipeline (Declarative):
This is the latest way of writing the Jenkins pipeline scripts.
Here we don’t have to mention node, we have to start with pipeline.
“agent” is similar to “node” where your build is going to run. It gives lot of flexibility, even you can put an docker image as an agent.
“stages“, “stage” and “steps” are mandatory.
“post” can be used for any post build activity.
Below is an example of Declarative Jenkins Pipeline:
pipeline { agent any stages{ stage('Build'){ steps{ echo "Build" } } stage('Test'){ steps{ echo "Test" } } } }
Below is an sample of the Declarative Jenkins Pipeline where we had mentioned “post“.
pipeline { agent any stages{ stage('Build'){ steps{ echo "Build" } } stage('Test'){ steps{ echo "Test" } } } post{ always{ echo "I run always" } success{ echo "I run when you are success" } failure{ echo "I run when you fail" } } }
On running the above Declarative Jenkins Pipeline one can see the code checkout from SCM is automatic, unlikely in Scripted Jenkins Pipeline where it has to be mentioned exclusively.
How to use Docker image as an agent ?
The below agent block will pull the maven docker image from the docker hub and install it.
And our build stages will be executed inside the docker container.
pipeline { //agent any agent { docker{ image 'maven:3.6.3' } } stages{ stage('Build'){ steps{ //echo "Build" sh 'mvn --version' } } stage('Test'){ steps{ echo "Test" } } } }