PM 大大通知我們,『很好,我們已經可以監控 www.example.com 的 Response code,但是這裡還有另外三個 URL 也需要進行監控。』
Target URL List
domain name | expected response code |
---|---|
www.example.com | 200 |
www.google.com | 200 |
test.k6.io | 308 |
k6.io | 301 |
...... 很好,要改 code 了 ...... QQ
如果時程很趕的話我們,簡單的替換底下紅色框框的部分到其他幾個新的 pipleine 即可,但是會造成大量 code 的重複,使得後期維護更新時造成很多麻煩 e.g. 某幾個 jenkinsfile 忘記更新之類的低級錯誤,會 debug 到懷疑人生。所以如果時間允許的話,還是不建議做這種便宜行事的方式。
呈上,我覺得比較好的作法是將重複的部分抽出成一個新的 function, 然後再讓各個 Jenkinsfile 去引用 library。
As Pipeline is adopted for more and more projects in an organization, common patterns are likely to emerge. Oftentimes it is useful to share parts of Pipelines between various projects to reduce redundancies and keep code "DRY"
(https://www.jenkins.io/doc/book/pipeline/shared-libraries/)
當多個 pipeline 都有使用到同質性非常高的部分時,Jenkins 官方鼓勵我們將其從 Pipeline 抽出成 function,進行統一管理。
https://www.jenkins.io/doc/book/pipeline/shared-libraries/
這次我們專注要使用的是 vars,
// vars/testIthome.groovy
def call(String executor){
script {
if ( executor == "Ithome" ){
echo "Hi Ben"
} else if (executor == "Jenkins" ){
echo "Hi Jenkins"
} else {
echo "unrecognizable"
}
}
}
需要將 function name 命名為
call
進入到 Manager Jenkins 選擇 Configure System,在 Global Pipeline Libraries 新增我們想被引用的專案。
Name (實際在 Jenkinsfile 會被引用的名稱): ithome-utils
Default version (git branch name): day7
Project Repository (專案位置): https://github.com/GSA/jenkins-shared-library-examples.git
開啟一個新的 Pipeline 專案來測試看看是否已經生效
library 'ithome-utils'
pipeline {
agent any
stages{
stage('test library'){
steps{
sample('Ithome')
sample('Jenkins')
sample('Ben')
}
}
}
}
測試成功!
回到 Pipeline - check-website-code
我們用同樣的方式進行 function 的抽離。
// var/webSiteCodePipeline.groovy
def call(Map pipelineParams) {
pipeline {
agent any
stages {
stage ("Request website") {
steps{
script{
response_code = sh (
script: "curl -o /dev/null -s -w %{http_code} ${pipelineParams.domain}",
returnStdout: true
).toInteger()
echo "${response_code}"
}
}
}
stage ("Check response code") {
steps{
script{
if ( response_code != pipelineParams.code ){
sh "false"
}
}
}
}
}
post {
success{
echo "success"
}
failure{
script {
withCredentials([string(credentialsId: 'ithome-telegram-bot-token', variable: 'TOKEN')]){
withCredentials([string(credentialsId: 'ithome-telegram-notification-group', variable: 'GROUP_ID')]){
sh """#!/bin/bash
curl -X GET https://api.telegram.org/bot${TOKEN}/sendMessage -d "chat_id=${GROUP_ID}&text=\"\"${pipelineParams.domain} response code != ${pipelineParams.code}.\"\""
"""
}
}
}
}
}
}
}
這樣我們將可以大幅修改本來的 Jenkinsfile 為
// www.example.com
library 'ithome-utils'
webSiteCodePipeline(domain: 'www.example.com', code: 200)
// www.google.com
library 'ithome-utils'
webSiteCodePipeline(domain: 'www.google.com', code: 200)
// test.k6.io
library 'ithome-utils'
webSiteCodePipeline(domain: 'test.k6.io', code: 308)
// k6.io
library 'ithome-utils'
webSiteCodePipeline(domain: 'k6.io', code: 301)
今天的例子稍微極端了一點,實際狀況需要視情況做。
之後會找時間更完整介紹 Shared Library 的使用場景。
shared-libraries
jenkins-shared-library-examples