HANDS-ON LAB Intermediate

GitHub Actions to AWS ECR via OIDC: Keyless CI/CD Authentication

Eliminate static AWS access keys by configuring OpenID Connect (OIDC) IAM federation between GitHub Actions and Amazon ECR.

Vibe DevOps·· ~8 min read
PythonDockerGitHub ActionsAWS IAMAmazon ECR

Key Takeaways & Prerequisites

  • Storing long-lived AWS IAM Access Keys in GitHub Secrets poses severe security risks; compromised keys can grant unrestricted account access.
  • OpenID Connect (OIDC) enables GitHub Actions workflows to obtain short-lived, temporary AWS STS credentials without storing any persistent secrets.
  • Configure AWS IAM Trust Policies with strict StringEquals and StringLike conditions matching your specific GitHub repository and branch.
  • Build and push Docker container images to private Amazon ECR repositories using native docker/build-push-action with provenance attestations.

Architecture & Execution Flow

  1. 01 →OIDC Identity ProviderTrust token.actions.githubusercontent.com
  2. 02 →IAM Role with Sub ClaimStrict repo & branch boundary
  3. 03 →STS AssumeRoleWithWebIdShort-lived 1-hour credentials
  4. 04 →ECR Login & PushZero permanent secrets stored
Table of Contents

Pushing an image from a local machine is trivial; granting CI push access without managing long-lived access keys is the architectural challenge. This lab builds a minimal HTTP service, compiles the release artifact, runs HTTP smoke tests against it, and pushes it to a private ECR registry. The scope terminates strictly at the registry: no ECS services are provisioned, no task definitions are updated, and the application is not exposed to the public Internet.

GitHub issues an OIDC token to the job; AWS validates the audience and subject claims, after which AWS STS issues short-lived temporary credentials. Setting id-token: write only grants permission to request the JWT—it does not inherently grant write access to ECR. The effective authorization boundary is governed strictly by the target IAM role.[1]

1. Prerequisites and Security Boundaries

Requirements include a GitHub repository with a main branch and GitHub Actions enabled, an AWS account, and the AWS CLI v2 configured on an administrative workstation authenticated via IAM Identity Center (AWS SSO) with permissions to provision IAM roles, OIDC identity providers, and ECR repositories. Do not use the AWS root account, and never provision long-lived access keys for the workflow. Docker is only required within the ubuntu-latest runner environment.

This guide assumes AWS Region ap-southeast-1, dummy account ID 111122223333, GitHub repository ORG/REPO, and ECR repository oidc-http-lab. Replace all instances of account IDs, organizations, and repository names before executing commands. The AWS CLI commands below must be executed in your administrative terminal, not embedded directly into the workflow.

Scoping trust policies to main is not a substitute for peer code review: anyone who can modify workflows on main can assume the role. Enforce branch protection rules, require mandatory code reviews, and restrict write permissions to .github/workflows/. This lab does not trigger on pull_request events to ensure untrusted PR code is never executed with AWS privileges.

2. Provisioning ECR and the IAM Role

Create a dedicated repository for this lab:

aws sts get-caller-identity
aws ecr create-repository \
  --region ap-southeast-1 \
  --repository-name oidc-http-lab \
  --image-tag-mutability IMMUTABLE

IMMUTABLE prevents overwriting existing tags; ECR will return an ImageTagAlreadyExistsException if you attempt to push an existing tag.[3] Tagging by Git commit SHA instead of latest ensures artifact traceability back to source code, though using a SHA does not guarantee build reproducibility on its own if the base image uses mutable tags.

Under IAM → Identity providers → Add provider, select OpenID Connect, enter the Provider URL https://token.actions.githubusercontent.com, and set the Audience to sts.amazonaws.com. If this provider already exists in your account, reuse it rather than creating a duplicate.[1]

Save trust.json on your administrative workstation:

{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": {
      "Federated": "arn:aws:iam::111122223333:oidc-provider/token.actions.githubusercontent.com"
    },
    "Action": "sts:AssumeRoleWithWebIdentity",
    "Condition": {
      "StringEquals": {
        "token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
        "token.actions.githubusercontent.com:sub": "repo:ORG/REPO:ref:refs/heads/main"
      }
    }
  }]
}

Note on new subject claims: The template above applies to repositories using traditional subject claims (typically repositories created before July 15, 2026 that have not opted into immutable subjects). Upstream documentation now specifies that newer repositories use the format repo:ORG@ORG_ID/REPO@REPO_ID:ref:refs/heads/main. For these repositories, substitute the exact ID-qualified subject in the trust policy; do not use the legacy format and expect authentication to succeed.[1][5]

The subject claim must match your exact owner/repository path without wildcards. If you later introduce GitHub Environments, the subject claim shifts to repo:ORG/REPO:environment:ENV_NAME; you must update the trust policy accordingly and configure environment protection rules rather than expanding the claim to repo:ORG/REPO:* as an insecure workaround.[1]

