1

在我们的项目中,我们在构建时附加分支名称,除非它是 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

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

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')
          }
        }
      }
    }
  }
}
4

1 回答 1

0

目前第一阶段针对所有情况执行,第二阶段仅master根据when表达式在分支上执行when { branch 'master' }。您可以将when表达式添加到第一阶段以仅构建非主分支。然后master分支将不会在两个阶段都执行:

stage('Build') {
  when { not { branch 'master' } }
  ...
}

您可以查看when 表达式文档以获取更多信息。

于 2021-10-17T11:29:24.393 回答