When there are a large number of Pipeline project build tasks, and a lot of code is duplicated, common logic needs to be extracted and reused. A Pipeline is essentially a Groovy script, so you can customize functions in a pipeline and use the language’s built-in features. For example, in the Jenkinsfile below, we have a custom createVersion function that uses the built-in Date class.

pipeline {
    agent any
    
    stages {
        stage ('build') {steps {// Output 201907-4echo "${createVersion(BUILD_NUMBER)}"
            }
        }
    }
}

def createVersion(String BUILD_NUMBER) {
    return new Date().format('yyyyMM') + "-${BUILD_NUMBER}"
}
Copy the code

A more elegant way to write this is to define variables within the environment

pipeline {
    agent any
    
    environment {
       _version = createVersion()
    }
    
    stages {
        stage ('build') {
            steps {
                echo "${_version}"
            }
        }
    }
}

def createVersion() {
    return new Date().format('yyyyMM') + "-${env.BUILD_NUMBER}"
}
Copy the code

Using shared libraries

General process:

  1. Create a new repository that contains shared library code

The jenkins-shared-library has been set up, and the file structure is as follows:

Global variables in the Vars directory can be used directly in pipeline, i.e. when you write sayHello(‘world’), you are actually calling the call function in sayhello.groovy

The SRC directory is the standard Java source code structure. The classes in the directory are called Library classes, and @library (‘global-shared-library@master’) statically loads all the code in the SRC directory into the classpath at once.

Classes in the SRC directory can automatically download third-party dependencies using the @grab annotation in Groovy

  1. Go to Jenkins’ Manage Jenkins -> Configure System -> Global Pipeline Libraries configuration page

  1. The Jenkins project pipeline introduces a shared library (you can specify the repository version and specific class) to create a new job of pipeline type. The content of Pipeline is as follows:
@Library('global-shared-library@master') _
pipeline {
    agent any
    
    environment {
       _version = createVersion()
    }
    
    stages {
        stage ('build') {
            steps {
                script {
                    def util = new com.mafeifan.Utils()
                    def version = util.createVersion("${BUILD_NUMBER}")
                    echo "${version}"
                    sayHello 'yes'
                    echo "${_version}"
                }
            }
        }
    }
}

def createVersion() {
    return new Date().format('yyyyMM') + "-${env.BUILD_NUMBER}"
}
Copy the code

Looking at the build log, we see that Jenkins pulled the shared library code first and executed successfully.

Implement Pipeline templates using shared libraries

// vars/generatePipeline.groovy

def call(String lang) {
  if (lang == 'go') {
    pipeline {
      agent any
       stages {
         stage ('set go path') {
            steps {
               echo "GO path is ready"
            }
         }
       }
    } 
  } else if (lang == 'java') {
    pipeline {
      agent any
       stages {
         stage ('clean install') {
            steps {
               sh "mvn clean install"}}}}} // Other languages}Copy the code

When used, Jenkinsfile has only two lines

@Library['global-shared-library'] _
generatePipeline('go')
Copy the code

If most projects are standardized, pipeline module technology for shared libraries can be used to reduce maintenance costs.

This is just a primer for writing more powerful shared libraries that need to know more about Groovy.

A custom function is preferred, if it appears in at least three projects, consider moving to a shared library, and consider using a Pipeline module if the projects’ pipelines are very similar.

reference

Jenkins. IO/useful/doc/book…