docker / build-push-action

GitHub Action to build and push Docker images with Buildx
https://github.com/marketplace/actions/build-and-push-docker-images
Apache License 2.0
4.24k stars 541 forks source link

Can't push to ECR | 403 Forbidden #901

Closed ajilk closed 1 year ago

ajilk commented 1 year ago

I am trying to cache the layers and push the built image to ECR. However, it is not working for the below workflow file. I am getting a 403 forbidden. I believe the action is not taking context into account somehow, because it does work when pushed manually so I believe I've configured everything (IAM policies, secrets) correctly

name: build and push docker image to ECR

run-name: ${{ github.actor }} is building and pushing docker image

on: workflow_dispatch

permissions:
  id-token: write
  contents: read

jobs:
  push:
    runs-on: ubuntu-latest
    steps:
      - name: Check out repository code
        uses: actions/checkout@v3

      - name: Configure AWS credentials
        uses: aws-actions/configure-aws-credentials@v2
        with:
          aws-region: us-east-1
          role-to-assume: ${{ secrets.role_to_assume}}

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

      # DOES NOT WORK
      - name: Setup Docker buildx
        uses: docker/setup-buildx-action@v2

      - name: Get tags for image
        id: metadata
        uses: docker/metadata-action@v4
        with:
          images: ${{ steps.ecr-login.outputs.registry }}/${{ secrets.repository }}
          tags: |
            type=raw,value=latest
            type=raw,value=main
            type=sha

      - name: Build and Push
        id: image
        uses: docker/build-push-action@v4
        with:
          context: .
          push: true
          tags: ${{ steps.metadata.outputs.tags }}
          cache-from: type=gha
          cache-to: type=gha,mode=max

      # WORKS
      # - name: Build and Push
      #   env:
      #     REGISTRY: ${{ steps.ecr-login.outputs.registry }}
      #     REPOSITORY: ${{ secrets.repository }}
      #   run: |
      #     docker build -t $REGISTRY/$REPOSITORY:latest .
      #     docker push $REGISTRY/$REPOSITORY:latest
ajilk commented 1 year ago

was missing "ecr:BatchGetImage", apparently that is need by docker/build-push-action but not needed when pushed manually

Final IAM policy

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ecr:CompleteLayerUpload",
                "ecr:BatchGetImage",
                "ecr:UploadLayerPart",
                "ecr:InitiateLayerUpload",
                "ecr:BatchCheckLayerAvailability",
                "ecr:PutImage"
            ],
            "Resource": "arn:aws:ecr:region:111122223333:repository/repository-name"
        },
        {
            "Effect": "Allow",
            "Action": "ecr:GetAuthorizationToken",
            "Resource": "*"
        }
    ]
}