Jenkinsfile

Jenkinsfile with Multi-Stage Pipeline (Best Practices & Scenarios)

A Jenkinsfile is a script that defines a Jenkins pipeline. Multi-stage pipelines help in structuring CI/CD workflows efficiently, ensuring code is built, tested, and deployed systematically.


1. Basic Multi-Stage Jenkinsfile (Declarative Pipeline)

pipeline {
    agent any

    environment {
        DOCKER_IMAGE = "myapp:latest"
    }

    stages {
        stage('Checkout') {
            steps {
                git 'https://github.com/user/repo.git'
            }
        }

        stage('Build') {
            steps {
                sh 'docker build -t $DOCKER_IMAGE .'
            }
        }

        stage('Test') {
            steps {
                sh 'docker run --rm $DOCKER_IMAGE npm test'
            }
        }

        stage('Push to Registry') {
            when {
                branch 'main'
            }
            steps {
                withDockerRegistry([credentialsId: 'docker-hub-credentials', url: 'https://index.docker.io/v1/']) {
                    sh 'docker push $DOCKER_IMAGE'
                }
            }
        }

        stage('Deploy') {
            when {
                branch 'main'
            }
            steps {
                sh './deploy.sh'
            }
        }
    }

    post {
        success {
            echo 'Pipeline executed successfully!'
        }
        failure {
            echo 'Pipeline failed!'
        }
    }
}

2. Breakdown of Key Sections

2.1 agent

  • Defines where the pipeline will run.

  • Example:

  • Best Practice: Use labels to specify a dedicated agent.


2.2 environment (Global Variables)

  • Stores environment variables.

  • Example:

  • Best Practice: Keep credentials in Jenkins Credentials Store instead of hardcoding them.


2.3 stages (Multi-Stage Structure)

Stage
Purpose

Checkout

Fetch source code

Build

Compile/build the application

Test

Run unit/integration tests

Push to Registry

Push Docker image to registry (e.g., Docker Hub, ECR, GCR)

Deploy

Deploy application


2.4 when Conditionals

  • Used to run stages conditionally.

  • Example: Run only on main branch:

  • Best Practice: Use when to avoid unnecessary runs on feature branches.


2.5 post Actions

  • Defines actions based on pipeline success/failure.

  • Example:


3. Optimized Jenkinsfile with Multi-Stage Docker Build


4. Multi-Stage Jenkinsfile with Parallel Execution

Best Practice: Use parallel to speed up execution.


5. Best Practices for Jenkinsfiles

✅ Use Declarative Pipelines

  • Prefer declarative syntax (pipeline {}) over scripted (node {}) for readability.

✅ Keep Secrets in Jenkins Credentials

  • Store API keys, Docker passwords securely:

✅ Use when Conditions for Better Control

  • Avoid unnecessary stages for non-main branches.

✅ Use Docker Caching

  • Improve build speed by caching layers.

✅ Implement Parallel Execution

  • Run independent stages in parallel to save time.


6. Scenario-Based Jenkinsfile Interview Questions

Q1: How do you run unit tests inside a container?

Answer: Use docker.image().inside {}


Q2: How do you ensure the deployment runs only on the main branch?

Answer: Use when { branch 'main' }


Q3: How do you store and use secrets securely in Jenkins?

Answer: Use withCredentials()


7. Summary

Topic
Key Takeaways

Multi-Stage Pipelines

Organize CI/CD workflows efficiently

Parallel Execution

Speed up build/test stages

when Condition

Control execution based on branch/environment

Docker Caching

Reduce build times

Jenkins Credentials

Store secrets securely

This multi-stage Jenkinsfile guide covers best practices, optimizations, and interview scenarios! 🚀 Let me know if you need more examples. 😊

Last updated