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

197 Views Asked by At

In our project, we append the branch name when we build, unless it's master. And we tag them with the build_id and "latest". This is what we want.

- 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

In order to achieve this, we are building twice when it's on the master branc. I think it's weird. How can we avoid that?

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

There are 1 best solutions below

0
Matthew Schuchard On BEST ANSWER

Currently the first stage executes for all situations, and the second stage executes only on the master branch according to the when expression when { branch 'master' }. You can add a when expression to the first stage to only build non-master branches. Then the master branch will not execute for both stages:

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

You can check the when expression documentation for more information.