Jenkins持续集成实战
Jenkins持续集成实战
Jenkins是最流行的开源CI/CD工具,通过Pipeline即代码实现可复用的自动化流水线。
Jenkins Pipeline基础
// Jenkinsfile
pipeline {
agent any
environment {
JAVA_HOME = tool 'JDK17'
APP_VERSION = readMavenPom().getVersion()
}
stages {
stage('Checkout') {
steps {
checkout scm
}
}
stage('Build') {
steps {
sh 'mvn clean compile -B'
}
}
stage('Test') {
parallel {
stage('Unit Tests') {
steps {
sh 'mvn test -B -Dtest=UnitTests'
}
}
stage('Integration Tests') {
steps {
sh 'mvn verify -B -DskipUnitTests -Dtest=IntegrationTests'
}
}
}
}
stage('Quality Gate') {
steps {
sh 'mvn sonar:sonar'
sh 'mvn org.sonarsource.scanner.maven:sonar-maven-plugin:check'
}
}
stage('Package') {
steps {
sh 'mvn package -DskipTests -B'
archiveArtifacts artifacts: 'target/*.jar'
}
}
stage('Docker Build') {
steps {
script {
docker.build("registry.example.com/app:${APP_VERSION}")
}
}
}
stage('Deploy Staging') {
steps {
sh "kubectl set image deployment/app app=registry.example.com/app:${APP_VERSION}"
}
}
}
post {
success {
mail to: 'team@example.com',
subject: "构建成功: ${currentBuild.fullDisplayName}",
body: "查看详情: ${env.BUILD_URL}"
}
failure {
mail to: 'team@example.com',
subject: "构建失败: ${currentBuild.fullDisplayName}",
body: "查看详情: ${env.BUILD_URL}"
}
}
}
凭据管理
// 使用Jenkins凭据
withCredentials([
usernamePassword(credentialsId: 'docker-registry',
usernameVariable: 'USER',
passwordVariable: 'PASS'),
string(credentialsId: 'sonar-token',
variable: 'SONAR_TOKEN')
]) {
sh "docker login -u ${USER} -p ${PASS} registry.example.com"
sh "mvn sonar:sonar -Dsonar.login=${SONAR_TOKEN}"
}
多分支流水线
// Jenkinsfile 多分支配置
pipeline {
agent {
label {
label 'java-agent'
}
}
when {
branch 'main'
}
stages {
stage('Production Deploy') {
when {
beforeInput true
}
input {
message '确认部署到生产环境?'
ok '确认部署'
}
steps {
sh 'kubectl set image deployment/app app=app:latest'
}
}
}
}
代码质量集成
stage('Quality') {
steps {
script {
// SonarQube质量门禁
timeout(10) {
waitForQualityGate abortPipeline: true
}
}
}
}
构建通知
post {
always {
junit testResults: '**/target/surefire-reports/*.xml'
jacoco(
execPattern: '**/target/jacoco.exec',
classPattern: '**/target/classes'
)
}
changed {
slackSend channel: '#dev-alerts',
message: "构建状态变更: ${currentBuild.fullDisplayName}"
}
}
小结
Jenkins Pipeline即代码的方式提供了灵活、可复用的CI/CD流水线,是DevOps实践的核心工具。