Sling Academy
Home/DevOps/Working with Jenkinsfile: A complete guide

Working with Jenkinsfile: A complete guide

Last updated: February 03, 2024

Introduction

Jenkinsfile, a text file written in the Groovy language, is part of the Jenkins Pipeline feature. It defines the steps for the continuous integration/delivery (CI/CD) pipeline that Jenkins will execute. Its strength lies in its ability to automate complex builds, tests, and deployment processes. This tutorial will guide you through the fundamentals of Jenkinsfile, from basic syntax to advanced features, including practical examples.

Basic Jenkinsfile Structure

A Jenkinsfile is divided into sections, each serving a specific purpose. The simplest Jenkinsfile has two main sections: the pipeline block, and within it, the stages block, which contains one or more stage blocks.

pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                echo 'Building..'
            }
        }
        stage('Test') {
            steps {
                echo 'Testing..'
            }
        }
        stage('Deploy') {
            steps {
                echo 'Deploying..'
            }
        }
    }
}

This basic Jenkinsfile defines three stages: Build, Test, and Deploy, with simple print commands in each step. This introduction teaches Jenkins to execute these steps sequentially.

Working with Parameters

Parameters allow you to customize executions. You can define parameters in the Jenkinsfile to make your pipeline more flexible.

pipeline {
    agent any
    parameters {
        string(name: 'DEPLOY_ENV', defaultValue: 'staging', description: 'The environment to deploy to')
    }
    stages {
        stage('Deploy') {
            steps {
                script {
                    echo "Deploying to ${params.DEPLOY_ENV}.."
                }
            }
        }
    }
}

This example introduces parameters, specifically a string parameter for the deployment environment. When triggering the pipeline, you can specify the deployment environment dynamically.

Advanced Features

Jenkinsfile supports various advanced features such as conditional execution, parallel steps, and error handling. Let’s explore how to implement these.

Conditional Execution

Conditional execution can be achieved using the when directive. It allows stages to run based on specific conditions.

pipeline {
    agent any
    stages {
        stage('Deploy to Prod') {
            when {
                environment name: 'DEPLOY_ENV', value: 'prod'
            }
            steps {
                echo 'Deploying to production...'
            }
        }
    }
}

This example shows a pipeline where the ‘Deploy to Prod’ stage only executes when the ‘DEPLOY_ENV’ environment variable is set to ‘prod’.

Parallel Execution

To execute steps or stages in parallel, use the parallel directive.

pipeline {
    agent any
    stages {
        stage('Tests') {
            steps {
                parallel {
                    stage('Unit Test') {
                        steps {
                            echo 'Running unit tests...'
                        }
                    }
                    stage('Integration Test') {
                        steps {
                            echo 'Running integration tests...'
                        }
                    }
                }
            }
        }
    }
}

This configuration runs the ‘Unit Test’ and ‘Integration Test’ stages in parallel, improving the pipeline’s efficiency.

Error Handling

Error handling in Jenkinsfile is crucial for managing failures gracefully. The post section allows you to define actions based on the pipeline’s execution status.

pipeline {
    agent any
    stages {
        stage('Test') {
            steps {
                script {
                    // Example of a failing command
                    error("This is a forced error")
                }
            }
        }
    }
    post {
        always {
            echo 'This will always execute'
        }
        success {
            echo 'Pipeline succeeded'
        }
        failure {
            echo 'Pipeline failed'
        }
    }
}

The post section in this example shows how to execute specific steps based on the pipeline’s outcome, ensuring that certain cleanup or notification steps are always performed.

Conclusion

The versatility and power of Jenkinsfile make it a cornerstone of modern CI/CD practices. Starting with simple pipelines and evolving to incorporate advanced features allows developers to automate their build, test, and deployment processes effectively. With practice, your Jenkinsfiles will become an integral part of your software development lifecycle.

Next Article: Branches and Pull Requests in Jenkins: A Deep Dive (with examples)

Previous Article: How to define a Jenkins pipeline: A practical guide

Series: Jenkins Tutorials

DevOps

You May Also Like

  • How to reset Ubuntu to factory settings (4 approaches)
  • Making GET requests with cURL: A practical guide (with examples)
  • Git: What is .DS_Store and should you ignore it?
  • NGINX underscores_in_headers: Explained with examples
  • How to use Jenkins CI with private GitHub repositories
  • Terraform: Understanding State and State Files (with Examples)
  • SHA1, SHA256, and SHA512 in Terraform: A Practical Guide
  • CSRF Protection in Jenkins: An In-depth Guide (with examples)
  • Terraform: How to Merge 2 Maps
  • Terraform: How to extract filename/extension from a path
  • JSON encoding/decoding in Terraform: Explained with examples
  • Sorting Lists in Terraform: A Practical Guide
  • Terraform: How to trigger a Lambda function on resource creation
  • How to use Terraform templates
  • Understanding terraform_remote_state data source: Explained with examples
  • Jenkins Authorization: A Practical Guide (with examples)
  • Solving Jenkins Pipeline NotSerializableException: groovy.json.internal.LazyMap
  • Understanding Artifacts in Jenkins: A Practical Guide (with examples)
  • Using Jenkins with AWS EC2 and S3: A Practical Guide