Devops Tutorial 25 – Jenkinsfile: Pipeline as a Code (Declarative)
What you will Learn:
What is Jenkinsfile
Install ‘Pipeline’ plugin
Create pipeline job
Jenkinsfile formats
‘Hello world’ declarative pipeline
Pipeline Logs
Console output of a run
Configure project to add more stages
What is Jenkinsfile?
So far we have been creating freestyle jobs and chaining them to create a pipeline. We can also create a pipeline by scripting inside a Jenkinsfile. That is why Jenkinsfile is also called as ‘Pipeline as a code’. So let us see how to do that.
Install ‘Pipeline’ plugin
First we need to install ‘Pipeline’ plugin
Important note: Restart Jenkins after installing plugin
Create pipeline job
Create a new job, but this time select job type as ‘Pipeline’
Click Ok
You should see 4 tabs:
General, Build Triggers, Advanced Project Options and Pipeline
Click ‘Pipeline’ tab. You would see a dropdown, click it.
Jenkinsfile formats
Now, Jenkinsfile can be written in 2 formats:
declarative,
scripted
Both these formats use groovy language having a slightly different structure
‘Hello world’ declarative pipeline
Select ‘Hello World’ declarative pipeline from the dropdown shown above. You would see the Jenkinsfile pipeline code snippet shown below
The script starts with ‘pipeline’ keyword followed by ‘agent any’. Latter means that the script can be executed on any agent (or a node or the machine).
We then see the ‘stages’ block that comprises of stage name (here ‘Hello’). The stage name can also be ‘Build’, ‘Deploy’, ‘Test’, Release’.
We then define the steps inside a stage.
Apply and Save
Notice above on the right hand side, we see a ‘Stage View’ section that right now has no data because the build has not yet been executed.
Click ‘Build Now’ and wait for the build to get successfully over
We can now see the stage view, see below
You can also see #1, this signifies the pipeline build number.
Pipeline Logs
Hover the mouse over the section seen below
Click ‘Logs’. You would see the log output as seen below
Close the above logs window.
Console output of a run
Click #1 link
Click console output
You can see the console output details as seen below
Configure project to add more stages
Click back button (2 times). We would see ‘Configure’
Click ‘Configure’ and focus on below section
Change the stage name to ‘Build’ and edit the echo statement
Next, select the lines of the stage block as shown below (lines 5-9)
Copy these lines and paste them after line 9, see below. Change the stage name to ‘Deploy’ and edit echo statement
Similarly add 2 more stages
So our entire Jenkinsfile looks as below
Apply and Save
Click ‘Build Now’
Wait for the build to get over
Notice the Stage view now. We see the 4 stages, see below
So this is how we setup the Jenkinsfile declarative pipeline as a code.
Thank you for reading!