0
votes

My target is to build docker images and tag them depending on the git branch and tag. The following rules should apply with the aim to have only one GitHub Actions workflow.

Rules:

  • push to develop branch creates a new image with the tag: latest
  • push to main branch creates a new image with the tag: stable
  • tag on main branch creates a new image with the given git tag as docker image tag f.e. git tag: 1.0.0 --> image tag: registry/company/project:1.0.0

My question is: Do you see a better (less code duplication) way to solve the issue of the following GitHub Actions configuration?

env:
  RELEASE_VERSION: ${GITHUB_REF#refs/*/}

... (previous jobs)

containerize:
    needs: build
    runs-on: ubuntu-latest
    steps:
     
     ... (previous steps)

      - name: Build and push Docker image to Registry with latest as image version
        if: github.ref == 'refs/heads/develop'
        uses: docker/build-push-action@v2
        with:
          context: .
          file: ./docker/Dockerfile
          push: true
          tags: ${{ secrets.REGISTRY_URL }}/company/project:latest
      
      - name: Build and push Docker image to Registry with stable as image version
        if: github.ref == 'refs/heads/main'
        uses: docker/build-push-action@v2
        with:
          context: .
          file: ./docker/Dockerfile
          push: true
          tags: ${{ secrets.REGISTRY_URL }}/company/project:stable
      
      - name: Build and push Docker image to Registry with given tag as image version
        if: ${{ env.RELEASE_VERSION }} != '' && github.ref == 'refs/heads/main'
        uses: docker/build-push-action@v2
        with:
          context: .
          file: ./docker/Dockerfile
          push: true
          tags: ${{ secrets.REGISTRY_URL }}/company/project:${{ env.RELEASE_VERSION }} 
1

1 Answers

0
votes

Currently, I don't think there is any better way to do it.

You could try to replace ${{ secrets.REGISTRY_URL }}/company/project by an environment variable. Something like ${{ env.IMAGE }}:latest and set it once at the job level:

containerize:
    needs: build
    runs-on: ubuntu-latest
    env:
      IMAGE: ${{ secrets.REGISTRY_URL }}/company/project

But that's not much of an improvement