在 Debian 上使用 Jenkins 实现多环境部署
一 架构与准备
二 配置管理与参数化
三 流水线示例
pipeline {
agent any
parameters {
choice(name: 'DEPLOY_ENV', choices: ['dev','test','prod'], description: '部署环境')
booleanParam(name: 'DEPLOY_TO_PROD', defaultValue: false, description: '确认部署到生产')
}
environment {
// 在 Jenkins 的“Credentials”中预先创建对应凭据,ID 如下
GIT_CRED = credentials('git-ssh')
TEST_SSH = credentials('test-server-ssh')
PROD_SSH = credentials('prod-server-ssh')
}
stages {
stage('Checkout') {
steps {
git branch: '*/main',
url: 'git@github.com:your-org/your-repo.git',
credentialsId: env.GIT_CRED
}
}
stage('Build') {
steps {
// 示例:Maven 多环境打包;若使用 Gradle,请替换为相应构建命令
sh 'mvn clean package -P${params.DEPLOY_ENV} -DskipTests'
}
}
stage('Deploy to Dev') {
when { expression { params.DEPLOY_ENV == 'dev' } }
steps {
sshPublisher(
publishers: [sshPublisherDesc(
configName: 'test-server',
transfers: [sshTransfer(
sourceFiles: 'target/*.jar',
removePrefix: 'target/',
remoteDirectory: '/opt/apps/myapp'
)]
)]
)
}
}
stage('Deploy to Test') {
when { expression { params.DEPLOY_ENV == 'test' } }
steps {
sshPublisher(
publishers: [sshPublisherDesc(
configName: 'test-server',
transfers: [sshTransfer(
sourceFiles: 'target/*.jar',
removePrefix: 'target/',
remoteDirectory: '/opt/apps/myapp'
)]
)]
)
}
}
stage('Deploy to Prod') {
when { allOf {
expression { params.DEPLOY_ENV == 'prod' }
expression { params.DEPLOY_TO_PROD == true }
} }
steps {
script {
// 可在此加入更严格的审批、灰度、回滚等逻辑
input message: '确认部署到生产环境?', ok: '确认'
}
sshPublisher(
publishers: [sshPublisherDesc(
configName: 'prod-server',
transfers: [sshTransfer(
sourceFiles: 'target/*.jar',
removePrefix: 'target/',
remoteDirectory: '/opt/apps/myapp'
)]
)]
)
}
}
}
post {
success { echo "部署到 ${params.DEPLOY_ENV} 成功" }
failure { echo "部署到 ${params.DEPLOY_ENV} 失败" }
}
}
四 安全与扩展