在Ubuntu上使用Jenkins实现多分支构建的完整步骤
安装Jenkins
若未安装Jenkins,可通过以下命令完成基础安装:
sudo apt update
sudo apt install openjdk-11-jdk # Jenkins依赖Java 11+
wget -q -O - https://pkg.jenkins.io/debian/jenkins.io.key | sudo apt-key add -
sudo sh -c 'echo deb http://pkg.jenkins.io/debian-stable binary/ > /etc/apt/sources.list.d/jenkins.list'
sudo apt update
sudo apt install jenkins
sudo systemctl start jenkins
sudo systemctl enable jenkins
安装必要插件
登录Jenkins管理界面(http://<服务器IP>:8080),进入「Manage Jenkins → Manage Plugins」,安装以下插件:
新建任务
在Jenkins首页点击「New Item」,输入项目名称(如my-multibranch-pipeline),选择「Multibranch Pipeline」类型,点击「OK」。
配置源码管理
在「Source Code Management」部分,选择「Git」,填写以下信息:
https://github.com/your-username/your-repo.git);设置分支发现策略
在「Branch Sources」→「Branch Discovery」部分,选择分支过滤规则:
*/main、*/develop,支持通配符);feature/*,避免频繁构建特性分支)。配置构建触发器(可选但推荐)
在「Build Triggers」部分,选择自动触发方式:
保存配置
点击「Save」,Jenkins会自动开始扫描仓库分支。首次扫描可能需要几分钟,完成后会在「Branches」 tab 下显示所有匹配的分支及对应的构建状态。
每个分支需包含一个Jenkinsfile(建议放在仓库根目录),定义该分支的构建流程。以下是常用示例:
pipeline {
agent any // 使用任意可用节点
environment {
PROJECT_NAME = 'my-app'
VERSION = '1.0.${BUILD_NUMBER}'
}
stages {
stage('Checkout') {
steps {
git branch: env.BRANCH_NAME, url: 'https://github.com/your-username/your-repo.git' // 动态获取当前分支
}
}
stage('Build') {
steps {
echo "Building ${PROJECT_NAME} for branch ${env.BRANCH_NAME}..."
sh './gradlew build' // 示例:使用Gradle构建(根据项目调整)
}
}
stage('Test') {
steps {
echo "Running tests for branch ${env.BRANCH_NAME}..."
sh './gradlew test'
}
}
stage('Deploy') {
when {
expression { env.BRANCH_NAME == 'main' } // 仅main分支部署到生产环境
}
steps {
echo "Deploying ${PROJECT_NAME} to production..."
sh './deploy.sh production' // 示例:调用部署脚本
}
}
}
post {
success {
echo "Build succeeded for branch ${env.BRANCH_NAME}!"
}
failure {
echo "Build failed for branch ${env.BRANCH_NAME}!"
}
}
}
node {
stage('Checkout') {
git branch: env.BRANCH_NAME, url: 'https://github.com/your-username/your-repo.git'
}
stage('Build') {
echo "Building for branch ${env.BRANCH_NAME}..."
sh './mvnw clean package' // 示例:使用Maven构建
}
stage('Test') {
echo "Running tests..."
sh './mvnw test'
}
stage('Deploy') {
if (env.BRANCH_NAME == 'develop') {
echo "Deploying to staging environment..."
sh './deploy.sh staging'
} else if (env.BRANCH_NAME == 'main') {
echo "Deploying to production environment..."
sh './deploy.sh production'
}
}
}
关键说明:
env.BRANCH_NAME:Jenkins内置变量,表示当前分支名称,可用于动态调整构建逻辑;when指令:根据条件(如分支名称、文件存在性)决定是否执行某阶段;- 脚本路径:若
Jenkinsfile不在根目录,需在Multibranch配置中修改「Script Path」(如ci/Jenkinsfile)。
自动触发
Push Events),当分支有新提交时,Jenkins会自动扫描并触发对应分支的构建;手动触发
在Jenkins项目页面,点击「Scan Repository Now」可手动触发分支扫描;点击「Build Now」可手动触发指定分支的构建。
查看结果
使用Webhook替代定期扫描
定期扫描会消耗Jenkins资源,建议为GitHub/GitLab配置Webhook:
http://<Jenkins服务器IP>:8080/github-webhook/),选择「Just the push event」;环境隔离
develop分支用docker-agent,main分支用linux-agent),避免环境冲突;environment块或withEnv设置分支专属环境变量(如DEPLOY_ENV=staging)。Jenkinsfile复用
load指令加载公共脚本(如load 'scripts/common.groovy')。权限控制
通过以上步骤,即可在Ubuntu上使用Jenkins实现多分支自动化构建,覆盖从代码提交到测试、部署的全流程,提升团队协作效率。