Save ecr-policy.json. Image upload actions are scoped strictly to the target repository; only GetAuthorizationToken requires Resource: "*" per AWS specifications.[2]

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "ecr:BatchCheckLayerAvailability",
        "ecr:InitiateLayerUpload",
        "ecr:UploadLayerPart",
        "ecr:CompleteLayerUpload",
        "ecr:PutImage",
        "ecr:BatchGetImage"
      ],
      "Resource": "arn:aws:ecr:ap-southeast-1:111122223333:repository/oidc-http-lab"
    },
    {
      "Effect": "Allow",
      "Action": "ecr:GetAuthorizationToken",
      "Resource": "*"
    }
  ]
}

Create the IAM role, attach the inline policy, and retrieve the ARN:

aws iam create-role --role-name github-ecr-lab \
  --assume-role-policy-document file://trust.json
aws iam put-role-policy --role-name github-ecr-lab \
  --policy-name PushOneRepository \
  --policy-document file://ecr-policy.json
aws iam get-role --role-name github-ecr-lab \
  --query Role.Arn --output text

Under GitHub Settings → Secrets and variables → Actions → Variables, configure three repository variables: AWS_REGION=ap-southeast-1, AWS_ROLE_ARN set to the retrieved ARN, and ECR_REPOSITORY=oidc-http-lab. These are non-sensitive configuration identifiers, not secrets. Do not configure AWS_ACCESS_KEY_ID or AWS_SECRET_ACCESS_KEY.

3. The Standalone Application and Dockerfile

In the root of your GitHub repository, create app.py:

from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer


class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        healthy = self.path == "/health"
        body = b"ok\n" if healthy else b"not found\n"
        self.send_response(200 if healthy else 404)
        self.send_header("Content-Type", "text/plain; charset=utf-8")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)


if __name__ == "__main__":
    ThreadingHTTPServer(("0.0.0.0", 8080), Handler).serve_forever()

Create the Dockerfile; copy only necessary artifacts, avoiding credentials or unvetted working directory context in the image:

FROM python:3.13-slim
WORKDIR /app
COPY app.py .
RUN python -m py_compile app.py
USER 10001:10001
EXPOSE 8080
CMD ["python", "-u", "app.py"]

This is an illustrative reference service, not a production web server hardened with TLS termination, authentication, or rate limiting. The base image utilizes a floating tag for simplicity in this lab; production pipelines should pin cryptographically audited image digests accompanied by automated update schedules.

4. CI/CD Workflow: Build → Smoke Test → Push

Create .github/workflows/ecr.yml as shown below. The referenced major versions align with upstream documentation: checkout v7, configure-aws-credentials v6, amazon-ecr-login v2.[4][5][6] Prior to production deployment, inspect releases and pin audited, immutable full commit SHAs rather than floating tags.

name: Build test and push ECR
on:
  push:
    branches: [main]
permissions:
  contents: read
  id-token: write
concurrency:
  group: ecr-main
  cancel-in-progress: false
