Ubuntu中自定义Jenkins构建脚本实操指南
一 准备环境
sudo apt update && sudo apt install -y openjdk-11-jdkwget -q -O - https://pkg.jenkins.io/debian/jenkins.io.key | sudo apt-key add -
sudo sh -c 'echo deb http://pkg.jenkins.io/debian-stable binary/ > /etc/apt/sources.list.d/jenkins.list'
sudo apt update && sudo apt install -y jenkins
sudo systemctl start jenkins && sudo systemctl enable jenkins
二 方式一 Pipeline 项目自定义脚本
pipeline {
agent any
environment {
APP_NAME = 'myapp'
WORKSPACE_DIR = "/var/lib/jenkins/workspace/${env.JOB_NAME}"
}
stages {
stage('Checkout') {
steps {
git branch: 'main', url: 'git@github.com:your-org/your-repo.git'
}
}
stage('Build') {
steps {
sh '''
chmod +x ./build.sh
./build.sh
'''
}
}
stage('Test') {
steps {
sh './test.sh'
}
post {
always {
junit '**/target/surefire-reports/*.xml'
publishHTML(target: [
reportDir: 'target/site/jacoco',
reportFiles: 'index.html',
reportName: 'Coverage Report'
])
}
}
}
stage('Deploy') {
steps {
sh './deploy.sh'
}
}
}
post {
success {
echo 'Build and deploy succeeded.'
}
failure {
echo 'Build or deploy failed.'
}
}
}
三 方式二 Freestyle 项目自定义脚本
#!/usr/bin/env bash
set -euo pipefail
echo "=== Build ==="
chmod +x ./build.sh
./build.sh
echo "=== Test ==="
./test.sh
echo "=== Deploy ==="
./deploy.sh
四 常见场景脚本模板
#!/usr/bin/env bash
set -euo pipefail
HOSTS=(10.0.0.13 10.0.0.14)
APP=myweb
APP_PATH=/var/www/html
download() {
rm -rf "$APP"
git clone git@your-gitlab.com:dev/"$APP".git
}
deploy() {
for h in "${HOSTS[@]}"; do
rsync -avz --delete "$APP"/ "$h:$APP_PATH"/
done
}
download
deploy
chmod +x deploy.sh && ./deploy.sh。#!/usr/bin/env bash
set -euo pipefail
BUILD_ID=DONTKILLME # 防止 Jenkins 杀掉子进程
cd "$WORKSPACE"
./mvnw clean package -DskipTests
PID=$(ps -aux | grep demo1 | grep -v grep | awk '{print $2}')
if [ -n "$PID" ]; then
kill -9 "$PID" || true
fi
nohup java -jar target/demo1-0.0.1-SNAPSHOT.jar \
-Xmx512m -Xms512m -Xss4m > app.log 2>&1 &
NEW_PID=$(ps -aux | grep demo1 | grep -v grep | awk '{print $2}')
if [ -z "$NEW_PID" ]; then
echo "启动失败"
exit 1
else
echo "启动成功,PID=$NEW_PID"
fi
BUILD_ID=DONTKILLME 常用于避免 Jenkins 在构建结束后终止由脚本启动的后台进程。五 权限与安全建议
chmod +x your_script.sh;在 Jenkinsfile/Freestyle 中先执行权限设置再运行脚本更稳妥。