Skip to content

官方文档,https://www.jenkins.io/zh/doc/book/pipeline/shared-libraries/

1.什么是共享库

共享库并不是一个全新的概念,平时我们在写python,java等语言的时候,会引用各种包,比如import xxx from xxx。类似编程语言中的 代码复用 ,不同阶段可能有 共用 的地方

在Jenkins的共享库中使用Groovy的语法,共享库中存储了Groovy的各种类,每个文件又可以编写各种的方法

2.共享库的结构

一般来说,共享库的结构分为可以分为resourcesrcvars。其结构如下

(root)
+- src                     # Groovy source files
|   +- org
|       +- foo
|           +- Bar.groovy  # for org.foo.Bar class
+- vars
|   +- foo.groovy          # for global 'foo' variable
|   +- foo.txt             # help for 'foo' variable
+- resources               # resource files (external libraries only)
|   +- org
|       +- foo
|           +- bar.json    # static helper data for org.foo.Bar
(root)
+- src                     # Groovy source files
|   +- org
|       +- foo
|           +- Bar.groovy  # for org.foo.Bar class
+- vars
|   +- foo.groovy          # for global 'foo' variable
|   +- foo.txt             # help for 'foo' variable
+- resources               # resource files (external libraries only)
|   +- org
|       +- foo
|           +- bar.json    # static helper data for org.foo.Bar

参数解释

参数说明
resource目录允许从'外部库中'使用步骤来'加载相关联的非Groovy的资源文件
src目录主要存放我们要'编写的groovy类',执行流水线时,此目录将添加到class_path中
vars是用来放各种参数文件,定义变量

==其实也不是只有这些,一层目录也可以放诸如doc等文件来放文档。这都根据实际的需要==

3.jenkins上 配置做

bash
manage Jenkins-----> configure system --->ctrl+f(Google浏览器)--->lib进行定位---->Global Pipeline Libraries
manage Jenkins-----> configure system --->ctrl+f(Google浏览器)--->lib进行定位---->Global Pipeline Libraries
  • 步骤

4.使用

在groovy脚本中的使用:@Library("库名称@分支") 这个库名称和分支就是在jenkins中设置的名称

调用方式:

groovy
@Library('jenkinslib@master') _
def tools = new org.devops.tools()

//jenkinslib 这个名字随便写,不是仓库名字决定,但是这个名字必须和jenkins 配置共享库的名字一致
//注释,org.devops.tools 是src里脚本的位置,导入调用
@Library('jenkinslib@master') _
def tools = new org.devops.tools()

//jenkinslib 这个名字随便写,不是仓库名字决定,但是这个名字必须和jenkins 配置共享库的名字一致
//注释,org.devops.tools 是src里脚本的位置,导入调用
  • 多个库调用
groovy
// 加载mylib共享库
@Library('mylib') _
 
 
// 加载mylib共享库的1.0版本
@Library('mylib@1.0') _
 
 
// 加载多个共享库, mylib共享库的默认版本, yourlib共享库的2.0版本(分支)
@Library(['mylib', 'yourlib@2.0']) _
// 加载mylib共享库
@Library('mylib') _
 
 
// 加载mylib共享库的1.0版本
@Library('mylib@1.0') _
 
 
// 加载多个共享库, mylib共享库的默认版本, yourlib共享库的2.0版本(分支)
@Library(['mylib', 'yourlib@2.0']) _
groovy
#!groovy
 
@Library('jenkinslib@master') _
def tools = new org.devops.tools()
 
pipeline{
    agent{
        node{
            label "master"
        }
    }
     
    stages{
        stage("Build"){
            steps{
                script{
                    tools.PrintMes("执行打包","green")
                     
                }
            }
        }  
    }
}
#!groovy
 
@Library('jenkinslib@master') _
def tools = new org.devops.tools()
 
pipeline{
    agent{
        node{
            label "master"
        }
    }
     
    stages{
        stage("Build"){
            steps{
                script{
                    tools.PrintMes("执行打包","green")
                     
                }
            }
        }  
    }
}

4.1共享库创建

在src/org/devops目录中创建utils.groovy文件,内容如下

