在我们的项目中,我们在构建时附加分支名称,除非它是master。我们用build_id和& latest"标记它们。这就是我们想要的。
- myapp:latest
- myapp:1
- myapp:2
- myapp:3
- myapp-branch-x:latest
- myapp-branch-x:1
- myapp-branch-x:2
- myapp-branch-x:3
- myapp-branch-y:latest
- myapp-branch-y:1
- myapp-branch-y:2
- myapp-branch-y:3
为了实现这一点,我们在主分支上构建两次。我觉得很奇怪。我们怎样才能避免这种情况呢?
pipeline {
environment {
dockerCredentials = 'myapp-dockerhub'
dockerRegistryUrl = 'https://dockerhub.example.com'
imageName = "dockerhub.example.com/myapp/myapp"
build_id = "${BUILD_ID}"
branch_name = "${BRANCH_NAME.toLowerCase().replace('-$', '')}"
app = ''
}
agent any
stages {
stage('Build') {
steps {
script {
app = docker.build(imageName + '-' + branch_name)
withDockerRegistry(credentialsId: dockerCredentials, url: dockerRegistryUrl) {
app.push(build_id)
app.push('latest')
}
}
}
}
stage('Build-Master') {
when {
branch 'master'
}
steps {
script {
app = docker.build(imageName)
withDockerRegistry(credentialsId: dockerCredentials, url: dockerRegistryUrl) {
app.push(build_id)
app.push('latest')
}
}
}
}
}
}
目前第一阶段针对所有情况执行,第二阶段仅根据when
表达式when { branch 'master' }
在master
分支上执行。您可以向第一阶段添加when
表达式,以便仅构建非主分支。那么master
分支将不会在两个阶段都执行:
stage('Build') {
when { not { branch 'master' } }
...
}
您可以查看when表达式文档获取更多信息。