Search code examples
github-actions

Add a tag to a Docker image if there's a git tag using GitHub Action


I'm using GitHub Actions to build a docker image using the build-push-action. I'd like to add tags to the image before pushing it to the docker registry:

  • Each image should be tagged with latest
  • If the commit that triggered the build has a git tag attached, the image should be tagged with this tag as well.

I have something along the lines of:

- name: Build and push
  id: docker_build
  uses: docker/build-push-action@v2
  with:
    context: .
    push: true
    tags:
      - user/image:latest

It would be easy to always add more tags, but I want to add it only if there's a git tag. Is there a way to do that?


Solution

  • There's a docker/metadata-action that does this. Make sure to set up the push tags trigger along with whatever other triggers you might need. The action docs have a lot more details about what tags it applies for each event trigger type. See also https://docs.github.com/en/actions/publishing-packages/publishing-docker-images for even more info on the general topic of Docker image publishing.

    name: Tag Docker Image with Git
    
    on:
      push:
        tags: [ v* ]
    
    env:
      REGISTRY: ghcr.io
      IMAGE_NAME: ${{ github.repository }}
    
    jobs:
      build:
    
        runs-on: ubuntu-latest
    
        steps:
        - name: Checkout
          uses: actions/checkout@v2
    
        - name: Log into the Container registry
          uses: docker/login-action@f054a8b539a109f9f41c372932f1ae047eff08c9
          with:
            registry: ${{ env.REGISTRY }}
            username: ${{ github.actor }}
            password: ${{ secrets.GITHUB_TOKEN }}
    
        - name: Extract metadata for the Docker image
          id: meta
          uses: docker/metadata-action@98669ae865ea3cffbcbaa878cf57c20bbf1c6c38
          with:
            images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
    
        - name: Build and push the Docker image
          uses: docker/build-push-action@ad44023a93711e3deb337508980b4b5e9bcdc5dc
          with:
            context: .
            push: true
            tags: ${{ steps.meta.outputs.tags }}
            labels: ${{ steps.meta.outputs.labels }}