第四章 4-6~4-7 Jenkins Job的編碼規範和構建配置
一、Freestyle Job的編碼規範和構建配置
1.1、創建一個freestyle任務
1.2、編輯描述信息
1.3、添加參數配置
1.4、源代碼管理
登錄之前的gitlab
進入到test-repo,拷貝git的地址
將倉庫地址複製到源碼管理配置中,但是出現了下面的錯誤。
我們需要去系統管理下面的全局工具配置中配置下面的。
但是在配置上後,會出現下面的報錯,這是由於Git的版本不是最新的導致的。
參照下面的鏈接,安裝配置最新的Git。
Linux下安裝最新版的Git
安裝配置後,可以看到已經沒有報錯了。
1.5、Build配置
#!/bin/sh:指定命令的類型爲shell命令
export:引入環境變量
#!/bin/sh
export PATH="/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin"
# Print env variable
echo "[INFO] Print env variable"
echo "Current deployment envrionment is $deploy_env" >> test.properties
echo "The build is $version" >> test.properties
echo "[INFO] Done..."
# Check test properties
echo "[INFO] Check test properties"
if [ -s test.properties]
then
cat test.properties
echo "[INFO] Done..."
else
echo "test.properties is empty"
fi
echo "[INFO] Build finished..."
1.6、Job構建工作
點擊下圖左側紅色框中的按鈕,進入到構建參數配置頁面,在設置了確定的配置參數的情況下,點擊“開始構建”按鈕開始構建。
點擊後可以看到下面展示的信息,說明構建成功。
點擊左邊的藍色圓球,進入到控制檯輸出界面
進入到之前的配置界面的構建中,修改之前的shell腳本。
保存後,重新按上面的步驟構建,查看控制檯輸出,在test.properties文件中成功輸出了相關參數。
二、Pipeline Job的編碼規範與構建配置
2.1、Pipeline簡介
2.1.1、pipeline基礎架構
2.1.2、agent區域
2.1.3、environment區域
2.1.4、script區域
2.1.5、常用steps區域
2.2、Pipeline Job構建配置
2.2.1、新建一個pipeline job
2.2.2、添加描述信息
2.2.3、編寫pipeline腳本
#!groovy
pipeline {
agent {node {label 'master'}}
environment {
PATH="/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin"
}
parameters {
choice(
choices: 'dev\nprod',
description: 'choose deploy environment',
name: 'deploy_env'
)
string (name: 'version', defaultValue: '1.0.0', description: 'build version')
}
stages {
stage("Checkout test repo") {
steps{
sh 'git config --global http.sslVerify false'
dir ("${env.WORKSPACE}") {
git branch: 'master', credentialsId: "edc4ee8c-db9a-4d09-bed6-5747da58d83b", url: 'http://192.168.2.200:8091/root/test-repo.git'
}
}
}
stage("Print env variable") {
steps {
dir ("${env.WORKSPACE}") {
sh """
echo "[INFO] Print env variable"
echo "Current deployment environment is $deploy_env" >> test.properties
echo "The build is $version" >> test.properties
echo "[INFO] Done..."
"""
}
}
}
stage("Check test properties") {
steps {
dir ("${env.WORKSPACE}") {
sh """
echo "[INFO] Check test properties"
if [ -s test.properties ]
then
cat test.properties
echo "[INFO] Done..."
else
echo "test.properties is empty"
fi
"""
echo "[INFO] Build finished..."
}
}
}
}
}
把上面的腳本複製黏貼到下圖中,點擊保存。
2.2.4、測試構建
點擊構建命令去構建腳本。但是構建失敗。構建失敗的原因是git命令不存在。
針對這個問題,在下圖中,已經修改了git的命令路徑。說明在jenkins的git配置上應該是沒有問題的。
檢查之前編寫的pipeline腳本,發現是下面的變量參數上沒有添加git的路徑,導致下面的shell語句在執行的時候找不到命令路徑。
修改後
重新執行構建命令,構建成功!