1. 程式人生 > 其它 >Jenkins Shared Library 新增第三方包支援

Jenkins Shared Library 新增第三方包支援

背景

我們在寫 Jenkins 的 Shared Library 時,有時候需要引用外部的一些 jar 包,比如 maven central 的一些 lib 等。
具體到我們的例子,需要引用 Gson 做 json 序列化。

問題

我們的 Shared Library 中有如下程式碼,用到了 Gson:

import com.google.gson.Gson

/**
 * @author wxweven
 */
class JsonUtils {
    static final Gson GSON = new Gson()

    static String toJson(User user) {
        return GSON.toJson(user)
    }
}

但是在執行的時候,Jenkins 報錯:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: JsonUtils.groovy: 3: unable to resolve class com.google.gson.Gson @ line 3, column 1. import com.google.gson.Gson

原因就是 Jenkins 無法找到 Gson 依賴。因為 Jenkins 系統預設是沒有 Gson jar 包的。

新增 Grab 支援

那麼怎麼給 Jenkins 的 Shared Library 新增第三方包支援呢?
Jenkins 官方文件中有說明:

Using third-party libraries

新增 @Grab 註解即可,示例如下:

@Grab('org.apache.commons:commons-math3:3.4.1')
import org.apache.commons.math3.primes.Primes
void parallelize(int count) {
  if (!Primes.isPrime(count)) {
    error "${count} was not prime"
  }
  // …
}

結合我們的程式碼,新增 @Grab 註解後的版本如下:

@Grab('com.google.code.gson:gson:2.8.6')
import com.google.gson.Gson

/**
 * @author wxweven
 */
class JsonUtils {
    public static final Gson GSON = new Gson()

    static String toJson(User user) {
        return GSON.toJson(user)
    }
}

這樣就可以給 Jenkins 中新增 Gson 的 jar 包支援了。

Grab 的語法,跟 maven 的 pom 比較類似,預設的格式是:groupId:artifactId:version

關於 Grab 的更多用法,請參考:官方文件

預設下載的 jar 包,會快取在 Master 節點的 ~/.groovy/grapes/ 目錄下。

結束語

我是梅小西,最近在某東南亞電商公司做 DevOps 的相關事情。從本期開始,將陸續分享基於 Jenkins 的 CI/CD 工作流,包括 Jenkins On k8s 等。

如果你對 Java 或者 Jenkins 等感興趣,歡迎與我聯絡,微信:wxweven(備註 DevOps)


我是梅小西,最近在某東南亞電商公司做 DevOps 的相關事情。從本期開始,將陸續分享基於 Jenkins 的 CI/CD 工作流,包括 Jenkins On k8s 等。
如果你對 Java 或者 Jenkins 等感興趣,歡迎與我聯絡,微信:wxweven(備註 DevOps)

本文由部落格群發一文多發等運營工具平臺 OpenWrite 釋出