jobs:
  image:
    runs-on: ubuntu-latest
    timeout-minutes: 15
    env:
      AWS_REGION: ${{ vars.AWS_REGION }}
      ECR_REPOSITORY: ${{ vars.ECR_REPOSITORY }}
    steps:
      - uses: actions/checkout@v7
        with:
          persist-credentials: false
      - name: Build amd64 image
        run: docker build --platform linux/amd64 -t lab:${{ github.sha }} .
      - name: Smoke test isolated container
        shell: bash
        run: |
          set -euo pipefail
          cleanup() {
            docker logs smoke || true
            docker rm -f smoke || true
          }
          trap cleanup EXIT
          docker run -d --name smoke --platform linux/amd64 \
            -p 127.0.0.1:18080:8080 "lab:$GITHUB_SHA"
          ready=0
          for attempt in $(seq 1 30); do
            if curl --fail --silent --show-error --max-time 1 \
              http://127.0.0.1:18080/health -o /tmp/health; then
              ready=1
              break
            fi
            sleep 1
          done
          test "$ready" -eq 1
          printf 'ok\n' | cmp - /tmp/health
          status=$(curl --silent --show-error --max-time 2 \
            -o /tmp/missing -w '%{http_code}' \
            http://127.0.0.1:18080/missing)
          test "$status" = 404
          printf 'not found\n' | cmp - /tmp/missing
      - name: Assume AWS role through OIDC
        uses: aws-actions/configure-aws-credentials@v6
        with:
          role-to-assume: ${{ vars.AWS_ROLE_ARN }}
          aws-region: ${{ vars.AWS_REGION }}
          role-session-name: gha-${{ github.run_id }}
          role-duration-seconds: 900
      - name: Verify AWS identity
        run: aws sts get-caller-identity
      - name: Login ECR
        id: login
        uses: aws-actions/amazon-ecr-login@v2
      - name: Push tested image
        env:
          REGISTRY: ${{ steps.login.outputs.registry }}
        run: |
          set -euo pipefail
          image="$REGISTRY/$ECR_REPOSITORY:$GITHUB_SHA"
          docker tag "lab:$GITHUB_SHA" "$image"
          docker push "$image"
          printf 'Published `%s`\n' "$image" >> "$GITHUB_STEP_SUMMARY"

Smoke tests execute prior to assuming AWS credentials; ports bind strictly to the runner's loopback interface with no external traffic egressing to production systems. The polling loop implements bounded retries, validating both HTTP status codes and response payloads; the bash trap dumps container stdout/stderr and removes the container on exit, even upon failure. The validated container image is retagged directly, avoiding non-deterministic rebuilds. The linux/amd64 architecture is specified for ECS tasks backed by X86_64; this image cannot be scheduled on ARM64 compute without cross-compilation.

5. Verification and Troubleshooting

Push a new commit to main and navigate to the Actions tab. The pipeline succeeds when: the build completes, /health returns ok\n, unmatched paths return 404, caller identity reflects the expected AWS account and assumed-role/github-ecr-lab/... ARN, and the push step outputs an image digest. From your administrative workstation, verify the pushed image by SHA:

SHA=THAY_BANG_40_KY_TU_COMMIT_SHA
aws ecr describe-images --region ap-southeast-1 \
  --repository-name oidc-http-lab --image-ids imageTag="$SHA" \
  --query 'imageDetails[0].{digest:imageDigest,tags:imageTags}'

This query relies on your administrative read privileges; the CI role intentionally omits ecr:DescribeImages to enforce least privilege.

Symptom Initial Checks
AssumeRoleWithWebIdentity rejected Verify provider/role account ID, audience, and that the subject claim matches main without accidental environment scoping.
Unable to fetch OIDC token Check job-level id-token: write permissions and ensure GitHub organization policies permit OIDC actions.
Login succeeds but upload returns AccessDenied Verify the ECR repository ARN, Region, and IAM push policy; authenticating against the registry does not confer write access.
Repository does not exist Verify prior ECR provisioning; reconcile repository variables against the correct target AWS account ID.
Smoke test timeout Inspect container logs, verify the process binds to 0.0.0.0:8080, check port mappings, and review build errors.
ImageTagAlreadyExistsException The SHA tag was already published; do not toggle repository mutability to bypass this guardrail.[3]

Retry semantics: The workflow deliberately fails if the SHA tag already exists in the registry. A failed run prior to the push step can be safely retried; retrying a run after the tag has been committed requires promoting the existing artifact or committing a new SHA. If the push step terminates due to a network timeout, inspect ECR first: a failed CI step does not guarantee the image layers were not persisted. Never delete existing tags simply to turn CI green.

6. Cost, Teardown, and Next Steps

Amazon ECR incurs storage and data transfer charges; do not assume your account qualifies for free tier allowances.[7] Likewise, verify your GitHub Actions runner consumption against your plan limits. This lab provisions no ECS clusters, NAT Gateways, or load balancers. In workflows producing many SHA tags, configure an ECR lifecycle policy aligned with your retention and rollback requirements.

Only after verifying that the repository is strictly isolated to this lab and consumed by no active workloads, execute teardown:

aws ecr delete-repository --region ap-southeast-1 \
  --repository-name oidc-http-lab --force
aws iam delete-role-policy --role-name github-ecr-lab \
  --policy-name PushOneRepository
aws iam delete-role --role-name github-ecr-lab

Delete the GitHub repository variables if decommissioning the environment; retain the IAM OIDC provider if shared across other roles. A successful CI push validates that the artifact resides in ECR, but does not guarantee runtime stability on AWS compute. Proceed to deploying containers to ECS Fargate using the verified image URI and digest.

Validation scope: This guide outlines a prescriptive architectural pattern rather than a static execution log. You must execute and validate the Actions workflows and ECR operations within your own AWS account; simulated cloud results cannot substitute for runtime verification.

Sources

[1] https://docs.github.com/en/actions/how-tos/secure-your-work/security-harden-deployments/oidc-in-aws — GitHub OIDC for AWS [2] https://docs.aws.amazon.com/AmazonECR/latest/userguide/image-push-iam.html — ECR push permissions [3] https://docs.aws.amazon.com/AmazonECR/latest/userguide/image-tag-mutability.html — ECR immutable tags [4] https://raw.githubusercontent.com/actions/checkout/main/README.md — Checkout action [5] https://raw.githubusercontent.com/aws-actions/configure-aws-credentials/main/README.md — Configure AWS credentials action [6] https://raw.githubusercontent.com/aws-actions/amazon-ecr-login/main/README.md — ECR login action [7] https://aws.amazon.com/ecr/pricing — ECR pricing

Read critically, test before applying. Examples reflect Vibe DevOps lab environments; adjust parameters to your infrastructure and verify in staging first.← Back to Hands-on Labs

Next Recommended Labs