Building and pushing Docker images to ECR and GHCR from GitHub Actions
Part 6 of the shorty series: build the Go image for amd64 and arm64 in GitHub Actions and push it to Amazon ECR and GHCR. OIDC instead of access keys, tags from the git SHA and version, buildx with the GitHub cache, and cross-compiling so arm64 needs no QEMU.
The shorty image only exists on my laptop. To run it anywhere else it has to be built by CI and pushed to a registry, with a tag that tells you exactly which commit is inside. In this blog we will do that from GitHub Actions: build for amd64 and arm64, push to Amazon ECR (where ECS will pull from in the next part) and to GitHub's own registry, GHCR, and log in to AWS without storing any access keys.
This is part 6 of the shorty series. It builds on the CI workflow from part 5 and the hardened Dockerfile from part 4. Level is intermediate. You need an AWS account you can create IAM roles in and a GitHub repo with shorty in it.
Versions: docker/build-push-action@v7, docker/metadata-action@v6, docker/setup-buildx-action@v4, docker/login-action@v4, aws-actions/configure-aws-credentials@v6, aws-actions/amazon-ecr-login@v2, Terraform 1.17.1 with the AWS provider 6.73.0, Docker 29.8.2 locally. I checked all of these on GitHub the day I wrote this because the major versions moved quite a lot this year.
Why two registries
ECR is where the image has to be for ECS. Pulls from ECR in the same region have no data transfer charge, and the task execution role can read it with one managed policy. GHCR is free for public images and the package shows up next to the repo on GitHub, which is nice if people want to docker run shorty without an AWS account. If you only deploy to AWS, ECR alone is fine. Drop the GHCR lines.
No access keys: OIDC
The old way was an IAM user with an access key in a GitHub secret. That key never expires unless you rotate it, and anyone who can read the secret (or print it from a workflow) has it. With OIDC, GitHub gives each job a short-lived signed token, and AWS swaps it for temporary credentials of a role. Nothing to store. Nothing to rotate.
AWS has to trust GitHub's token issuer once per account. I keep this and the ECR repository in a small Terraform root called infra/bootstrap, which I apply by hand. It's the stuff CI itself needs to exist before CI can do anything.
resource "aws_iam_openid_connect_provider" "github" {
url = "https://token.actions.githubusercontent.com"
client_id_list = ["sts.amazonaws.com"]
}
Older guides add a thumbprint_list with a magic hex string. AWS checks GitHub's certificate against its own trusted CAs now, and in the 6.x provider the argument is optional, so I left it out.
The role is where the real security is. The trust policy says which GitHub workflows may assume it:
data "aws_iam_policy_document" "image_trust" {
statement {
actions = ["sts:AssumeRoleWithWebIdentity"]
principals {
type = "Federated"
identifiers = [aws_iam_openid_connect_provider.github.arn]
}
condition {
test = "StringEquals"
variable = "token.actions.githubusercontent.com:aud"
values = ["sts.amazonaws.com"]
}
condition {
test = "StringLike"
variable = "token.actions.githubusercontent.com:sub"
values = [
"repo:${var.github_repo}:ref:refs/heads/main",
"repo:${var.github_repo}:ref:refs/tags/v*",
]
}
}
}
resource "aws_iam_role" "image" {
name = "shorty-gha-image"
assume_role_policy = data.aws_iam_policy_document.image_trust.json
max_session_duration = 3600
}
The sub claim is the part people get wrong. It looks like repo:fenixara/shorty:ref:refs/heads/main for a push to main. If you only check aud, or use repo:*, basically any repository on GitHub can assume your role. Here only pushes to main and to v* tags of one repo get in. Pull requests have a different sub (repo:fenixara/shorty:pull_request), so a PR can't push images at all. If trust policies are new to you, IAM explained by writing policies goes through them line by line.
The permissions are just ECR push on one repository, plus ecr:GetAuthorizationToken, which only works on *:
data "aws_iam_policy_document" "image_push" {
statement {
sid = "Login"
actions = ["ecr:GetAuthorizationToken"]
resources = ["*"]
}
statement {
sid = "Push"
actions = [
"ecr:BatchCheckLayerAvailability",
"ecr:BatchGetImage",
"ecr:CompleteLayerUpload",
"ecr:GetDownloadUrlForLayer",
"ecr:InitiateLayerUpload",
"ecr:PutImage",
"ecr:UploadLayerPart",
]
resources = [aws_ecr_repository.shorty.arn]
}
}
The ECR repository
resource "aws_ecr_repository" "shorty" {
name = "shorty"
# sha-* and version tags can never be overwritten. Only "main" may move.
image_tag_mutability = "IMMUTABLE_WITH_EXCLUSION"
image_tag_mutability_exclusion_filter {
filter = "main"
filter_type = "WILDCARD"
}
image_scanning_configuration {
scan_on_push = true
}
}
Immutable tags matter for deploys. If sha-1a2b3c4 could be overwritten, "roll back to sha-1a2b3c4" would not mean anything. For a long time ECR made you pick: all tags immutable or none. The exclusion filter is newer and lets the one moving tag, main, stay mutable. One side effect: re-running the build job for a commit that was already pushed fails, because ECR refuses to push sha-1a2b3c4 a second time. I'm fine with that, the image is already there only.
There's also a lifecycle policy in the repo code that keeps v* release images and the last 50 others, so the repo doesn't grow forever. The full bootstrap is in the shorty code under infra/bootstrap:
cd infra/bootstrap
terraform init
terraform plan -out tfplan
terraform apply tfplan
terraform output image_role_arn
The state goes to S3 with native locking, set up as in storing Terraform state in S3. To be clear, I ran terraform fmt and terraform validate on this with Terraform 1.17.1, but I didn't apply it to a real account for this post.
Then in the GitHub repo, under Settings, Secrets and variables, Actions, add two variables (not secrets): AWS_ACCOUNT_ID and AWS_IMAGE_ROLE_ARN. A role ARN isn't a secret. Without a trust match it's useless to anyone.
The workflow
.github/workflows/image.yml, next to the ci.yml from part 5:
name: image
on:
push:
branches: [main]
tags: ["v*"]
pull_request:
permissions:
contents: read
env:
AWS_REGION: ap-south-1
ECR_IMAGE: ${{ vars.AWS_ACCOUNT_ID }}.dkr.ecr.ap-south-1.amazonaws.com/shorty
GHCR_IMAGE: ghcr.io/${{ github.repository }}
jobs:
build:
runs-on: ubuntu-latest
timeout-minutes: 20
permissions:
contents: read
id-token: write # OIDC token for AWS
packages: write # push to ghcr.io
outputs:
tag: ${{ steps.meta.outputs.version }}
digest: ${{ steps.build.outputs.digest }}
steps:
- name: AWS credentials
if: github.event_name != 'pull_request'
uses: aws-actions/configure-aws-credentials@v6
with:
role-to-assume: ${{ vars.AWS_IMAGE_ROLE_ARN }}
aws-region: ${{ env.AWS_REGION }}
- name: Log in to ECR
if: github.event_name != 'pull_request'
uses: aws-actions/amazon-ecr-login@v2
- name: Log in to GHCR
if: github.event_name != 'pull_request'
uses: docker/login-action@v4
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Tags and labels
id: meta
uses: docker/metadata-action@v6
with:
images: |
${{ env.ECR_IMAGE }}
${{ env.GHCR_IMAGE }}
tags: |
type=sha,priority=700
type=ref,event=branch
type=ref,event=pr
type=semver,pattern=v{{version}}
flavor: |
latest=false
- uses: docker/setup-buildx-action@v4
- name: Build and push
id: build
uses: docker/build-push-action@v7
with:
platforms: linux/amd64,linux/arm64
push: ${{ github.event_name != 'pull_request' }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
build-args: |
VERSION=${{ steps.meta.outputs.version }}
cache-from: type=gha
cache-to: type=gha,mode=max
There's one more step in the repo that writes the digest and tags to the job summary. actionlint 1.7.12 is happy with the whole file.
A few things that surprised me or that I had to look up.
id-token: write is what lets the job ask GitHub for an OIDC token. Without it configure-aws-credentials fails, because the job has no way to get an ID token. packages: write lets the built-in GITHUB_TOKEN push to GHCR, so there's no personal access token anywhere.
There's no actions/checkout step. build-push-action builds from the git context by default (https://github.com/<owner>/<repo>.git#<ref>), so BuildKit fetches the source itself. The .dockerignore still applies because it's in the repo. You only need checkout if a step before the build change files.
Pull requests build but don't push. The three login steps are skipped and push is false. You still find out in the PR if the Dockerfile is broken. Pull requests from forks don't get an OIDC token or secrets anyway, which is what you want.
And then lowercase. My GitHub org is FenixAra, with capitals, and Docker refuses image names with capitals. ghcr.io/${{ github.repository }} would break a plain docker push. metadata-action lowercases image names for you, which is one more reason to let it build the tags.
Tags
For a push to main, the tags come out as:
111122223333.dkr.ecr.ap-south-1.amazonaws.com/shorty:sha-1a2b3c4
111122223333.dkr.ecr.ap-south-1.amazonaws.com/shorty:main
ghcr.io/fenixara/shorty:sha-1a2b3c4
ghcr.io/fenixara/shorty:main
and for a pushed git tag v1.4.0, sha-... plus v1.4.0. sha-<7 chars> is the tag deploys will use. It's immutable and it points at one commit, which is the whole idea of building once and promoting the same image. main is just a convenience for "whatever was built last".
I turned latest off. Nothing of mine should ever deploy latest.
The priority=700 on the sha tag is a small trick. metadata-action's version output is the tag with the highest priority. By default the branch tag (600) beats sha (100), so on main the version would be main, and that's what shorty version would print. Pushing sha to 700 puts it above the branch but below semver (900). Now main builds print sha-1a2b3c4 and release builds print v1.4.0, through the VERSION build arg that the Dockerfile already passes to -ldflags -X main.version.
Two architectures without QEMU
Fargate on Graviton (arm64) is cheaper than x86 for the same size, and my Mac is arm64 too, so I want both. The usual answer is docker/setup-qemu-action, which emulates the other CPU. That works, but now what happens is the Go compiler for the arm64 half runs under emulation on GitHub's x86 runners. Slow.
Go can cross-compile, so the build stage doesn't need to run on the target CPU at all. Two changes to the Dockerfile from part 4:
FROM --platform=$BUILDPLATFORM golang:1.27.4-alpine AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
ARG VERSION=dev
ARG TARGETOS TARGETARCH
RUN CGO_ENABLED=0 GOOS=$TARGETOS GOARCH=$TARGETARCH go build -trimpath -ldflags="-s -w -X main.version=${VERSION}" -o /out/shorty ./cmd/shorty
--platform=$BUILDPLATFORM runs the build stage on the builder's own platform. BuildKit fills in TARGETOS and TARGETARCH for each platform you ask for. The runtime stage (distroless) has no RUN at all, it only copies the binary, so nothing ever needs emulation and I could drop the QEMU step completely.
I tried it locally before touching workflow:
docker buildx build --platform linux/amd64,linux/arm64 \
--build-arg VERSION=0.1.0-test -t shorty:multi --load .
The build log shows it plainly:
#14 [linux/arm64 build 4/6] RUN go mod download
#16 [linux/arm64->amd64 build 6/6] RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build ...
#17 [linux/arm64 build 6/6] RUN CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build ...
go mod download ran once, and the amd64 binary was compiled on arm64 (arm64->amd64). The whole thing took about 39 seconds with a warm base image. Both variants ran fine:
docker run --rm --platform linux/amd64 shorty:multi /shorty version
docker run --rm --platform linux/arm64 shorty:multi /shorty version
0.1.0-test
0.1.0-test
IMAGE ID DISK USAGE CONTENT SIZE
shorty:multi d62cbb7397c0 52.5MB 11.8MB
├─ linux/amd64 a95b7b675116 26.9MB 6.11MB
└─ linux/arm64 d145c1aeb4c8 25.6MB 5.64MB
This only works because shorty is built with CGO_ENABLED=0. With cgo you need a C cross compiler for each target, and QEMU starts looking reasonable again.
The build cache
cache-from: type=gha and cache-to: type=gha,mode=max store BuildKit's layer cache in the GitHub Actions cache. mode=max saves the layers of the build stage too, not only the final image, and those are the ones that matter here: the go mod download layer only changes when go.mod or go.sum change. The cache counts against the repo's Actions cache size limit, and old entries get evicted when it's full, so a cold build now and then is normal.
Note that this is a different cache from setup-go's cache in part 5. That one is for go test on the runner. This one is inside BuildKit.
Checking what got pushed
After a run, the digest is in the job summary. To check both platforms really made it to ECR:
aws ecr describe-images --repository-name shorty --image-ids imageTag=sha-1a2b3c4
docker buildx imagetools inspect 111122223333.dkr.ecr.ap-south-1.amazonaws.com/shorty:sha-1a2b3c4
imagetools inspect lists one manifest per platform. You'll probably see extra unknown/unknown entries as well, those are the build attestations that build-push-action adds by default, not broken images.
That's the image side done. Next part takes sha-1a2b3c4 from ECR and runs it on ECS Fargate behind a load balancer, all in Terraform.