jenkins 共享库

创建共享库

gitlab创建共享库

可以直接在github中创建一个公开类型的仓库,也可以创建私有类型的gitlab仓库,需要提前配置好仓库的认证凭据,这里使用gitlab创建了一个名为jenkinslib的项目作为共享库,并创建类文件和Jenkinsfile文件 /src/org/devops/tools.groovy 和Jenkinsfile

image

定义类方法

如在tools.groovy中定义PrintMsg(msg)

pacakge org.devops
//打印信息
def PrintMsg(msg){
  println(msg)
}

Jenkinsfile引用类

在Jenkinsfile中使用 @Library(‘jenkinslib’) _ 来加载共享库,注意后面符号 _ 用于加载,类的实例化 def mytools = new org.devops.tools(),使用上面Groovy类文件中的方法 PrintMsg(msg),如下:

@Library('jenkinslib') _     
def tools = new org.devops.tools()
pipeline {
 
	agent { label  "master" }
 
	stages {
		stage("build"){
			steps{
				script{
					msg = "hello jenkins"
					tools.PrintMsg(msg)
				}
			}
		}
	}
}

在Jenkins中使用共享库

在Jenkins中配置共享库

Jenkins系统配置 -> Global Pipeline Libraries
首先,为共享库设置一个名称 jenkinslib (自定义,无需与gitlab仓库一致),注意这个名称后续在Jenkinsfile中引用,再设置一个默认的版本,这里的版本是分支的名称,我这配置的是master版本。

jenkins配置->系统配置
image

image

在pipeline使用库

在pipeline使用共享库,流水线定义为 pipeline script from SCM方式,在URL中配置共享库的仓库地址,我的仓库在gitlab中,所以这里填写的是gitlab的项目地址,(如果你用的是github可以使用github方式),如果仓库是私有的方式,需要在jenkins的凭据中添加一个账号用于下载共享库。
image

image

保存Jenkins配置,执行pipeline,控制台输出:打印msg(hello Jenkins)

image

项目中定义的vars的作用

image

image

def call(){
    println("hello,test vars")
}

hello在任意位置调用
image

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

hello()
pipeline {
 
	agent any
	stages {
		stage("build"){
			steps{
				script{
					msg = "hello jenkins"
					tools.PrintMsg(msg)
				}
			}
		}
	}
}

image

转自

https://blog.csdn.net/weixin_44802620/article/details/125133847