GitHub Actions Workflow for Docker Build and Push to ECR
Build a secure ECR pipeline with OIDC, scoped IAM, and scanning.

Sponsored by Porter
- Written by
- Ship It Yourself Editors
- Updated
- November 26, 2026
- Reading time
- 8 min read
- Sources cited
- 1 sources ↓
What this covers
A GitHub Actions workflow for Docker build and push to ECR is easy to make functional. OIDC authentication, scoped IAM permissions, immutable image tags, and pre-push scanning must shape the workflow from the start, rather than arrive as patches after the first successful deployment.
Why the basic ECR push workflow leaves your pipeline exposed
A successful push proves that the runner can reach the registry and upload an image. It proves little about the safety of that path. The common IAM-user setup stores aws-access-key-id and aws-secret-access-key as GitHub secrets, which lets the workflow authenticate but leaves long-lived credentials to protect. Those credentials can leak, be rotated incorrectly, or never be rotated at all. The gap is between completing an operation and controlling who can perform it, with which image, under which conditions.
That gap starts before Docker builds anything. If the authentication design depends on a permanent secret, every later security gate sits on top of that dependency. To make the workflow production-ready, the stored credential must go before more checks are added around it.
How OIDC federation eliminates stored AWS credentials entirely
OIDC federation replaces stored AWS keys with a short-lived exchange. GitHub issues a signed token, called a JWT, to the runner for the job. The runner presents it to AWS STS through sts:AssumeRoleWithWebIdentity, and AWS validates it against the GitHub OIDC provider registered in the account. AWS then issues temporary credentials for the job. There is no permanent AWS secret to rotate.
The role’s trust policy decides which jobs can get credentials. Its aud claim must equal sts.amazonaws.com, while its sub claim should identify a specific repository and branch, such as repo:<ORG>/<REPO>:ref:refs/heads/main. A wildcard weakens that boundary by admitting more callers. The workflow also needs id-token: write and contents: read in its permissions block. Without the token permission, the OIDC exchange cannot give the job credentials.
Terraform is the right default for provisioning the provider and role because it makes the trust policy reviewable and auditable. Moving to self-hosted runners changes the trust model in practice because whoever controls the host can request cloud credentials within the trust policy’s scope.
The minimum IAM permissions that actually let a push succeed
Authentication establishes who the runner is allowed to become. Authorization defines what that role can do. Attaching AmazonEC2ContainerRegistryPowerUser gets past many setup problems, but grants more access than a push job needs. A narrowly scoped push policy is the better starting point.
The policy needs two distinct permission statements. ecr:GetAuthorizationToken requires a wildcard resource because it is an account-level call. The upload statement needs ecr:BatchCheckLayerAvailability, ecr:InitiateLayerUpload, ecr:UploadLayerPart, ecr:CompleteLayerUpload, and ecr:PutImage. Those actions should target arn:aws:ecr:REGION:ACCOUNT_ID:repository/REPO_NAME. Omitting an upload action can produce authentication errors that do not clearly identify IAM as the cause.
For a cross-account push, both the IAM policy and the repository policy must allow the operation. In the same account, either policy can allow access, but an explicit denial still blocks it. Scoping the upload actions to one repository limits the damage that compromised job credentials could cause elsewhere.
Structuring the workflow steps in the right order