groovy
package org.devops
def getVersion(String BUILD_NUMBER, String GIT_COMMIT){
    return new Date().format('yyMM')+"-${BUILD_NUMBER}"+"-${GIT_COMMIT}"
}
package org.devops
def getVersion(String BUILD_NUMBER, String GIT_COMMIT){
    return new Date().format('yyMM')+"-${BUILD_NUMBER}"+"-${GIT_COMMIT}"
}

4.2pipeline中的使用

groovy
#!groovy
 
@Library('jenkinslib@master') _
def util = new org.devops.utils()
 
pipeline{
    agent{
        node{
            label "master"
        }
    }
     
    stages{
        stage("Build"){
            steps{
                script{
                    def v = util.getVersion("${BUILD_NUMBER}","${GIT_COMMIT}")
                    echo "${v}"
                }
            }
        }
     
    }
 
}
#!groovy
 
@Library('jenkinslib@master') _
def util = new org.devops.utils()
 
pipeline{
    agent{
        node{
            label "master"
        }
    }
     
    stages{
        stage("Build"){
            steps{
                script{
                    def v = util.getVersion("${BUILD_NUMBER}","${GIT_COMMIT}")
                    echo "${v}"
                }
            }
        }
     
    }
 
}

4.3resource

使用resource/里的文件

用法:

1.resources/xxx.json文件

groovy
cat jenkinslib/resources/config.json
{
    "name": "jin tian"
 
}
cat jenkinslib/resources/config.json
{
    "name": "jin tian"
 
}

2.vars/Pipeline.groovy

groovy
cat jenkinslib/vars/Pipeline.groovy

import hwf.devops.Tools
 
def call(Map args){
    def tools = new Tools()
 
    pipeline {
        agent { label "build"}
 
        stages{
            stage("build"){
                steps{
                    script{
                         //加载resource里的文件
                        config = libraryResource '/config.json'
                        config = readJSON text: config -"\n"
                        value = tools.PrintMsg("hwf")
                        println(config.name)
 
                    }
                }
            }
        }
    }
}
cat jenkinslib/vars/Pipeline.groovy

import hwf.devops.Tools
 
def call(Map args){
    def tools = new Tools()
 
    pipeline {
        agent { label "build"}
 
        stages{
            stage("build"){
                steps{
                    script{
                         //加载resource里的文件
                        config = libraryResource '/config.json'
                        config = readJSON text: config -"\n"
                        value = tools.PrintMsg("hwf")
                        println(config.name)
 
                    }
                }
            }
        }
    }
}

5.案例

5.1颜色案例

注意:我们需要安装 插件AnsiColor,这样才能使用ansiColor()方法,可以在片段生成器查看更多的用法

groovy
ansiColor('css') {
  sh "ls -al"
}


echo 'this will be rendered as-is'
// multiple ansiColor steps within one pipeline are also supported


ansiColor('vga') {
  echo '\033[42m\033[97mWhite letters, green background\033[0m'
}
ansiColor('css') {
  sh "ls -al"
}


echo 'this will be rendered as-is'
// multiple ansiColor steps within one pipeline are also supported


ansiColor('vga') {
  echo '\033[42m\033[97mWhite letters, green background\033[0m'
}
  • 创建tool.groovy
groovy
package org.devops


//格式化输出
def PrintMes(value,color){
    colors = ['red'   : "\033[40;31m >>>>>>>>>>>${value}<<<<<<<<<<< \033[0m",
              'blue'  : "\033[47;34m ${value} \033[0m",
              'green' : "\033[40;32m >>>>>>>>>>>${value}<<<<<<<<<<< \033[0m" ]
    ansiColor('xterm') {
        println(colors[color])
    }
}
package org.devops


//格式化输出
def PrintMes(value,color){
    colors = ['red'   : "\033[40;31m >>>>>>>>>>>${value}<<<<<<<<<<< \033[0m",
              'blue'  : "\033[47;34m ${value} \033[0m",
              'green' : "\033[40;32m >>>>>>>>>>>${value}<<<<<<<<<<< \033[0m" ]
    ansiColor('xterm') {
        println(colors[color])
    }
}

