Pro Jenkinsfile: Avoid These Common Mistakes – Part 1

06 / Jun / 2024 by Karandeep Singh 0 comments

Introduction

Hello, DevOps Engineers! Uncle Jenkins here, your trusty CI/CD butler, ready to help you master the art of writing Jenkinsfiles. Just as a butler ensures everything in the household runs smoothly, I’m here to ensure your CI/CD pipelines are efficient and error-free. Let’s dive into some common pitfalls you might face and, more importantly, how to get them right. Let’s get started!

Jenkins logo

Jenkins logo

Not Using Declarative Syntax: Keep It Simple, Silly!

Declarative syntax in Jenkinsfiles is like the gold standard: clear, concise, and easy to work with. Opting for declarative syntax instead of scripted pipelines can prevent confusion and streamline your CI/CD workflows.

Jenkins Pipeline

Jenkins Pipeline


Tip: Use the declarative syntax whenever possible. Here’s a quick example:

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

Hardcoding Credentials: A Recipe for Disaster

Hardcoding credentials in your Jenkinsfile is like leaving the front door unlocked—not very secure! This practice can lead to security vulnerabilities and make it difficult to manage secrets.
Avoidance Tip: Use Jenkins credentials management to handle sensitive information securely. You can then reference these credentials in your Jenkinsfile:

pipeline {
    agent any
        stage(‘Deploy’) {
            steps {
                script {
                    // Using withCredentials to access stored credentials
                    withCredentials([usernamePassword(credentialsId: ‘my-credentials-id’, usernameVariable: ‘USERNAME’, passwordVariable: ‘PASSWORD’)]) {
                        echo “Deploying with credentials”
                        sh “””
                        # Using the credentials in shell commands
                        curl -u $USERNAME:$PASSWORD -X POST http://example.com/deploy
                        “””
                  }
              }
        }
    }
}

Ignoring Error Handling: Don’t Leave It to Chance

Pipelines fail. It’s a fact. Ignoring error handling means you’ll be unprepared when things go wrong, costing you time and resources.
Avoidance Tip: Use try-catch blocks and the post section to manage errors and ensure proper cleanup.

pipeline {
    agent any
    stages {
        stage(‘Build’) {
            steps {
                script {
                    try {
                        sh ‘./build.sh’
                    } catch (hudson.AbortException e) {
                        echo “Build aborted: ${e.message}
                        error(“Stopping the pipeline due to build abortion.”)
                    } catch (IOException e) {
                        echo “Build failed due to I/O error: ${e.message}
                        error(“Stopping the pipeline due to I/O error.”)
                    } finally {
                        echo ‘Cleaning up…’
                        cleanWs()
                    }
                }
            }
        }
    }
}

Ignoring Workspace Cleanup: Don’t Be a Hoarder

Unused files cluttering your workspace can cause builds to fail. Clean up after yourself.

Clean workspace

Clean workspace

Avoidance Tip: Use the cleanWs step to clean the workspace after build.

pipeline {
    agent any
    stages {
          stage(‘Build’) {
              steps {
                    sh ‘make build’
              }
          }
    }
    post {
          always {
              cleanWs()
          }
    }
}

Not using Parallelism: Speed Up Your Pipeline

Running tasks sequentially that could run in parallel wastes time.
Avoidance Tip: Use the parallel step to run tasks concurrently.

pipeline {
    agent any
    stages {
        stage(‘Test’) {
            parallel failFast: true, stages: {
                stage(‘Unit Test’) {
                    steps {
                        echo ‘Running unit tests..’
                    }
                }
                stage(‘Integration Test’) {
                    steps {
                        echo ‘Running integration tests..’
                    }
                }
            }
        }
    }
}

 Key Points:

  • Parallel Block with failFast: The failFast parameter is true in the parallel block. If either the “Unit Test” or “Integration Test” stage fails, the other parallel stage is immediately halted, and the pipeline progresses to any post-failure handling without wasting time or resources on a build that’s already known to have issues.
  • Immediate Feedback: This setup ensures that any failure in the testing phase is immediately caught and addressed, speeding up the development cycle by reducing the wait time for feedback.

Neglecting to Use Jenkins Shared Library for Reusable Code: Simplify and Standardize

Duplicated code is error-prone and difficult to maintain. Jenkins Shared Libraries help you DRY (Don’t Repeat Yourself).

shared library

shared library

Avoidance Tip: Using shared libraries to encapsulate common logic.

@Library(‘jenkins-shared-library’) _
pipeline {
    agent any
    stages {
        stage(‘Build’) {
            steps {
                // Using a custom function from the shared library
                customBuildFunction()
            }
        }
    }
}

Conclusion

Mastering Jenkinsfile creation is important for optimizing CI/CD pipelines. Avoiding common pitfalls and adopting best practices can significantly enhance pipeline efficiency. Consider connecting with TO THE NEW for further support and expertise, especially in managing complex CI/CD tasks. Our team of AWS Certified Architects & DevOps Engineers can assist in streamlining your operations, offering services from migration to managed cloud solutions to disaster recovery, and ensuring your CI/CD pipelines are as efficient and resilient as possible. We still need to discuss more points regarding how to write a professional Jenkinsfile. Stay tuned for the next blog, covering additional strategies and insights to help you master Jenkinsfile creation and further improve your CI/CD practices.

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *