流水线即代码 #
Pipeline as Code是将CI/CD流程定义为代码的实践,使流水线可以版本化管理、审查和复用。
核心原则 #
1. 版本控制 #
text
Jenkinsfile存放在代码仓库中
与代码同步管理
支持代码审查
2. 可读性 #
text
使用清晰的命名
添加必要的注释
保持结构简洁
3. 可维护性 #
text
模块化设计
使用共享库
避免重复代码
Jenkinsfile最佳实践 #
基本结构 #
groovy
pipeline {
agent any
environment {
APP_NAME = 'myapp'
}
options {
timeout(time: 30, unit: 'MINUTES')
buildDiscarder(logRotator(numToKeepStr: '10'))
}
stages {
stage('Build') {
steps {
sh 'mvn clean package'
}
}
stage('Test') {
steps {
sh 'mvn test'
}
}
stage('Deploy') {
when {
branch 'main'
}
steps {
sh 'deploy.sh'
}
}
}
post {
always {
cleanWs()
}
}
}
使用参数 #
groovy
pipeline {
agent any
parameters {
choice(name: 'ENVIRONMENT', choices: ['dev', 'test', 'prod'])
booleanParam(name: 'SKIP_TESTS', defaultValue: false)
string(name: 'VERSION', defaultValue: '')
}
stages {
stage('Build') {
steps {
echo "Building for ${params.ENVIRONMENT}"
}
}
}
}
环境隔离 #
groovy
pipeline {
agent any
environment {
NAMESPACE = getNamespace()
}
stages {
stage('Deploy') {
steps {
sh "kubectl apply -f k8s/${env.NAMESPACE}/"
}
}
}
}
def getNamespace() {
switch(env.BRANCH_NAME) {
case 'main': return 'production'
case 'develop': return 'development'
default: return "feature-${env.BRANCH_NAME.replaceAll('/', '-')}"
}
}
设计模式 #
模板模式 #
groovy
// 共享库中定义模板
def call(Map config) {
pipeline {
agent any
stages {
stage('Build') {
steps {
sh "${config.buildCommand}"
}
}
stage('Test') {
steps {
sh "${config.testCommand}"
}
}
stage('Deploy') {
when {
expression { config.deploy }
}
steps {
sh "${config.deployCommand}"
}
}
}
}
}
// 项目中使用
@Library('shared-lib') _
standardPipeline(
buildCommand: 'mvn clean package',
testCommand: 'mvn test',
deploy: true,
deployCommand: 'kubectl apply -f k8s/'
)
策略模式 #
groovy
def getDeployer(String type) {
switch(type) {
case 'kubernetes':
return new KubernetesDeployer(this)
case 'docker':
return new DockerDeployer(this)
case 'ssh':
return new SSHDeployer(this)
default:
error "Unknown deployer type: ${type}"
}
}
pipeline {
agent any
stages {
stage('Deploy') {
steps {
script {
def deployer = getDeployer(params.DEPLOY_TYPE)
deployer.deploy()
}
}
}
}
}
工厂模式 #
groovy
class PipelineFactory {
static def create(String type, steps) {
switch(type) {
case 'java':
return new JavaPipeline(steps)
case 'nodejs':
return new NodeJSPipeline(steps)
case 'python':
return new PythonPipeline(steps)
default:
throw new Exception("Unknown pipeline type: ${type}")
}
}
}
pipeline {
agent any
stages {
stage('Build') {
steps {
script {
def pipeline = PipelineFactory.create('java', this)
pipeline.build()
}
}
}
}
}
错误处理 #
统一错误处理 #
groovy
pipeline {
agent any
stages {
stage('Build') {
steps {
script {
try {
sh 'mvn clean package'
} catch (Exception e) {
echo "Build failed: ${e.message}"
currentBuild.result = 'FAILURE'
throw e
}
}
}
}
}
post {
failure {
script {
notifyFailure()
}
}
}
}
重试机制 #
groovy
stage('Deploy') {
steps {
retry(3) {
sh 'deploy.sh'
}
}
}
超时控制 #
groovy
stage('Test') {
steps {
timeout(time: 30, unit: 'MINUTES') {
sh 'mvn test'
}
}
}
条件执行 #
基于分支 #
groovy
stage('Deploy to Production') {
when {
branch 'main'
}
steps {
sh 'deploy-prod.sh'
}
}
基于环境变量 #
groovy
stage('Deploy') {
when {
expression { params.ENVIRONMENT == 'prod' }
}
steps {
sh 'deploy-prod.sh'
}
}
基于输入 #
groovy
stage('Deploy to Production') {
when {
expression { params.ENVIRONMENT == 'prod' }
}
input {
message "Deploy to production?"
ok "Deploy"
}
steps {
sh 'deploy-prod.sh'
}
}
代码质量 #
代码检查 #
groovy
stage('Code Quality') {
steps {
withSonarQubeEnv('SonarQube') {
sh 'mvn sonar:sonar'
}
}
}
stage('Quality Gate') {
steps {
timeout(time: 5, unit: 'MINUTES') {
waitForQualityGate abortPipeline: true
}
}
}
测试覆盖率 #
groovy
stage('Test Coverage') {
steps {
sh 'mvn jacoco:report'
jacoco(
execPattern: '**/target/jacoco.exec',
classPattern: '**/target/classes',
sourcePattern: '**/src/main/java',
exclusionPattern: '**/test/**'
)
}
}
安全最佳实践 #
凭据管理 #
groovy
environment {
DB_PASSWORD = credentials('db-password')
}
stage('Deploy') {
steps {
withCredentials([usernamePassword(
credentialsId: 'deploy-credentials',
usernameVariable: 'DEPLOY_USER',
passwordVariable: 'DEPLOY_PASS'
)]) {
sh 'deploy.sh'
}
}
}
输入验证 #
groovy
stage('Validate') {
steps {
script {
if (!params.VERSION.matches('\\d+\\.\\d+\\.\\d+')) {
error("Invalid version format")
}
}
}
}
文档化 #
添加注释 #
groovy
pipeline {
agent any
stages {
// 构建阶段:编译和打包应用
stage('Build') {
steps {
sh 'mvn clean package'
}
}
// 测试阶段:运行单元测试和集成测试
stage('Test') {
steps {
sh 'mvn test'
}
}
}
}
README文档 #
markdown
# CI/CD Pipeline
## 参数说明
- ENVIRONMENT: 部署环境
- SKIP_TESTS: 是否跳过测试
- VERSION: 应用版本
## 使用方法
1. 选择参数
2. 点击构建
3. 查看构建结果
## 流程说明
1. Build: 编译打包
2. Test: 运行测试
3. Deploy: 部署应用
下一步学习 #
小结 #
- Pipeline as Code实现版本化管理
- 遵循设计模式提高可维护性
- 统一错误处理机制
- 使用条件控制流程
- 注意安全性配置
- 添加必要的文档
最后更新:2026-03-28