海龟 發表於 2025-10-13 21:01:00

Jenkins Share Library教程 —— 开发入门

<h3 id="写在前面">写在前面</h3>
<p>今日心情有点小丧,但总体问题不大,有一些突然来的活,还没整完,明天再继续搞把。</p>
<p>有难度吗?</p>
<p>有一些把,我觉得还是要做一些自己不擅长的工作,才会有成长的吧,为什么?</p>
<p>用我们测试同学的话术,就是提升“自己”的“测试覆盖率”,即<strong>解决问题的能力</strong>,核心就是<strong>会了就是赚了!</strong></p>
<h3 id="学习目标">学习目标</h3>
<p>通过本教程,你将学会:</p>
<p>✅ 理解 Jenkins Shared Library 是什么<br>
✅ 创建自己的共享库项目(Git 仓库)<br>
✅ 在 Jenkinsfile 中调用共享库<br>
✅ 实际运行一个示例流水线<br>
✅ 能独立维护公司内部的通用 Jenkins 函数</p>
<hr>
<h3 id="一什么是-jenkins-shared-library">一、什么是 Jenkins Shared Library?</h3>
<blockquote>
<p>可以把 Jenkins 比喻成一个“厨师”,而 Shared Library 就是一份“菜谱合集”。</p>
</blockquote>
<p>在没有共享库时,每个 Jenkinsfile 都要写重复的步骤,比如:</p>
<pre><code class="language-groovy">pipeline {
agent any
stages {
    stage('Build') {
      steps {
      sh 'mvn clean install'
      }
    }
    stage('Test') {
      steps {
      sh 'mvn compile test'
      }
    }
}
}
</code></pre>
<p>几百个项目要是都这样写的话,会非常麻烦。</p>
<p>于是我们可以把这些公共逻辑抽取出来放到一个“共享库”里,以后只要一句话就能复用。</p>
<p>也就是可以直接通过方法实现调用:</p>
<pre><code class="language-groovy">@Library('my-shared-lib') _
pipeline {
agent any
stages {
    stage('Build &amp; Test') {
      steps {
      myPipeline.buildAndTest()
      }
    }
}
}
</code></pre>
<p>这样,所有项目就能共享一套逻辑,方便统一管理和维护。</p>
<hr>
<h3 id="二准备环境">二、准备环境</h3>
<h4 id="你需要的环境">你需要的环境</h4>
<table>
<thead>
<tr>
<th>工具</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>Jenkins</td>
<td>版本 &gt;= 2.3(最好用 LTS)</td>
</tr>
<tr>
<td>Git</td>
<td>版本管理工具</td>
</tr>
<tr>
<td>一个 Git 仓库</td>
<td>用来存放共享库代码(GitHub / GitLab 都行)</td>
</tr>
</tbody>
</table>
<hr>
<h3 id="三创建共享库项目">三、创建共享库项目</h3>
<p>在你的 Git 仓库中新建项目,例如:</p>
<pre><code>https://github.com/yourname/jenkins-shared-lib-demo
</code></pre>
<p>项目结构如下:</p>
<pre><code>jenkins-shared-lib-demo/
├── vars/
│   └── helloWorld.groovy
├── src/
│   └── org/example/Utils.groovy
└── resources/
    └── templates/email.txt
