TOKEN="test-token"
GROUP_ID="-000000000"
CODE=$(curl -o /dev/null -s -w %{http_code} www.example.com)
if [ "${CODE}" != "200" ]; then
message="www.example.com response code != 200."
curl -X GET "https://api.telegram.org/bot${TOKEN}/sendMessage" \
-d "chat_id=${GROUP_ID}&text=${message}"
首先我們將
TOKEN
與
GROUP_ID
用 Jenkins 來託管吧。
我們是使用
Credentials plugin
,預設在 Jenkins 初始推薦安裝時會安裝。
先進到 Manage Jenkins >> Manage Credentials
點選在 Stores scoped to Jenkins 選單中的 Jenkins
點選 System 選單中的 Global credentials (unrestricted)
點選在左邊選單中的 Add Credentials 後即可新增新的 Credentials。
常見的 Credentials 種類:
Username and password: 可以儲存常見的 user/ password 形式的 credentials,常見的有 db 的 user/password 、 git server 的 user/token 或是 aws 的 Access key ID/Secret access key (亦可使用 AWS 專門的
credentials plugin
)
Secret text: 儲存單一的 token 之類的訊息。
此時我們要使用的類型是 Secret text
Secret -> 存放 telegram bot token
ID -> 在 Pipeline 引用 Secret text 時的識別名稱(推薦取一些比較白話的名字)
Description -> 在 Credentials 頁面的額外識別訊息。
完成圖如下:
回到我們的 Jenkinsfile,新增
withCredentials
pipeline {
agent any
stages {
stage ("Check www.example.com response code") {
steps{
withCredentials([string(credentialsId: 'ithome-telegram-bot-token', variable: 'TOKEN')]){
withCredentials([string(credentialsId: 'ithome-telegram-notification-group', variable: 'GROUP_ID')]){
sh '''
command=$(curl -o /dev/null -s -w %{http_code} www.example.com)
if [ "${command}" != "200" ]; then
message="www.example.com response code != 200."
curl -X GET "https://api.telegram.org/bot${TOKEN}/sendMessage" \
-d "chat_id=${GROUP_ID}&text=${message}"
Cronjob
有兩種方式可以新增定時排程,第一是從 UI 介面上 Pipeline configure 中可進行設定,第二是在 Jenkinsfile 中進行宣告。但是這邊只會介紹在 UI 如何設定。
在 Configure 頁面中的 Build Triggers 下,點選 Build periodically
在裡面輸入 0 20 * * * -> 表示每天的晚上八點執行。
需要特別注意這邊的晚上八點指的是 UTC,並不會跟隨著系統時間進行替換,如果需要指定時區的話需要額外宣告在第一行。
TZ=Asia/Taipei
0 20 * * *
(非常推薦將 Credentials 用 Jenkins 的 solution,第一,當你有多個 pipeline 需要用同一個 token 時,在更新時可以統一更新不用怕漏更新; 第二,在執行時就算有人故意去 echo 他,在 output 的介面,也會用 ****** 取代實際的密碼。)
今天我們以 Jenkins 儲存我們的敏感資訊以及設定定時排程,明天讓我們一起來重構現在的 Jenkinsfile 吧~
Github 專案連結
ithome-jenkins
The Importance of SOLID Design Principles
How to Run a Shell Script in Jenkins Pipeline
How to Securely Manage Secrets Within Jenkins
Meaning of H/5 in cron Jenkins