名称: jenkins-pipeline 描述: 使用声明式和脚本式流水线构建Jenkins,包含阶段、代理、参数和插件。实现多分支流水线和部署自动化。
Jenkins流水线
概述
使用声明式和脚本式方法创建企业级Jenkins流水线,通过高级控制流自动化构建、测试和部署。
使用场景
- 企业CI/CD基础设施
- 复杂的多阶段构建
- 本地部署自动化
- 参数化构建
实现示例
1. 声明式流水线 (Jenkinsfile)
pipeline {
agent { label 'linux-docker' }
environment {
REGISTRY = 'docker.io'
IMAGE_NAME = 'myapp'
}
parameters {
string(name: 'DEPLOY_ENV', defaultValue: 'staging')
}
stages {
stage('代码检出') { steps { checkout scm } }
stage('安装依赖') { steps { sh 'npm ci' } }
stage('代码检查') { steps { sh 'npm run lint' } }
stage('测试') {
steps {
sh 'npm run test:coverage'
junit 'test-results.xml'
}
}
stage('构建') {
steps {
sh 'npm run build'
archiveArtifacts artifacts: 'dist/**/*'
}
}
stage('部署') {
when { branch 'main' }
steps {
sh 'kubectl set image deployment/app app=${REGISTRY}/${IMAGE_NAME}:latest'
}
}
}
post {
always { cleanWs() }
failure { echo '流水线执行失败!' }
}
}
2. 脚本式流水线 (Groovy)
// Jenkinsfile - 脚本式流水线
node('linux-docker') {
def imageTag = sh(returnStdout: true, script: 'git rev-parse --short HEAD').trim()
def registry = 'docker.io'
try {
stage('代码检出') { checkout scm }
stage('安装依赖') { sh 'npm ci' }
stage('测试') { sh 'npm test' }
stage('构建') { sh 'npm run build' }
currentBuild.result = 'SUCCESS'
} catch (Exception e) {
currentBuild.result = 'FAILURE'
error("构建失败: ${e.message}")
}
}
3. 多分支流水线
pipeline {
agent any
stages {
stage('构建') { steps { sh 'npm run build' } }
stage('测试') { steps { sh 'npm test' } }
stage('部署') {
when { branch 'main' }
steps { sh 'npm run deploy:prod' }
}
}
}
4. 参数化流水线
pipeline {
agent any
parameters {
string(name: 'VERSION', defaultValue: '1.0.0', description: '发布版本号')
choice(name: 'ENV', choices: ['staging', 'prod'], description: '部署环境')
}
stages {
stage('构建') { steps { sh 'npm run build' } }
stage('测试') { steps { sh 'npm test' } }
stage('部署') {
steps { sh "npm run deploy:${params.ENV}" }
}
}
}
5. 带凭证的流水线
pipeline {
agent any
environment {
DOCKER_CREDS = credentials('docker-hub')
}
stages {
stage('构建与推送') {
steps {
sh '''
echo $DOCKER_CREDS_PSW | docker login -u $DOCKER_CREDS_USR --password-stdin
docker build -t myapp:latest .
docker push myapp:latest
'''
}
}
}
}
最佳实践
✅ 建议
- 使用声明式流水线以提高可读性
- 使用凭证插件管理密钥
- 归档构建产物和报告
- 为生产环境部署设置审批门禁
- 保持流水线模块化和可复用
❌ 避免
- 在流水线代码中存储凭证
- 忽略流水线错误
- 跳过测试覆盖率报告
- 使用已弃用的插件