The Ultimate Guide : Getting Started with Jenkins Pipeline

No comments

Application deployment is a daily task for developers and operations team. With Jenkins you can work with your deployment but for long deployment process you need a way to make things look easy and deploy in structured way.

To Bring simplicity in process of deployment Jenkins Pipeline are your best friend. They make the process look like as if river is flowing beautifully. Having said that , In this tutorial we will cover all about CI/CD and in depth knowledge of Jenkins Pipeline and Jenkins file.

Table of content

  1. What is CI/CD ( Continuous Integration and Continuous deployments)?
  2. What is Jenkins Pipeline?
  3. How to create a basic Jenkins Pipeline
  4. Handling Parameters in Jenkins Pipeline
  5. How to work with Input Parameters
  6. Conclusion

What is CI/CD ( Continuous Integration and Continuous deployments)

With CI/CD products are delivered to clients in a very smart and effective way by using different automated stages. With CI/CD it saves tons of time for both developer and operations team and there are very less chances of human errors. CI/CD stands for continuous integration and continuous deployments. It automates everything starting from integrating to deployments.

Continuous Integration

CI also known as Continuous integration is primarily used by developers. Successful Continuous integration means developers code is built , tested and then pushed to Shared repository whenever there is a change in code.

Developers push code changes every day, multiple times a day. For every push to the repository, you can create a set of scripts to build and test your application automatically. These scripts help decrease the chances that you introduce errors in your application.

This practice is known as Continuous Integration. Each change submitted to an application, even to development branches, is built and tested automatically and continuously.

Continuous Delivery

Continuous delivery is step beyond continuous integration . In this case not only application is continuously built and tested each time the code is pushed but application is also deployed continuously. However, with continuous delivery, you trigger the deployments manually.

Continuous delivery checks the code automatically, but it requires human intervention to deploy the changes.

Continuous Deployment

Continuous deployment is again a step beyond continuous integration the only difference between deployment and delivery is deployment automatically takes the code from shared repository and deploy the changes to environments such as Production where customers can see those changes. This is the final stage of CI/CD pipeline. With CD it takes hardly few minutes to deploy the code to the environments. It depends on heavy pre automation testing.

Examples of CI/CD Platform:

  • Spinnaker and Screwdriver built platform for CD
  • GitLab , Bamboo , CircleCI , Travis CI and GoCD are built platform for CI/CD

What is Jenkins Pipeline?

Jenkins Pipeline are group of plugins which helps to deliver a complete continuous delivery pipeline into Jenkins. Jenkins Pipeline plugin is automatically installed while installing the Jenkins with suggested plugins. This starts from building the code till deployment of the software right up to the customer. Jenkins pipeline allows you to write complex operations and code deployment as code with DSL language ( Domain specific language ) where we define a text file called “JENKINSFILE” which is checked into the repository.

  • Benefits of Jenkins pipeline
    • Pipeline can be written in code which can be more easier and gives more ability to review.
    • In case Jenkins stop you can still continue to write Jenkins file
    • With code capabilities you can allow waiting, approvals , stop and many other functionalities.
    • It support various extensions & plugins.
  • Jenkins file can be written with two syntax’s ( DSL: Domain Specific Language)
    • Declarative Pipeline : This is newer and writing code with this is much easier
    • Scripted Pipeline : This is older and writing code with this is little complicated
  • Scripted pipeline syntax can be generated from
http://Jenkins-server:8080/pipeline-syntax/
  • Declarative Pipeline syntax can be generated from
http://Jenkins-server:8080/directive-generator/

  • Jenkins Pipeline supports various environmental variables such as
    • BUILD_NUMBER: Displays the build number
    • BUILD_TAG: Displays the tag which is jenkins-${JOB_NAME}-${BUILD_NUMBER}
    • BUILD_URL: Displays the URL of the result of Build
    • JAVA_HOME: Path of Java home
    • NODE_NAME: It specifics the name of the node. For example set it to master is for Jenkins controller
    • JOB_NAME: Name of the Job
  • You can set the environmental variables dynamically in pipeline as well
    environment {
        AWS_ACCESS_KEY_ID     = credentials('jenkins-aws-secret-key-id')
        AWS_SECRET_ACCESS_KEY = credentials('jenkins-aws-secret-access-key')
        MY_KUBECONFIG = credentials('my-kubeconfig')
   }
  • Lets take a example of Jenkins file and understand the basic terms one by one
    • pipeline: It is Declarative Pipeline-specific syntax 
    • agent: Agent allows Jenkins to allocate an executor or a node. For example Jenkins slave
    • Stages: It include multiple tasks which Pipeline needs to perform. It can have a single task as well.
    • Stage: Stage is one single task under stages.
    • steps: These are steps which needs to be executed in every stage.
    • sh: sh is one of the step which executes shell command.
