Note_Tech

All technological notes.


Project maintained by simonangel-fong Hosted on GitHub Pages — Theme by mattgraham

Jenkins - Pipeline & Jenkinsfile

Back


Jenkins Pipeline

pic


Pipeline fundamental

Best Practice


Node vs Agent


node {
    checkout scm
    sh 'mvn test'
}

// choose a specific agent by label
node('linux && docker') {
    sh 'docker build -t myapp .'
}

// using in declarative pipeline
pipeline {
    agent none
    stages {
        stage('Build') {
            steps {
                script {
                    node('build-node') {
                        echo 'Building on build-node...'
                    }
                }
            }
        }
    }
}

pipeline {
    agent any
}


Tools

pipeline {
    agent any
    tools {
        // Define the tools and their configurations here
        maven 'MavenTool' // Name of the tool and the tool installation name
        jdk 'JDKTool'    // Name of the tool and the tool installation name
    }
    stages {
        // Define your pipeline stages here
        stage('Build') {
            steps {
                // Use the configured tools in your pipeline stages
                script {
                    sh '''#!/bin/bash
                    echo "Building with Maven"
                    mvn clean package
                    '''
                }
            }
        }
    }
}

Options


Upstream and Downstream projects


Throttle Concurrent Builds


Steps

Handle Credentials

// scope secrets as narrowly as possible
stage('Call API') {
    steps {
        withCredentials([string(credentialsId: 'my-api-token', variable: 'API_TOKEN')]) {
            sh '''
              set +x
              curl -H "Authorization: Bearer $API_TOKEN" https://api.example.com
            '''
        }
    }
}

Milestone

pipeline {
    agent any
    stages {
        stage('Deploy') {
            steps {
                // Ensure no older build deploys after this point
                milestone 1
                echo "1111"
                milestone 2
                echo "2222"
            }
        }
    }
}


Script Block

pipeline {
    agent any
    stages {
        stage('demo') {
            steps {
                // Standard declarative step
                echo 'Starting...'

                script {
                    // Scripted Groovy logic begins here
                    def browser = 'chrome'
                    if (browser == 'chrome') {
                        echo 'Running tests in Chrome'
                    } else {
                        echo 'Running tests in default browser'
                    }
                }
            }
        }
    }
}

Common workflow controls

pipeline {
    agent any
    options {
        parallelsAlwaysFailFast()   // fail-fast behavior
    }
    stages {
        stage('Test') {
            parallel {
                stage('A') {
                    steps { sh './test-a.sh' }
                }
                stage('B') {
                    steps { sh './test-b.sh' }
                }
            }
        }
    }
}

Shared Library


@Library('my-shared-library') // Reference the Shared Library

// Import custom steps
import com.example.CustomPipelineSteps

pipeline {
    agent any
    stages {
        stage("Build") {
            steps {
                script {
                    CustomPipelineSteps.build() // Use a custom step from the Shared Library
                }
            }
        }
        stage('Test') {
            steps {
                script {
                    CustomPipelineSteps.test() // Another custom step
                }
            }
        }
    }
}

Sample: Docker build and push

pipeline {
  agent any
  stages {
    stage('Build') {
      steps {
        script {
          docker.build("my-app:${env.BUILD_ID}")
        }
      }
    }
    stage('Push') {
      steps {
        script {
          docker.withRegistry('https://www.docker.com/', 'docker-hub-credentials') {
            docker.image("my-app:${env.BUILD_ID}").push()
          }
        }
      }
    }
  }
}

Sample: Deploy pipeline

pipeline {
    agent any

    options {
        disableConcurrentBuilds()
        timeout(time: 30, unit: 'MINUTES')
    }

    stages {
        stage('Plan') {
            steps {
                retry(2) {
                    sh 'terraform plan'
                }
            }
        }

        stage('Approval') {
            input {
                message 'Apply infrastructure changes?'
                ok 'Apply'
            }
            steps {
                echo 'Approved'
            }
        }

        stage('Apply') {
            steps {
                sh 'terraform apply -auto-approve'
            }
        }
    }

    post {
        success {
            echo 'Success!'
        }
        failure {
            echo 'Failed!'
        }
    }
}

Sample: Fast CI pipeline

pipeline {
    agent any
    options {
        parallelsAlwaysFailFast()
    }

    stages {
        stage('Checks') {
            parallel {
                stage('Lint') {
                    steps { sh 'npm run lint' }
                }
                stage('Unit Test') {
                    steps { sh 'npm test' }
                }
                stage('Security Scan') {
                    steps { sh './scan.sh' }
                }
            }
        }
    }
}

Lab: Create Pipeline

pipeline {
    agent any

    stages {
        stage('Build') {
            steps {
                echo 'Build ...'
                sh """
                    echo 'multiple steps:'
                    pwd
                    date
                    hostname
                """
            }
        }

        stage('Test') {
            steps {
                echo 'Testing ...'
            }
        }

        stage('Deploy') {
            steps {
                echo 'Deploy ...'
            }
        }
    }

    post {
        success {
            echo 'Success!'
        }
        failure {
            echo 'Failed!'
        }
    }
}

Lab: Demo Retry

pipeline {
    agent any

    stages {
        stage('Retry') {
            steps {
                retry(3){
                    sh 'deliberate error'
                }
            }
        }
    }
}

pic


Lab: Demo Timeout

pipeline {
    agent any

    stages {
        stage('Deploy') {
            steps {
                timeout(time: 3, unit: "SECONDS"){
                    sh 'sleep 5'
                }
            }
        }
    }
}

pic


Lab: Parallel statge pipeline

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

pic

pic