Search code examples
dockergithub-actionsdocker-imagegit-tag

Build Docker Image and tag it with github tag name


I have created a GitHub action on repo tag creation. I am successfully able to build and push the Docker image to AWS but, I don't know how to tag the image with the same name of the GitHub tag. Below is my git workflow file

name: Build Docker Image and Push to AWS ECR
on:
  push:
    tags:
    - '*'


jobs:

  build:

     runs-on: ubuntu-latest

     steps:
         - name: Checkout
           uses: actions/checkout@v1

         - name: Configure AWS credentials
           uses: aws-actions/configure-aws-credentials@v1
           with:
               aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
               aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
               aws-region: us-west-2

         - name: Login to Amazon ECR
           id: login-ecr
           uses: aws-actions/amazon-ecr-login@v1

         - name: Build, tag, and push image to Amazon ECR
           id: build-image
           env:
               ECR_REGISTRY: ${{ secrets.AWS_REGISTRY }}
               ECR_REPOSITORY: repo_name
               IMAGE_TAG: latest
           run: |
               docker build -t $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG .
               docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG

Please help me in replacing the correct value at IMAGE_TAG in the above code


Solution

  • We decided the use the git commit sha as the image tag, as it always represents the unique state of the code.

    - name: Build, tag, and push image to Amazon ECR
      env:
        ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}
        ECR_REPOSITORY: reponame
        IMAGE_TAG: ${{ github.sha }}
      run: |
        docker build -t $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG .
        docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG
    

    If you need or prefer to use the commit tag, you just need to extract it from the ref using something like this:

    - name: Extract Git Tag
      run: echo "GIT_TAG=${GITHUB_REF/refs\/tags\//}" >> $GITHUB_ENV
    - name: Build, tag, and push image to Amazon ECR
      env:
        ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}
        ECR_REPOSITORY: reponame
        IMAGE_TAG: ${{ env.GIT_TAG }}
      run: |
        docker build -t $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG .
        docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG