CentOS上Jenkins配置多分支管道步骤
yum或官方仓库安装Jenkins(参考Jenkins官方文档),并启动服务(systemctl start jenkins、systemctl enable jenkins)。http://<服务器IP>:8080)→ Manage Jenkins → Manage Plugins,安装以下插件:
my-multibranch-pipeline),选择Multibranch Pipeline,点击OK。在项目配置页面,找到Branch Sources部分,添加代码源(以Git为例):
https://gitee.com/username/repo.git或git@github.com:username/repo.git);^(feature|develop|release)/)、“Exclude branches that match regex”),默认发现所有包含Jenkinsfile的分支。为实现自动化构建,可配置Scan Multibranch Pipeline Triggers:
@daily每天扫描一次,或H/5 * * * *每5分钟扫描一次);/github-webhook/(GitHub)或/gitlab-webhook/(GitLab)路径,当有推送(push)或拉取请求(PR)时自动触发扫描。在代码仓库的根目录下创建Jenkinsfile(文件名需与项目配置中的Script Path一致,默认为Jenkinsfile),定义流水线逻辑。示例如下:
pipeline {
agent any // 使用任意可用节点
environment {
// 定义环境变量
ARTIFACT_DIR = "target"
VERSION = "1.0.${env.BUILD_NUMBER}"
}
stages {
stage('Checkout') {
steps {
echo "Checking out code from branch: ${env.BRANCH_NAME}"
checkout scm // 检出当前分支代码
}
}
stage('Build') {
steps {
echo "Building application..."
sh 'mvn clean package -DskipTests' // 示例:Maven构建
}
}
stage('Test') {
when {
// 仅在非feature分支运行测试
expression { !env.BRANCH_NAME.startsWith('feature/') }
}
steps {
echo "Running unit tests..."
sh 'mvn test' // 运行单元测试
}
}
stage('Deploy') {
when {
// 仅在develop或release分支部署
anyOf {
expression { env.BRANCH_NAME == 'develop' }
expression { env.BRANCH_NAME == 'release' }
}
}
steps {
echo "Deploying to staging environment..."
sh 'scp ${ARTIFACT_DIR}/*.jar user@staging-server:/opt/app/' // 示例:部署到测试环境
}
}
}
post {
success {
echo "Pipeline succeeded for branch: ${env.BRANCH_NAME}"
}
failure {
echo "Pipeline failed for branch: ${env.BRANCH_NAME}"
// 可添加邮件通知等操作
}
}
}
说明:
agent any:使用任意Jenkins节点执行流水线;environment:定义全局环境变量;stages:定义流水线的各个阶段(如Checkout、Build、Test、Deploy);when:通过条件控制阶段执行(如仅在特定分支运行测试或部署);post:定义流水线结束后的操作(如成功/失败通知)。feature/new-login),提交包含Jenkinsfile的代码;my-multibranch-pipeline/feature-new-login);Jenkinsfile位于仓库根目录,且文件名与配置一致;http://<Jenkins服务器IP>:8080/github-webhook/),以及Jenkins是否有网络访问权限。