共享库
共享库

目录
[toc]
环境
- 实验环境
1jenkins/jenkins:2.346.3-2-lts-jdk11
2gitee仓库/github仓库/gitlab仓库都行
- 实验软件
链接:https://pan.baidu.com/s/12a9iRveUOUbQpSNAE7WhIw
提取码:0820
2023.4.11-共享库-代码

1、共享库概述
共享库这并不是一个全新的概念,其实在编程语言Python中,我们可以将Python代码写到一个文件中,当代码数量增加,我们可以将代码打包成模块然后再以import的方式使用此模块中的方法。
在Jenkins中使用Groovy语法,共享库中存储的每个文件都是一个groovy的类,每个文件(类)中包含一个或多个方法。每个方法包含groovy语句块。
可以在Git等版本控制系统中创建一个项目用于存储共享库。共享流水线有助于减少冗余并保持代码整洁。

库结构:
- src: 类似于java的源码目录,执行流水线时会加载到class路径中。 //需要先导入才可以使用
- vars: 存放全局变量脚本,小的功能函数。 //可以直接加载的
- resources: 存放资源文件,类似于配置信息文件。
2、共享库定义
1.创建一个项目
devops06-jenkins-library
可以直接在github中创建一个公开类型的仓库,仓库名称自定义。公开类型的仓库是为了便于验证,也可以创建私有类型的,但是需要提前配置好仓库的认证凭据。

2.创建目录结构

1src
2vars
3rsources
3.将函数写入共享库中
1、创建resources/config/config.json文件

1{
2 "id": 100,
3 "name": "devops"
4}
2、创建src/og/devops/Common.groovy文件

1package org.devops
2
3// define GetUserName
4def GetUserNameByID(users,id){
5 for (i in users){
6 if (i["id"] == id){
7 return i["name"]
8 }
9 }
10 return "null"
11}
3、创建vars/GetUserName.groovy文件

1// define GetUserName
2def GetUserNameByID(users,id){
3 for (i in users){
4 if (i["id"] == id){
5 return i["name"]
6 }
7 }
8 return "null"
9}
提交:(这里以main分支提交)


4.共享库的定义

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

⚠️ 注意:
- 这里的Name不一定和刚才创建的仓库名称一样,只是一个别名而已;
- 这里的Default version填的是仓库的分支名称;
- 共享库是可以配置多个的!
- 接下来我们配置**共享库的仓库地址,**我的仓库在gitlab中,所以这里我填写的是Git的方式。如果仓库是私有的方式,需要在jenkins的凭据中添加一个账号用于下载共享库。


点击Save。
3、共享库使用

测试1:基础使用共享库
- 编写Jenkinsfile代码,并提交:

1@Library("mylib") _
2
3pipeline {
4 agent any
5
6 stages{
7 stage("Test"){
8 steps{
9 script{
10 echo "hello world!"
11 }
12 }
13 }
14 }
15}
提交:

⚠️
==注意:这里出现一个gitlab报错的问题……在定义共享库配置后:说是无法解析刚才的仓库地址==
1hudson.plugins.git.GitException: Command "git ls-remote -h -- http://440c1581aeec/root/devops06-jenkins-library.git" returned status code 128:
2stdout:
3stderr: fatal: unable to access 'http://440c1581aeec/root/devops06-jenkins-library.git/': Could not resolve host: 440c1581aeec

- 开始执行流水线:
这里再配置下流水线,让其使用gitlab里的仓库:


- 运行后,这里会报错……

- 奇怪哇:
自己把这个字符串和本地机器做了域名解析,在自己pc上是可以正常拉取仓库的,但是jenkins是不行的……


这个应该是gitlab哪里的配置问题……
这里先进行搁置,此时用gitee来测试。
- 在自己的gitee上创建相同的配置:

- 然后重新配置jenkins及流水线内容:


- 再次运行,观察效果:

看到,这次就成功了。😘
测试2:src目录里导包
编写Jenkinsfile代码:


1@Library("mylib") _
2
3//import Common.groovy
4def common = new org.devops.Common()
5
6users = [
7 ["id": 1, "name": "jenkins1"],
8 ["id": 2, "name": "jenkins2"],
9 ["id": 3, "name": "jenkins3"],
10 ]
11
12
13pipeline {
14 agent any
15
16 stages{
17 stage("Test"){
18 steps{
19 script{
20 echo "hello world!"
21 name = common.GetUserNameByID(users,1)
22 print(name)
23 }
24 }
25 }
26 }
27}
提交,并运行流水线。


符合预期。
测试3:vars里函数调用
- 编写jenkins代码
错误版演示:


提交并运行流水线:

可以看到会报错的。
- 我们再来演示下正确版写法:

call是固定写法:

1@Library("mylib") _
2
3//import Common.groovy
4def common = new org.devops.Common()
5
6users = [
7 ["id": 1, "name": "jenkins1"],
8 ["id": 2, "name": "jenkins2"],
9 ["id": 3, "name": "jenkins3"],
10 ]
11
12
13pipeline {
14 agent any
15
16 stages{
17 stage("Test"){
18 steps{
19 script{
20 echo "hello world!"
21 name = common.GetUserNameByID(users,1)
22 print(name)
23
24 echo "vars output demo"
25 name = GetUserName(users,2)
26 print(name)
27 }
28 }
29 }
30 }
31}
- 提交并运行:

符合预期。
测试4:资源文件引用
- 代码


1@Library("mylib") _
2
3//import Common.groovy
4def common = new org.devops.Common()
5
6users = [
7 ["id": 1, "name": "jenkins1"],
8 ["id": 2, "name": "jenkins2"],
9 ["id": 3, "name": "jenkins3"],
10 ]
11
12
13pipeline {
14 agent any
15
16 stages{
17 stage("Test"){
18 steps{
19 script{
20 echo "src output demo"
21 name = common.GetUserNameByID(users,1)
22 print(name)
23
24 echo "vars output demo"
25 name = GetUserName(users,2) //注意:这里输出的是字符串数据
26 print(name)
27
28 echo "get resources"
29 data = libraryResource 'config/config.json'
30 println(data)
31
32 }
33 }
34 }
35 }
36}
- 提交并运行

测试5:处理json数据
- 安装
pipeline util插件(安装了这个插件后,才能使用这些语法)


- 代码

1@Library("mylib") _
2
3//import Common.groovy
4def common = new org.devops.Common()
5
6users = [
7 ["id": 1, "name": "jenkins1"],
8 ["id": 2, "name": "jenkins2"],
9 ["id": 3, "name": "jenkins3"],
10 ]
11
12
13pipeline {
14 agent any
15
16 stages{
17 stage("Test"){
18 steps{
19 script{
20 echo "src output demo"
21 name = common.GetUserNameByID(users,1)
22 print(name)
23
24 echo "vars output demo"
25 name = GetUserName(users,2)
26 print(name)
27
28
29 echo "get resources"
30 data = libraryResource 'config/config.json' //这里是字符串数据
31 println(data)
32
33 //这里是json数据
34 data_json = readJSON text: data
35 println(data_json["id"])
36
37 }
38 }
39 }
40 }
41}
- 运行

4、代码汇总
Jenkinsfile

1@Library("mylib") _
2
3//import Common.groovy
4def common = new org.devops.Common()
5
6users = [
7 ["id": 1, "name": "jenkins1"],
8 ["id": 2, "name": "jenkins2"],
9 ["id": 3, "name": "jenkins3"],
10 ]
11
12
13pipeline {
14 agent any
15
16 stages{
17 stage("Test"){
18 steps{
19 script{
20 echo "src output demo"
21 name = common.GetUserNameByID(users,1)
22 print(name)
23
24 echo "vars output demo"
25 name = GetUserName(users,2)
26 print(name)
27
28
29 echo "get resources"
30 data = libraryResource 'config/config.json' //这里是字符串数据
31 println(data)
32
33 //这里是json数据
34 data_json = readJSON text: data
35 println(data_json["id"])
36
37 }
38 }
39 }
40 }
41}
Common.groovy