var路径下创建一个hello.groovy的文件,我们只输出一个hello

  • 创建hello.groovy
groovy
def call(){
    println("hello")
}
def call(){
    println("hello")
}
  • 使用共享库

系统配置里找到 Global Pipeline Libraries

echo2

  • 编写jenkinsfile

在Jenkinsfile中使用@Library('jenkins-sharelib-tools') _来加载共享库,注意后面符号_用于加载。类的实例化def tools = new org.devops.tools(),使用类中的方法tools.PrintMes("获取代码",'green')

groovy
#!groovy
@Library('jenkins-sharelib-tools') _     
def tools = new org.devops.tools()
pipeline {
    agent { node {  label "master" }}
stages {
        //下载代码
        stage("GetCode"){ 
            steps{  
                timeout(time:5, unit:"MINUTES"){   
                    script{ 
                        tools.PrintMes("获取代码",'green')
                        hello.call()
                    }
                }
            }
        }
    }
}
#!groovy
@Library('jenkins-sharelib-tools') _     
def tools = new org.devops.tools()
pipeline {
    agent { node {  label "master" }}
stages {
        //下载代码
        stage("GetCode"){ 
            steps{  
                timeout(time:5, unit:"MINUTES"){   
                    script{ 
                        tools.PrintMes("获取代码",'green')
                        hello.call()
                    }
                }
            }
        }
    }
}
  • 创建一个pipeline

我们流水线的类型,选择Pipeline script from SCM。我们配置一个gitlab的仓库然后将jenkinsfile放入

注意, 我们在同一个仓库下可以添加多个jenkinsfile,可以用名字来区分,也可以建多个路径,比如我放到tools路径下面,就需要配置./tools/Jenkinsfile.之前的共享库,其实也可以在org路径下,放多个文件,适用于不同的情况

5.2gitlab

官方文档,https://docs.gitlab.com/ee/api/branches.html

  • postman 调试

  • 在jenkins中操作

  • 配置gitlab token

  • 配置jenkins token

  • 生成pipeline

groovy
withCredentials([string(credentialsId: 'e0c7ba82-67da-42a0-ae98-95cf0c019569', variable: 'GITLABTOKEN')]) {
    // some block
}
withCredentials([string(credentialsId: 'e0c7ba82-67da-42a0-ae98-95cf0c019569', variable: 'GITLABTOKEN')]) {
    // some block
}
  • 完整代码

vi Jenkinsfile

groovy
@Library("sharelib") _

//导入
def gitab = new org.devops.gitlab()