</code></pre>
<hr>
<h3 id="四编写第一个共享函数">四、编写第一个共享函数</h3>
<p>新建文件:<code>vars/helloWorld.groovy</code></p>
<pre><code class="language-groovy">def call(String name = 'Jenkins') {
    echo "Hello, ${name}! Welcome to Shared Library!"
}
</code></pre>
<p>解释:</p>
<ul>
<li><code>vars/</code> 目录下的每个 <code>.groovy</code> 文件会自动变成一个全局函数。</li>
<li>文件名 <code>helloWorld.groovy</code> 就对应函数名 <code>helloWorld()</code></li>
<li><code>def call(...)</code> 是约定写法,表示默认执行逻辑。</li>
</ul>
<hr>
<h3 id="五在-jenkins-中配置共享库">五、在 Jenkins 中配置共享库</h3>
<h4 id="1️⃣-打开-jenkins--系统管理--系统配置">1️⃣ 打开 Jenkins → “系统管理” → “系统配置”</h4>
<h4 id="2️⃣-滚动到-global-pipeline-libraries全局流水线库">2️⃣ 滚动到 “Global Pipeline Libraries(全局流水线库)”</h4>
<p>点击 “Add” 新建一条:</p>
<table>
<thead>
<tr>
<th>字段</th>
<th>值</th>
</tr>
</thead>
<tbody>
<tr>
<td>名称</td>
<td><code>my-shared-lib</code>(后面要引用这个名字)</td>
</tr>
<tr>
<td>Default version</td>
<td><code>main</code>(你的 Git 默认分支)</td>
</tr>
<tr>
<td>Source Code Management</td>
<td>Git</td>
</tr>
<tr>
<td>Repository URL</td>
<td><code>https://github.com/yourname/jenkins-shared-lib-demo.git</code></td>
</tr>
</tbody>
</table>
<p>保存。</p>
<hr>
<h3 id="六在-jenkinsfile-中使用">六、在 Jenkinsfile 中使用</h3>
<p>在你的项目 Jenkinsfile 写:</p>
<pre><code class="language-groovy">@Library('my-shared-lib') _
pipeline {
agent any
stages {
    stage('Say Hello') {
      steps {
      helloWorld('软件测试君')
      }
    }
}
}
</code></pre>
<p>运行后,你会在控制台输出看到:</p>
<pre><code> echo
Hello, 软件测试君! Welcome to Shared Library!
</code></pre>
<p>恭喜!你已经完成了第一个共享库调用!</p>
<hr>
<h3 id="七进阶示例模块化封装">七、进阶示例(模块化封装)</h3>
<p>创建一个更实用的函数,比如构建 Maven 项目:</p>
<p>📁 <code>vars/buildApp.groovy</code></p>
<pre><code class="language-groovy">def call(Map config = [:]) {
    stage('Build') {
      sh 'mvn clean install'
    }
    stage('Test') {
      sh 'mvn compile test'
    }
    if (config.deploy == true) {
      stage('Deploy') {
            echo "Deploying to ${config.env ?: 'staging'}..."
      }
    }
}
</code></pre>
<p>然后 Jenkinsfile:</p>
<pre><code class="language-groovy">@Library('my-shared-lib') _
pipeline {
agent any
stages {
    stage('CI Flow') {
      steps {
      buildApp(env: 'prod', deploy: true)
      }
    }
}
}
</code></pre>
<hr>
<h3 id="八实践练习">八、实践练习</h3>
<h4 id="练习-1">练习 1:</h4>
<p>编写一个 <code>notifySlack.groovy</code>,当构建失败时自动通知 Slack。</p>
<p>提示:</p>
<pre><code class="language-groovy">def call(String message) {
    echo "Send Slack notification: ${message}"
}
</code></pre>
<h4 id="练习-2">练习 2:</h4>
<p>在 <code>src/org/example/Utils.groovy</code> 编写工具类:</p>
<pre><code class="language-groovy">package org.example

class Utils {
    static String getTimestamp() {
      return new Date().format("yyyy-MM-dd HH:mm:ss")
    }
}
</code></pre>
<p>然后在 Jenkinsfile 调用:</p>
<pre><code class="language-groovy">@Library('my-shared-lib') _
import org.example.Utils

pipeline {
agent any
stages {
    stage('Show Time') {
      steps {
      echo "Current time: ${Utils.getTimestamp()}"
      }
    }
}
}
</code></pre>
<p>运行后,你会在控制台输出看到:</p>
<p><img src="https://img2024.cnblogs.com/blog/718867/202510/718867-20251013204213161-921157602.png" alt="image" loading="lazy"></p>
<hr>
<h3 id="九共享库版本管理">九、共享库版本管理</h3>
<p>在企业项目中,你通常会:</p>
<ul>
<li>使用 <strong>Git tag</strong> 来发布共享库版本(例如 <code>v1.0.0</code>)</li>
<li>在 Jenkinsfile 中固定使用特定版本:</li>
</ul>
<pre><code class="language-groovy">@Library('my-shared-lib@v1.0.0') _
</code></pre>
<p>这样能防止库更新影响旧项目。</p>
<hr>
<p>恭喜你 ,到此<code>Jenkins Share Library</code>开发就算入门了。</p>
<h3 id="写在最后">写在最后</h3>
<p>改一改自己懒惰的毛病,学起来,顺便也锻炼下自己的写作能力,没有什么华丽的辞藻了,只剩下热诚地坚持了!</p>
<p>最后,感谢您的观看,如文章对您有帮助,老规矩,点赞转发就哦了,如有疑问,欢迎文末留言交流!</p>


</div>
<div id="MySignature" role="contentinfo">
    <p><span style="font-family: 微软雅黑; font-size: 22px; font-weight: normal; font-style: italic; text-decoration: none"><strong>优秀不够,你是否无可替代</strong></span></p>
<p><span style="font-family: 微软雅黑; font-size: 18px; font-weight: normal; font-style: italic; text-decoration: none"><strong>
软件测试交流QQ群:721256703,期待你的加入!!</strong></span></p>
<p><span style="font-family: 微软雅黑; font-size: 18px; font-weight: normal; font-style: italic; text-decoration: none"><strong>欢迎关注我的微信公众号:软件测试君 </strong></span></p>
<img src="https://www.cnblogs.com/images/cnblogs_com/longronglang/1061549/o_QQ%E6%88%AA%E5%9B%BE20190728134401.jpg" height="200" width="450"><br><br><br>
来源:https://www.cnblogs.com/longronglang/p/19139381
頁: [1]
查看完整版本: Jenkins Share Library教程 —— 开发入门