1package org.devops
2
3// define GetUserName
4def GetUserNameByID(users,id){
5 for (i in users){
6 if (i["id"] == id){
7 return i["name"]
8 }
9 }
10 return "null"
11}
GetUserName.groovy

1// define GetUserName
2def call(users,id){
3 for (i in users){
4 if (i["id"] == id){
5 return i["name"]
6 }
7 }
8 return "null"
9}
config.json

1{
2 "id": 100,
3 "name": "devops"
4}
FAQ
TemplatingEngine实践(扩展)🍊
准备JTE代码
准备Librarys Resource仓库: 根目录例如gradle和maven都是单独的library, 目录下steps是我们具体定义的功能函数。

准备配置Pipeline Template和Configuration Files:
pipeline_config.groovy
1//加载的仓库
2libraries{
3 sonarqube
4 gradle
5}
6
7// 环境变量
8application_environments{
9 dev {
10 short_name = "t"
11 }
12 test
13}
Jenkinsfile
1pipeline {
2 agent {
3 label "master"
4 }
5
6 stages{
7 stage("build"){
8 steps{
9 build(dev.short_name)
10 build_test()
11 }
12 }
13 }
14}
安装JTE插件
安装Templating Engine插件

进入系统配置,配置插件:


Pipeline测试
创建一条Pipeline

ConsoleOutput
1Started by user unknown or anonymous
2[JTE] Obtained Pipeline Configuration File (show)
3[JTE] Pipeline Configuration Modifications (show)
4[JTE] Obtained Template (show)
5[JTE] Loading Library sonarqube (show)
6[JTE] Loading Library gradle (show)
7[JTE] Template Primitives are overwriting Jenkins steps with the following names: (show)
8[Pipeline] Start of Pipeline
9[Pipeline] node
10Running on Jenkins in /var/jenkins_home/workspace/demo-jte-pipeline
11[Pipeline] {
12[Pipeline] stage
13[Pipeline] { (build)
14[JTE][Step - gradle/build.call(String)]
15[Pipeline] echo
16gradle build
17[Pipeline] echo
18t
19[JTE][Step - gradle/build_test.call()]
20[Pipeline] readJSON
21[Pipeline] echo
22{"name":"jenkins","id":"devopsvip"}
23[Pipeline] }
24[Pipeline] // stage
25[Pipeline] }
26[Pipeline] // node
27[Pipeline] End of Pipeline
28Finished: SUCCESS
参考文档
https://www.jenkins.io/blog/2019/05/09/templating-engine/
示例代码库:
https://jihulab.com/devopsvip/demo-jte-config
https://jihulab.com/devopsvip/demo-jte-lib
12023.4.11-TemplatingEngine实践(扩展)-测试代码
链接:https://pan.baidu.com/s/1C_RaCMCH5PxzNsQ2sVm_5g
提取码:0820

关于我
我的博客主旨:
- 排版美观,语言精炼;
- 文档即手册,步骤明细,拒绝埋坑,提供源码;
- 本人实战文档都是亲测成功的,各位小伙伴在实际操作过程中如有什么疑问,可随时联系本人帮您解决问题,让我们一起进步!
🍀 微信二维码
x2675263825 (舍得), qq:2675263825。

🍀 微信公众号
《云原生架构师实战》

🍀 个人主页:

🍀 知识库:
https://onedayxyy.cn/docusaurus/

🍀 博客:
http://47.100.215.163:8090/


🍀 csdn
https://blog.csdn.net/weixin_39246554?spm=1010.2135.3001.5421

🍀 知乎
https://www.zhihu.com/people/foryouone

最后
好了,关于本次就到这里了,感谢大家阅读,最后祝大家生活快乐,每天都过的有意义哦,我们下期见!