pipeline {
	agent { label "master"}
	
	stages{
		stage("test"){
			steps{
				script{
					/*withCredentials([string(credentialsId: 'e0c7ba82-67da-42a0-ae98-95cf0c019569', variable: 'GITLABTOKEN')]) {
					sh """
					//Create branch
						curl --location \
						     --request POST \
						     "http://192.168.1.22/api/v4/projects/2/repository/branches?branch=${env.branchName}&ref=${env.baseBranch}" \
						     --header "PRIVATE-TOKEN: ${GITLABTOKEN}"
					"""
					}*/
					projectId = GetprojectId(${env.projectName}")
					CreateBranch(projectId, "${env.branchName}", "${env.baseBranch}")
					
					/*
					projectId = gitlab.GetprojectId(${env.projectName}")
					gitlab.CreateBranch(projectId, "${env.branchName}", "${env.baseBranch}")
					*/
				}
			}
		}
	}
}


//
def HttpReq(apiURL, method){
	gitlabURL = "http://192.168.1.22/api/v4"
	withCredentials([string(credentialsId: 'e0c7ba82-67da-42a0-ae98-95cf0c019569', variable: 'GITLABTOKEN')]) {
				response =	sh returnStdout: true, script: """
					//Create branch
						curl --location \
						     --request POST \
						     "${gitlabURL}/${apiURL}" \
						     --header "PRIVATE-TOKEN: ${GITLABTOKEN}"
					"""
	}
	return response
}


//创建分支
def CreateBranch(projectId, branchName, baseBranch){
	
	apiURL = "projects/${projectId}/repository/branches?branch=${branchName}&ref=${baseBranch}"
	HttpReq(apiURL, "POST")
	
	/*withCredentials([string(credentialsId: 'e0c7ba82-67da-42a0-ae98-95cf0c019569', variable: 'GITLABTOKEN')]) {
					sh """
					//Create branch
						curl --location \
						     --request POST \
						     "http://192.168.1.22/api/v4/projects/${projectId}/repository/branches?branch=${branchName}&ref=${baseBranch}" \
						     --header "PRIVATE-TOKEN: ${GITLABTOKEN}"
					"""
	}*/
}


//获取项目 id
def GetprojectId(projectName){
	apiURL = "project?search=${projectName}"
	result = HttpReq(apiURL, "GET")
	result = readJSON test: result
	
	return result[0]["id"]
	
	/*withCredentials([string(credentialsId: 'e0c7ba82-67da-42a0-ae98-95cf0c019569', variable: 'GITLABTOKEN')]) {
					sh """
					//Create branch
						curl --location \
						     --request POST \
						     "http://192.168.1.22/api/v4/projects/${projectId}/repository/branches?branch=${branchName}&ref=${baseBranch}" \
						     --header "PRIVATE-TOKEN: ${GITLABTOKEN}"
					"""
	}*/
}
@Library("sharelib") _

//导入
def gitab = new org.devops.gitlab()

pipeline {
	agent { label "master"}
	
	stages{
		stage("test"){
			steps{
				script{
					/*withCredentials([string(credentialsId: 'e0c7ba82-67da-42a0-ae98-95cf0c019569', variable: 'GITLABTOKEN')]) {
					sh """
					//Create branch
						curl --location \
						     --request POST \
						     "http://192.168.1.22/api/v4/projects/2/repository/branches?branch=${env.branchName}&ref=${env.baseBranch}" \
						     --header "PRIVATE-TOKEN: ${GITLABTOKEN}"
					"""
					}*/
					projectId = GetprojectId(${env.projectName}")
					CreateBranch(projectId, "${env.branchName}", "${env.baseBranch}")
					
					/*
					projectId = gitlab.GetprojectId(${env.projectName}")
					gitlab.CreateBranch(projectId, "${env.branchName}", "${env.baseBranch}")
					*/
				}
			}
		}
	}
}


//
def HttpReq(apiURL, method){
	gitlabURL = "http://192.168.1.22/api/v4"
	withCredentials([string(credentialsId: 'e0c7ba82-67da-42a0-ae98-95cf0c019569', variable: 'GITLABTOKEN')]) {
				response =	sh returnStdout: true, script: """
					//Create branch
						curl --location \
						     --request POST \
						     "${gitlabURL}/${apiURL}" \
						     --header "PRIVATE-TOKEN: ${GITLABTOKEN}"
					"""
	}
	return response
}


//创建分支
def CreateBranch(projectId, branchName, baseBranch){
	
	apiURL = "projects/${projectId}/repository/branches?branch=${branchName}&ref=${baseBranch}"
	HttpReq(apiURL, "POST")
	
	/*withCredentials([string(credentialsId: 'e0c7ba82-67da-42a0-ae98-95cf0c019569', variable: 'GITLABTOKEN')]) {
					sh """
					//Create branch
						curl --location \
						     --request POST \
						     "http://192.168.1.22/api/v4/projects/${projectId}/repository/branches?branch=${branchName}&ref=${baseBranch}" \
						     --header "PRIVATE-TOKEN: ${GITLABTOKEN}"
					"""
	}*/
}


//获取项目 id
def GetprojectId(projectName){
	apiURL = "project?search=${projectName}"
	result = HttpReq(apiURL, "GET")
	result = readJSON test: result
	
	return result[0]["id"]
	
	/*withCredentials([string(credentialsId: 'e0c7ba82-67da-42a0-ae98-95cf0c019569', variable: 'GITLABTOKEN')]) {
					sh """
					//Create branch
						curl --location \
						     --request POST \
						     "http://192.168.1.22/api/v4/projects/${projectId}/repository/branches?branch=${branchName}&ref=${baseBranch}" \
						     --header "PRIVATE-TOKEN: ${GITLABTOKEN}"
					"""
	}*/
}