Jenkins Pipeline

Code Your Build Steps

Published on Jul 25, 2021

Reading time: 2 minutes.


What is Jenkins Pipeline 🤔


  • Jenkins Pipeline allows us to write the Jenkins build steps in code
  • Pipelines are robust. So if your server undergoes an unpredicted restart, the pipeline will be automatically resumed.
  • Jenkins Pipelines support big projects. You can run many jobs, and even use pipelines in a loop

Jenkins Pipeline format

Jenkins Pipeline can be defined by a text file called JenkinsFile. You can implement pipeline as code using JenkinsFile, and this can be defined by using a DSL (Domain Specific Language).

Pipeline Syntax

There are two types of syntax can be used when you write the Jenkinsfile.

  • Declarative
  • Scripted

Difference beween Declarative and Scripted Pipeline

  • Declarative pipeline is a relatively new feature that supports the pipeline as code concept. It makes the pipeline code easier to read and write.
  • Scripted pipeline uses groovy - Groovy is the scripting language for the java platform.
  • No matter of what Pipeline it is Under the hood even the Declarative pipeline will inteprated by groovy in Jenkins.

Declarative pipeline Example code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
pipeline {
    agent { label 'master'}

    parameters{
        string(name:'AWS_ACCESS_KEY', defaultValue: '', description: 'AWS_ACCESS_KEY')
        string(name:'AWS_SECRET_ACCESS_KEY', defaultValue: '', description: 'AWS_SECRET_ACCESS_KEY')
        string(name:'token', defaultValue: '', description: 'token')
    }
    stages {
        stage('Terraform init'){
            steps{
                  sh(
                      '''
                      sh 'scripts/terraform-init.sh'
                      '''  
                  )
            }

        }
        stage('Terraform apply'){
            steps{
                  sh(
                      '''
                      sh 'scripts/terraform-apply.sh'
                      '''  
                  )5
            }
        }
    }
}

Scripted pipeline Example code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
Jenkinsfile (Scripted Pipeline)
node {  
    stage('Build') { 
        // 
    }
    stage('Test') { 
        // 
    }
    stage('Deploy') { 
        // 
    }
}

Key Differences.

  • Pipeline: This is the user-defined block, which contains all the processes such as build, test, deploy, etc. it is a group of all the stages in a JenkinsFile. All the stages and steps are defined in this block. It is used in declarative pipeline syntax.
1
2
pipeline{  
}  
  • Node: The node is a machine on which Jenkins runs is called a node. A node block is used in scripted pipeline syntax.
1
2
node{  
}