With the role defined, the workflow can follow its dependencies. The source must be checked out before the build, and docker/setup-buildx-action@v4 must run before any build step that uses Buildx. Buildx provides the foundation for layer caching and multi-platform builds. Next, aws-actions/configure-aws-credentials@v6 uses role-to-assume to perform the OIDC exchange. AWS-dependent steps need those credentials before they run.
ECR login follows credential configuration. The build then produces the image that the scan will inspect, and the push follows only after that scan passes. This order is the security gate in practice. A combined build-and-push operation that publishes before inspection defeats the purpose, even if a scanner runs later in the same workflow.
For docker/build-push-action@v6, the context input set to . selects the build context. The important design choice is not an exhaustive set of flags, but keeping publication behind the scan result. Pin actions to major versions at minimum. Security-related actions need full commit SHA pins because their own integrity is part of the release path.
Why immutable image tagging with github.sha is a correctness requirement
The tag latest is a mutable pointer. Two builds can finish out of order, or a rollback can retag an older image. A deployment that follows that pointer can end up running old code while it appears to ask for the newest build. Push order is not release order.
Use github.sha as the default image tag. It identifies the exact commit that produced the image, and different commits do not share it. Deployment configuration can then name the intended commit instead of depending on a pointer being updated in step with the deployment. The running image tag also gives the team a direct answer to which commit is deployed.
If local development needs latest, keep it as a second tag pushed after the SHA tag. The SHA tag remains the deployment artifact. The convenience tag is only a shortcut for people. ECR lifecycle policies should clean up untagged and old images automatically rather than retain every SHA-tagged build indefinitely.
Scanning for CVEs before the push, not after
A pre-push scan can block publication of a vulnerable image. A post-push scan cannot undo its arrival in the registry or stop a deployment system that has already pulled it. The scan therefore belongs between build and push, with a hard failure for critical CVEs.
Trivy integrates through aquasecurity/trivy-action and can produce SARIF findings for the GitHub Security tab and pull-request code scanning alerts. It can also map vulnerabilities to specific Dockerfile lines. Setting ignore-unfixed to true narrows alerts to CVEs with an available patch, reducing noise from upstream issues the team cannot yet fix.
The scanner itself is also a dependency to protect. The March 2026 Trivy supply-chain incident and the remediation for CVE-2026-33634 make the case for pinning aquasecurity/trivy-action and other security actions to full commit SHAs. Mutable version tags such as @v0.20.0 are not equivalent pins.
Build-time scanning remains a snapshot of the image. ECR enhanced scanning complements it by monitoring images already in the registry as vulnerability information changes. After deployment, the Trivy Operator can provide in-cluster visibility, with Prometheus alerting on VulnerabilityReport metrics.
Locking down the workflow itself: branch protection, environment gates, and OIDC claim scoping
A clean image scan is insufficient if an uncontrolled workflow can assume the production role. Branch protection, role trust, and approval gates protect different parts of the path from commit to push. The branch-specific OIDC subject establishes which workflow context AWS accepts.
Organization metadata can further narrow role access. As of March 12, 2026, GitHub Actions OIDC tokens support organization-level repository custom property claims, including repo_property_compliance_tier and repo_property_team. The April 2, 2026 scoping example uses compliance_tier set to production to allow access only to repositories with that tag. Repository identity need not be the only condition.
A named GitHub environment such as production adds required reviewers, deployment wait timers, and environment-specific secrets. For a SOC 2-shaped pipeline, separate the build-and-scan job from the push job that holds the production role. The push waits until the scan passes and the environment approval is given.
The HIPAA-shaped pattern described here adds stricter controls. It uses GitHub-hosted runners for build and scan, but not for the job holding the production role. OPA gates check scan freshness within the last hour, cosign signature verification, an approver distinct from the author, and a calling workflow pinned to a semver tag. These controls apply to that pipeline design, with compliance requiring more than the workflow alone.
Layer caching, path filters, and multi-arch builds that keep CI costs proportionate
Once the release path is controlled, efficiency comes from avoiding unnecessary work while preserving gates. A changed layer invalidates downstream layers while leaving earlier layers available for reuse. The scan still runs where the release decision requires it.
Path filters reduce unnecessary workflow runs in monorepos. Filters that cover image inputs such as Dockerfile and src/** let a service build run only when those inputs change, leaving other repository edits out. This can save a lot of runner minutes while keeping that service’s tests and scan gate. The filter must reflect what affects the image.
Runner time is only part of the cost. Pulling ECR layers to a runner outside the AWS account crosses a metered network path, so smaller images and fewer redundant matrix legs reduce transfer work. For AMD64 and ARM64 builds, QEMU emulation on a hosted Linux runner is slower than native execution. Teams building frequently should evaluate native ARM runners before defaulting to emulation.
Small teams well below the hosted-runner free tier should default to GitHub Actions SaaS. The January 2026 price reduction strengthened that choice. At that scale, self-hosted runner maintenance is rarely justified, especially when its additional trust concerns are included.
Registry choice for AWS-first teams: ECR, GHCR, and the middle path
ECR is the natural default when workloads run on AWS. ECS tasks, EKS pods, and Lambda functions pulling from ECR in the same region avoid cross-region transfer costs. IAM also removes the need for separate runtime registry credentials. Enhanced scanning through Inspector works within the AWS account, so there is no need to deploy another scanning tool.
That advantage depends on where the workloads run. GitHub Container Registry, or GHCR, is a compelling option for teams spread across clouds because pushes authenticate with GITHUB_TOKEN, without an AWS role. Its appeal is a simpler push-side authentication model for a cloud-agnostic setup.
Build once, use GHCR as the source of truth, and push the same image tag to ECR. Production configuration points at ECR for regional runtime pulls, while development environments keep using GHCR.
Docker Hub also supports native GitHub Actions OIDC as of July 31, 2026 on Team, Business, Docker Hardened Images, and Docker Sponsored Open Source Program plans. Eligible workflows receive ephemeral tokens, removing the need to store a PAT. That changes the authentication comparison, but does not remove the need to weigh runtime location and registry access.
What to hand off to a PaaS layer versus what to keep in the workflow
The workflow’s endpoint is a trusted, immutable artifact in ECR. Scheduling its rollout is a different responsibility. A PaaS or deployment layer can own cluster upgrades, autoscaling, node lifecycle management, and the operational work that starts after publication.
The workflow must retain responsibility for its authentication, permissions, image identity, scan gate, and action pins. Those controls determine what enters the registry. The deployment layer then owns continuous rescanning and the response to post-deployment vulnerabilities, as well as rightsizing, spot instance management, and idle resource removal. Keeping environments separate at the infrastructure level, audit logging, and access reviews are also work that belongs outside the build job.
GitHub Actions produces the artifact, ECR stores it, and the deployment platform puts it to work. Porter, a managed Kubernetes PaaS that runs applications inside a team's own AWS account, is one such layer, handling autoscaling and cluster upgrades. A production-ready workflow stops at that handoff with an image whose origin and release conditions are explicit, rather than leaving the deployment system to guess what a successful push meant.
This article is sponsored by Porter.
Methodology & sources
- Build and push Docker images to Amazon ECR using GitHub Actions and Terraform - AWS Prescriptive Guidance
Covered the pattern of using GitHub OIDC with a Terraform-provisioned IAM role to push Docker images to ECR without stored AWS keys.