如何避免在 Jenkinsfile 中构建两次以获得不同的图像名称?

How to avoid building twice in a Jenkinsfile in order to have different image names?

在我们的项目中,我们在构建时附加分支名称,除非是master。我们用 build_id 和“最新”标记它们。这就是我们想要的。

- 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

为了实现这一点,我们在 master 分支上构建了两次。我觉得很奇怪。我们怎样才能避免这种情况?

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 expression documentation 了解更多信息。