pipeline {
   agent any 
    stages {
        stage('Testing the Jenkins Version') {
            steps {
                echo 'Hello, Jenkins'
                sh 'service jenkins status'
               //  sh("kubectl --kubeconfig $MY_KUBECONFIG get pods")
            }
        }
    }
}

How to create a basic Jenkins Pipeline

  • Install Jenkins on the ubuntu machine. Please find the steps to install Jenkins from here
  • Once you have Jenkins Machine , visit Jenkins URL and Navigate to New Item
  • Choose Pipeline from the option and provide it a name such as pipeline-demo and click OK
  • Now add a Description such as my demo pipeline and add a Pipeline script as below
pipeline {
   agent any 
    stages {
        stage('Testing the Jenkins Version') {
            steps {
                echo 'Hello, Jenkins'
                sh 'service jenkins status'
            }
        }
    }
}
  • Click on Save & Finally click on Build Now
  • lets verify the code execution from console output of the Job. So click on the build number and click on it.

Handling Parameters in Jenkins Pipeline

If you wish to use Build with Parameters , so those parameters are accessible using params keyword in pipeline.

Lets see a quick example. In below code we have Profile as a parameter and it can be accessed as ${params.Profile} .Lets paste the code in pipeline script as we did earlier

pipeline {
  agent any
  parameters {
    string(name: 'Profile', defaultValue: 'devops-engineer', description: 'I am devops guy') 
}
 stages {
    stage('Testing DEVOPS') {
       steps {
          echo "${params.Profile} is a cloud profile"
       }
     }
   }
}
  • Lets build the Jenkins pipeline now.
  • Next verify the console output
  • Similarly we can use different parameters such
pipeline {
    agent any
    parameters {
        string(name: 'PERSON', defaultValue: 'AutomateInfra', description: 'PERSON')
        text(name: 'BIOGRAPHY', defaultValue: '', description: 'BIOGRAPHY')
        booleanParam(name: 'TOGGLE', defaultValue: true, description: 'TOGGLE')
        choice(name: 'CHOICE', choices: ['One', 'Two', 'Three'], description: 'CHOICE')
        password(name: 'PASSWORD', defaultValue: 'SECRET', description: 'PASSWORD')
    }
    stages {
        stage('All-Parameters') {
            steps {
                echo "I am ${params.PERSON}"
                echo "Biography: ${params.BIOGRAPHY}"
                echo "Toggle: ${params.TOGGLE}"
                echo "Choice: ${params.CHOICE}"
                echo "Password: ${params.PASSWORD}"
            }
        }
    }
}

How to work with Input Parameters

Input parameter allows you to provide an input using a input step. Unless input is provided the pipeline will be paused. Lets see a quick example in which Jenkins job will prompt for “should we continue” message. Unless we approve it will remain as it is else finally it will abort.

pipeline {
    agent any
    stages {
        stage('Testing input condition') {
            input {
                message "Should we continue?"
                ok "Yes, we should."
                submitter "automateinfra"
                parameters {
                    string(name: 'PERSON', defaultValue: 'Automate', description: 'Person')
                }
            }
            steps {
                echo "Hello, ${PERSON}, nice to meet you."
            }
        }
    }
}
  • Lets paste the content in Jenkins pipeline script and click on build now.
  • Let us verify by clicking on build Now

Conclusion

In this tutorial we learnt what is CI/CD and CI/CD open source tool Jenkins. We covered how to write pipeline and syntax of Jenkins pipeline using its language known as DSL ( domain specific language ) . Also we learnt in depth of Jenkins pipeline and created basic Jenkins pipeline and executed it.

Hope this tutorial will help you a kick start to how to work with Jenkins pipeline and execute them. If you like this please share it.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s