GitHub Hour 4: Moving to the Cloud (AWS)

No access keys stored. Use GitHub OIDC to get temporary AWS credentials, send myapp from CI to ECR, ECS Fargate, EKS and Lambda, and practice multi-account promotion and rollback
configure-aws-credentials v6.3.0amazon-ecr-login v2.1.7ecs-deploy-task-definition v2.6.4Region ca-central-1Verified against official docs · 2026-11-15
Overall learning goals
  • Based on what the team has to operate, choose among ECS on Fargate / ECS Express Mode / EKS / Lambda options, and know that App Runner is no longer accepting new customers, so new projects should use ECS Express Mode.
  • Build by hand the GitHub → IAM OIDC federation: the IAM OIDC identity provider and the aud/sub conditions in the role trust policy, and to correctly handle the immutable subject format from 2026-07-15 onward (repo:owner@ID/repo@ID:…).
  • Use aws-actions/amazon-ecr-login to push to immutable tags ECR repository, read the scan results, and deploy by digest .
  • Use render-task-definition + deploy-task-definition to deploy to ECS Fargate, wait for the service to stabilize, and use the deployment circuit breaker to roll back automatically; learn about ECS native blue/green.
  • Create EKS access entries for the CI role, then deploy with kubectl/helm; use Lambda versions + weighted aliases for progressive rollouts.
  • Design dev / stage / prod multi-account setup with roles and environment approvals roles and environment approvals, understand the organization-level OIDC trust model, and be able to troubleshoot independently Not authorized to perform sts:AssumeRoleWithWebIdentity and similar typical errors.

1-hour time plan

#TimeModuleCore contentAnimation / interactionLab (AWS account · ca-central-1)
0Before classWarm-up and AWS setupAWS CLI v2, lab IAM identity, budget alert, get owner/repo numeric IDsOIDC prerequisite self-checkaws sts get-caller-identity
100–05Choosing an AWS deployment architectureECS Fargate / Express Mode / EKS / Lambda; App Runner status; GitHub Actions neededArchitecture decision toolConfirm region and quotas
205–14OIDC federation: GitHub → IAMOIDC provider, trust policy aud/sub, immutable subject,configure-aws-credentials@v6, session duration, and role chainingCore animation: OIDC → STS token exchange (including failure scenarios)Create OIDC provider + role, have the workflow print its identity
314–21Build and push to ECRamazon-ecr-login@v2, IMMUTABLE, scan on push, digest, lifecycle policyTag vs digest push simulationCI push sha- tag
421–30Deploy to ECS on FargateRender task definition, deploy service, wait for stability, circuit-breaker rollback, native blue/greenRolling deployment + circuit breaker state machineWorkflow deploys myapp-dev
530–38Deploy to EKS and LambdaEKS access entries, update-kubeconfig, kubectl/helm; Lambda image/zip, versions and weighted aliasesLambda alias traffic shifting(Optional) Lambda alias 10% canary
638–45Multi-account and environment promotionAccount isolation, one role per environment, environment approvals, organization-level trust (repository_owner_id)Promotion pipeline and trust matrixprod role trusts only environment:prod
745–54Troubleshooting cloud deploymentsAssumeRoleWithWebIdentity denied, No OpenIDConnect provider, ECR login, ECS stuck, EKS UnauthorizedInteractive troubleshooting treeDeliberately cause a sub mismatch and fix it
854–60Cost, cleanup and self-checkCost breakdown, cleanup order, safe removal (roles, providers, repository variables)Cost estimatorOne-click cleanup script
—After classCheat sheet · Capstone labCI → OIDC → ECR (immutable) → ECS (dev automatic / prod approval) → circuit-breaker rollback → cleanupFinal quiz (12 questions)Capstone lab

Knowledge Coverage Matrix

Target skillM1M2M3M4M5M6M7M8Key commands / ActionLab
Choose an AWS compute service by scenario✓··✓✓··✓Decision tableM1
No keys: OIDC → STS temporary credentials·✓✓✓✓✓✓·configure-aws-credentials@v6M2
Write a minimal working trust policy (aud/sub/immutable format)·✓···✓✓·aws iam create-roleM2/M6
Push immutable images and reference them by digest··✓✓✓·✓·amazon-ecr-login@v2,docker/build-push-actionM3
ECS deployment, wait for stability, circuit-breaker rollback···✓·✓✓·amazon-ecs-deploy-task-definition@v2M4 / capstone
EKS access entries and CI deployment····✓·✓·aws eks create-access-entryM5 (reading)
Lambda version/alias progressive rollout✓···✓···aws lambda update-alias --routing-configM5 (optional)
Multi-account, environment approvals and promotion·✓···✓··environment:,vars.AWS_ROLE_ARNCapstone
Troubleshooting cloud deployment failures·✓✓✓✓·✓·CloudTrail,describe-servicesM7
Cost control and full cleanup··✓····✓aws ecs delete-service --forceM8

Topics not covered in this lab (and where to learn them)

TopicWhy it is not in this labWhere to learn it
Dockerfile, multi-stage builds, ECS task definition fields and ALB detailsContainers are covered in the Docker course; this lab only covers how GitHub drives themDocker Lesson 4 (AWS ECS/ECR/EKS)
EKS cluster creation, VPC CNI, Karpenter, Pod IdentityBelongs to Kubernetes platform operationsK8s Lesson 7 (EKS)
Managing OIDC providers, roles and ECS resources with TerraformThis lab uses the CLI so every step is visible; production should use IaCTerraform course Lesson 4 (AWS)
Azure federated credentials (Entra workload identity)Covered in the previous lesson; this lab maps one-to-one to itLesson 3 (Azure)
Reusable workflows, artifact attestations, pinning Action SHAs and hardeningBelongs to the 'production-grade Actions' topicLesson 5
Git credentials, branches and mergingCovered in the Git courseGit 8-hour course

How to use these course materials

10 pages per module
Principles · diagrams · animations · commands · labs · production cases · troubleshooting · quizzes · audio · video. Read 'Principles' and 'Animation' first, then do the 'Lab'. The token exchange animation in Module 2 is the core of the course.
Learning progress
A quiz score of ≥ 70% or clicking 'Mark this module complete' counts toward progress, stored in this browser (cleared on refresh if local storage is disabled).
Audio narration
The Audio page reads the narration aloud using the browser's Web Speech API (en-US); if no Chinese voice pack is installed, the narration script is still readable as text.
Cost and security notes This lab incurs a small amount of AWS cost (Fargate tasks, ECR storage, CloudWatch logs, public IPv4 addresses). With the minimum configuration in this lab (two 0.25 vCPU / 0.5 GB tasks, no ALB), running for 1 hour costs roughly US$0.10; forgetting to clean up is the real risk. Set up a budget alert first inBefore class, and after class run theModule 8 cleanup script. Prices follow the AWS Pricing Calculator official pricing page.
Version notes (verified 2026-11-15)aws-actions/configure-aws-credentials v6.3.0; amazon-ecr-login v2.1.7; amazon-ecs-render-task-definition v1.9.1; amazon-ecs-deploy-task-definition v2.6.4; amazon-ecs-deploy-express-service v1.2.2; aws-lambda-deploy v1.1.2; actions/checkout v7.0.1; docker/build-push-action v7.4.0; docker/setup-buildx-action v4.4.1. Examples use major version tags for readability; for production, pin by SHA (see the command page in Module 2 and Lesson 5).

Module 0 · Warm-up and AWS setup (complete before class)

Prepare an AWS account you can safely experiment in, a lab identity and a budget alert, and get the numeric IDs of your GitHub repository
Before class ≈ 10 minAWS CLI v2 · gh CLI
Prerequisites
  • CompletedLesson 2(Actions core: permissions, environments, variables and secrets) andLesson 3(OIDC and how it maps to Azure).
  • Under a personal account you have a myapp repository (the Flask + gunicorn app from the Docker course, listening on 5000, serving /healthz, with the Dockerfile in the repository root). /healthz It does not depend on Redis, and this lab does not deploy Redis, so the page showing hits=N/A is normal. We recommend making myapp a public repository: with GitHub Free/Pro/Team plans, required reviewers and wait timers for environments are only available for public repositories (private repositories need Enterprise; on the Free plan, environment secrets are not available for private repositories either). Do not commit any secrets to the repository; this lab does not need any.
  • A lab-only AWS account (strongly recommended not to use a company production account), plus an admin identity with IAM, ECR, ECS, EC2 (security groups) and CloudWatch Logs permissions (an IAM Identity Center user or administrator role).
  • Local machine or Codespaces: AWS CLI v2,gh CLI (already gh auth login),jq, Git 2.56, Docker Engine 29 (for local debugging only; CI builds on GitHub-hosted runners).

Connection with the previous lesson

Lesson 3 (Azure)This lesson (AWS)Notes
Entra app registration / user-assigned managed identityIAM roleCloud identity that a GitHub workload assumes
Federated identity credential (issuer + subject + audience)IAM OIDC identity provider + role trust policy conditionsAWS splits 'who to trust' into two layers: an account-level provider + role-level conditions
azure/login@v3aws-actions/configure-aws-credentials@v6both are needed permissions: id-token: write
audience api://AzureADTokenExchangeaudience sts.amazonaws.comAction defaults; no need to write manually
ACR / Container Apps / AKSECR / ECS Fargate / EKSImage registry / managed containers / Kubernetes

Step 1: Confirm the AWS identity and region

aws --version
export AWS_REGION=ca-central-1
aws configure set region $AWS_REGION          # or set it in the SSO profile
aws sts get-caller-identity
export ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
aws-cli/2.x.x Python/3.x Linux/6.x
{
    "UserId": "AROAEXAMPLEID:you@example.com",
    "Account": "111122223333",
    "Arn": "arn:aws:sts::111122223333:assumed-role/AWSReservedSSO_AdministratorAccess_abc123/you@example.com"
}

All example account numbers in this lab are 111122223333 (the placeholder values commonly used in AWS docs); replace them with your own $ACCOUNT_ID. Do not create an IAM user with long-term access keys for the lab. That is exactly the practice this lesson is retiring.

Step 2: Set a budget alert (1 minute, strongly recommended)

cat > budget.json <<'EOF'
{ "BudgetName": "gh-lab-10usd", "BudgetLimit": {"Amount": "10", "Unit": "USD"},
  "TimeUnit": "MONTHLY", "BudgetType": "COST" }
EOF
cat > notify.json <<'EOF'
[{ "Notification": {"NotificationType":"ACTUAL","ComparisonOperator":"GREATER_THAN","Threshold":50,"ThresholdType":"PERCENTAGE"},
   "Subscribers": [{"SubscriptionType":"EMAIL","Address":"you@example.com"}] }]
EOF
aws budgets create-budget --account-id $ACCOUNT_ID --budget file://budget.json \
  --notifications-with-subscribers file://notify.json

Sends an email when actual spend exceeds US$5 (50% of US$10). A plain budget that only notifies has no extra charge; budgets with automated actions (Budget Actions) are charged per day after the free allowance. See the AWS Budgets pricing page.

Step 3: Get the numeric IDs of the GitHub owner and repo (needed in Module 2)

Since 2026-07-15,newly created, renamed or transferred repositories use immutable subject: repo:OWNER@OWNER-ID/REPO@REPO-ID:…. You need to know which format your repository uses, and both numbers.

export GH_OWNER=$(gh api user --jq .login)        # for organization repos, use the organization name
export GH_REPO=myapp
gh api repos/$GH_OWNER/$GH_REPO --jq '{owner: .owner.login, owner_id: .owner.id, repo: .name, repo_id: .id, created_at: .created_at}'
{
  "owner": "octo-dev",
  "owner_id": 123456,
  "repo": "myapp",
  "repo_id": 789012,
  "created_at": "2026-09-02T08:15:11Z"
}
How do you tell which subject to use? If the repository was created after 2026-07-15, or was renamed or transferred afterward, or an organization/repository admin has opted in manually: immutable format repo:octo-dev@123456/myapp@789012:ref:refs/heads/main; otherwise it is still the legacy format repo:octo-dev/myapp:ref:refs/heads/main. The most reliable approach is to, in the Module 2 lab,have the workflow print the real sub before writing the trust policy (without printing the token itself).

Warm-up: answer from memory (30 seconds)

Why is storing AWS_ACCESS_KEY_ID in GitHub Secrets no longer the recommended practice?

Long-term keys never expire automatically. If they leak from logs, forks, third-party Actions or departing staff, they remain valid until someone rotates them manually. OIDC gives each run temporary credentials that last 1 hour by default, and only runs that satisfy the trust policy conditions (repository, branch, environment) can get them.

Which permission must be added under permissions in the workflow to request an OIDC token?

id-token: write. It only allows requesting and using OIDC tokens and grants no write access to the repository. Once it is set, permissions any other unlisted permissions become none, so you usually also need to add contents: read for checkout.

In Lesson 3, is the subject in the Azure federated credential the same thing as the sub in the AWS trust policy?

Yes, they are the same GitHub OIDC token sub claim. The difference is that Azure federated credentials require an exact match (or use flexible federated credential expressions), whereas AWS trust policies can use StringEquals exact matching, or also use StringLike with wildcards.

Environment self-check list

Module 1 · Choosing an AWS deployment architecture

00:00 – 05:00 · First decide how much the team is willing to operate, then decide which set of APIs the GitHub workflow should call
5 minECS Fargate · Express ModeApp Runner no longer accepts new customers★★★★
Learning objectives
  • Explain the operational boundaries, billing and the matching official GitHub Action for ECS on Fargate, ECS Express Mode, EKS and Lambda.
  • Know the current status of App Runner: no longer accepts new customers (existing customers can keep using it, but no new features are added); AWS recommends migrating to ECS Express Mode.
  • Understand that wherever you deploy, the GitHub → AWS identity chain is the same: OIDC → STS → temporary credentials → service API.
Prerequisites: The ECS object model from Docker Lesson 4 (cluster, task definition, service). Importance:★★★★

What: four mainstream destinations

ECS on FargateECS Express ModeEKSLambda
What you deliverImage + task definition JSON + service configurationImage + two IAM roles (one API call)Image + Kubernetes manifests / Helm chartZip package or container image + function configuration
What AWS manages for youServers, scheduling, rolling deploymentsOn top of ECS, automatically creates an ALB (with TLS), auto scaling, networking, loggingControl plane (Auto Mode also manages nodes)All servers and scaling; billed per request
GitHub deployment Actionamazon-ecs-render-task-definition@v1 + amazon-ecs-deploy-task-definition@v2amazon-ecs-deploy-express-service@v1No official dedicated Action: aws eks update-kubeconfig + kubectl/helmaws-lambda-deploy@v1 or AWS CLI / SAM
Core permissions needed by the CI roleecs:RegisterTaskDefinition,ecs:UpdateService,ecs:DescribeServices,iam:PassRolecreate/update of Express services + iam:PassRoleeks:DescribeCluster + EKS access entries (Kubernetes permissions)lambda:UpdateFunctionCode,PublishVersion,UpdateAlias
Typical cost starting pointBilled by task vCPU/memory-secondsExpress Mode itself is free; you pay only for the underlying resources (Fargate, ALB, etc.)Cluster hourly fee + nodes/FargateRequests + GB-seconds, with a free tier

Why: why the destination affects the workflow

The deployment steps in a workflow are essentially which set of AWS APIs to call with temporary credentials. ECS deployment is RegisterTaskDefinition → UpdateService → DescribeServices polling; EKS deployment is DescribeCluster after getting the endpoint, use the IAM identity to call Kubernetes API (permissions are mapped by EKS access entries); Lambda is UpdateFunctionCode → PublishVersion → UpdateAlias. The destination determines the CI role's permission policy, the rollback method and where to start troubleshooting.

How: current status of App Runner (verified)

The official AWS documentation 'AWS App Runner availability change' states that App Runner is no longer open to new customers; existing customers can keep using it as usual (including creating new services), and AWS continues to invest in security and availability, but no new features are planned. AWS officially recommends migrating to Amazon ECS Express Mode: one API call, providing one image and two IAM roles (the task execution role ecsTaskExecutionRole and the infrastructure role ecsInfrastructureRoleForExpressServices); ECS will create the Fargate service, ALB, auto scaling and networking in your account; Express Mode itself carries no additional charge. The date when new customers stopped being accepted is recorded as 2026-04-30 per the verification in the Docker course of this repository (the AWS documentation page itself has no date; follow the official page).

When: how to choose

  • A web/API service, and the team does not want to touch Kubernetes: start with ECS Express Mode; when you need fine-grained control (Service Connect, custom deployment strategies, multi-container sidecars), move down to a regular ECS service. Express Mode creates regular ECS/ELB resources, which you can take over directly.
  • Already have task definitions and services, and want precise control over each release: ECS on Fargate + official render/deploy Actions (the main path of this lesson).
  • Already have a Kubernetes platform, or need the CRD ecosystem: EKS (the cluster is maintained by a platform team; the application team's CI only gets permissions for a specific namespace).
  • Event-driven, intermittent traffic, single execution ≤ 15 min: Lambda (images up to 10 GB).

Comparison with Azure (Lesson 3)

NeedAzureAWS
Managed containers, least operationsContainer AppsECS Express Mode / ECS on Fargate
Managed KubernetesAKSEKS
FunctionsFunctionsLambda
Image registryACRECR
CI identityEntra federated credentialIAM OIDC provider + role
Common misconceptions (1) 'Deploying to EKS only needs IAM permissions': IAM only lets you call eks:DescribeCluster; whether you can kubectl apply depends on EKS access entries (or the legacy aws-auth ConfigMap). (2) 'App Runner has been shut down': it has not; it only no longer accepts new customers. (3) 'Express Mode is another compute service': it is just a quick way to create and manage ECS, and the underlying service is still a Fargate service.

Architecture diagram: the same identity chain, four destinations

GitHub Actions run permissions: id-token: writeenvironment: dev / produbuntu-latest GitHub-hosted runnerBuild image → push → deploy JWT AWS STS AssumeRoleWithWebIdentityVerify iss / aud / sub→ temporary credentials (1h by default) ECRGetAuthorizationToken · push ECS (Fargate / Express)RegisterTaskDefinition · UpdateService EKSDescribeCluster → K8s API LambdaUpdateFunctionCode · UpdateAlias App RunnerNot accepting new customers → Express Mode Runtime identity (a separate matter) ECS: task execution role(pull images, write logs)ECS: task role (application)EKS: Pod Identity / IRSALambda: execution roleCI only needs iam:PassRole CI role ≠ runtime role: the CI role handles deployment, and the runtime role handles the application accessing AWS Keeping the two separate is the key to least privilege; CI hands the runtime role to ECS/Lambda through iam:PassRole
Figure 1-1: GitHub talks to STS only once; after that, all deployment APIs use the same temporary credentials

Decision flow

Event-driven,≤ 15 minutes? Lambda Yes No Need KubernetesAPI / CRD ecosystem? EKS Yes No Want to build everything with one call:ALB + TLS + scaling? ECS Express Mode Yes No ECS on FargateTask definition + service (the main path of this lesson) Do not choose App Runner for new projects (it does not accept new customers); existing App Runner services should move to Express Mode using DNS weighted records, following the official guide
Figure 1-2: simplified decision flow (real selection also has to consider team skills, compliance and existing platforms)

Interactive: deployment target selector

Answer 4 questions to see the recommended deployment target, the GitHub Action needed and the core permissions for the CI role. Each step shows the reasoning behind the decision.

Start again from the first question.
# Recommendation results will appear here

Core commands: survey the foundation of the account

CommandPurposeNotes
aws ec2 describe-vpcs --filters Name=is-default,Values=trueFind the default VPCThis lab uses the public subnets of the default VPC, avoiding NAT gateway charges
aws ecs create-cluster --cluster-name myapp-labCreate ECS clusterThe cluster itself is free; the first use automatically creates the ECS service-linked role
aws service-quotas get-service-quota --service-code fargate --quota-code L-3032A538Check Fargate on-demand vCPU quotaNew account quotas may be low; check before large deployments
aws apprunner list-servicesCheck whether you are an existing App Runner customerCalls to the create API from new accounts are rejected (follow the official statement)
aws ecs create-express-gateway-service …Express Mode creates the full stack in one stepRequires --execution-role-arn and --infrastructure-role-arn
export AWS_REGION=ca-central-1
VPC_ID=$(aws ec2 describe-vpcs --filters Name=is-default,Values=true --query 'Vpcs[0].VpcId' --output text)
SUBNETS=$(aws ec2 describe-subnets --filters Name=vpc-id,Values=$VPC_ID Name=default-for-az,Values=true \
  --query 'Subnets[].SubnetId' --output text | tr '\t' ',')
echo "VPC=$VPC_ID SUBNETS=$SUBNETS"
aws ecs create-cluster --cluster-name myapp-lab --tags key=course,value=gh-part4 \
  --query 'cluster.[clusterName,status]' --output text
VPC=vpc-0a1b2c3d SUBNETS=subnet-0aaa,subnet-0bbb,subnet-0ccc
myapp-lab   ACTIVE

GitHub usage of Express Mode (for reference)

The following snippet is adapted from the example in AWS's official App Runner migration guide (that example uses configure-aws-credentials@v5, this lesson upgrades everything to v6):

- uses: aws-actions/amazon-ecs-deploy-express-service@v1
  with:
    service-name: myapp-express
    image: ${{ steps.login-ecr.outputs.registry }}/myapp:sha-${{ github.sha }}
    execution-role-arn: arn:aws:iam::111122223333:role/ecsTaskExecutionRole
    infrastructure-role-arn: arn:aws:iam::111122223333:role/ecsInfrastructureRoleForExpressServices
    container-port: 5000
    health-check-path: /healthz
    min-task-count: 1
    max-task-count: 3

Common mistake: Forgetting that Express Mode creates an ALB (billed hourly); if you don't delete it after the lab, charges continue. Production use: Replaces App Runner's 'push and go live' experience.

Lab 1: Prepare the ECS cluster and network (about 3 min)

Create the cluster and log group
aws ecs create-cluster --cluster-name myapp-lab --tags key=course,value=gh-part4
aws logs create-log-group --log-group-name /ecs/myapp
aws logs put-retention-policy --log-group-name /ecs/myapp --retention-in-days 3

Logs are retained for 3 days so lab logs do not take up storage long-term.

Create a task security group (allow only your IP to access port 5000)
MYIP=$(curl -s https://checkip.amazonaws.com)
TASK_SG=$(aws ec2 create-security-group --group-name myapp-task-sg --description "myapp lab tasks" \
  --vpc-id $VPC_ID --query GroupId --output text)
aws ec2 authorize-security-group-ingress --group-id $TASK_SG --protocol tcp --port 5000 --cidr $MYIP/32
echo $TASK_SG
sg-0123456789abcdef0

To save money, this lab does not create an ALB; tasks get public IPs directly. This is only suitable for labs: production should use private subnets + ALB (see Docker Lesson 4).

Create the task execution role (the ECS agent uses it to pull images from ECR and write CloudWatch logs)
cat > ecs-tasks-trust.json <<'EOF'
{ "Version": "2012-10-17",
  "Statement": [{ "Effect": "Allow", "Principal": {"Service": "ecs-tasks.amazonaws.com"}, "Action": "sts:AssumeRole" }] }
EOF
aws iam create-role --role-name myappTaskExecutionRole --assume-role-policy-document file://ecs-tasks-trust.json
aws iam attach-role-policy --role-name myappTaskExecutionRole \
  --policy-arn arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy
Record the variables, which later modules and the capstone lab will use:
cat > ~/gh-part4.env <<EOF
export AWS_REGION=$AWS_REGION ACCOUNT_ID=$ACCOUNT_ID VPC_ID=$VPC_ID SUBNETS=$SUBNETS TASK_SG=$TASK_SG
export GH_OWNER=$GH_OWNER GH_REPO=myapp CLUSTER=myapp-lab
EOF
source ~/gh-part4.env
Verifyaws ecs describe-clusters --clusters myapp-lab --query 'clusters[0].status' returns "ACTIVE".

Case 1: App Runner fails to create a service in a new account

Problem: A team followed a two-year-old blog post to open a new AWS account for a new business line, planned to use App Runner, and service creation failed. Root cause: App Runner no longer accepts new customers. Fix: Switch to ECS Express Mode, with the GitHub side changed to amazon-ecs-deploy-express-service; existing App Runner services in older accounts migrate step by step using Route 53 weighted records of 10/25/50/75/100, as the official guide describes. Lesson: Check the service's 'availability change' announcement before choosing.

Case 2: Running only one API on EKS

Problem: To be 'technically advanced', a three-person team deployed a single Flask API to EKS; the monthly cluster and node costs far exceeded the application's value, and the CI also had to maintain kubeconfig and access entries. Fix: Moved to ECS on Fargate; CI role permissions were simplified from two sets (EKS + K8s RBAC) to a single set of ECS APIs. Limitation: Only if the company already has a shared EKS platform, where the application team needs just namespace-level access, is the cost justified.

Case 3: Lambda container image cold starts

Problem: A 2 GB image was packed directly into Lambda, and cold-start latency was noticeable. Fix: Use multi-stage builds to shrink the image, use the AWS-provided Lambda base images, and configure provisioned concurrency on the latency-sensitive alias. Limitation: Long-lived connections / WebSocket services and tasks running longer than 15 minutes are not suited to Lambda.

Common errors and fixes

An error occurred (AccessDeniedException) when calling the CreateService operation (App Runner)

Cause: The account is not an existing App Runner customer, or the identity lacks App Runner permissions. Fix: Use ECS Express Mode for new projects; confirm whether you really need App Runner.

Unable to assume the service linked role. Please verify that the ECS service linked role exists.

Cause: A new account is using ECS for the first time, and the service-linked role AWSServiceRoleForECS has not been created yet (usually created automatically, occasionally with a delay).

aws iam get-role --role-name AWSServiceRoleForECS || aws iam create-service-linked-role --aws-service-name ecs.amazonaws.com
You've reached the limit on the number of vCPUs you can run concurrently

Cause: Insufficient Fargate on-demand vCPU quota (common in new accounts). Fix: Check and request an increase with Service Quotas; reduce desiredCount during the lab.

InvalidParameterException: The specified log group does not exist.

Cause: The task definition references a CloudWatch log group that does not exist, and awslogs-create-group is not set. Fix:aws logs create-log-group --log-group-name /ecs/myapp (already created in step 1 of this lab).

Command-line questions
1. List the default subnet IDs in each availability zone of the default VPC, joined with commas.
aws ec2 describe-subnets --filters Name=vpc-id,Values=$VPC_ID Name=default-for-az,Values=true \
  --query 'Subnets[].SubnetId' --output text | tr '\t' ','
2. Confirm that the ECS service-linked role exists.
aws iam get-role --role-name AWSServiceRoleForECS --query Role.Arn --output text
Scenario analysis questions
A team has 5 microservices, all HTTP APIs, with steady traffic; nobody knows Kubernetes, and the boss wants push-and-it-goes-live like App Runner. What would you recommend? How would you handle it on the GitHub side?

Recommend ECS Express Mode (App Runner no longer accepts new customers). One Express service per microservice, which can share an ALB. GitHub side: OIDC → configure-aws-credentials@v6 → amazon-ecr-login@v2 → build and push → amazon-ecs-deploy-express-service@v1. When a service needs a finer-grained deployment strategy, switch it directly to a regular ECS service with the render/deploy Action; the underlying resources are the same.

Verified tutorial videos

▶
Deploying a Modern Application Stack to AWS Fargate with Amazon ECS - AWS Online Tech Talks — AWS Developers
English · Overall architecture of Fargate and ECS; useful background for Modules 1 and 4
▶
Serverless for container fans via Amazon ECS and AWS Lambda — Bret Fisher
English · Compares the trade-offs of running containers on ECS vs Lambda

Official documentation

Video storyboard script (about 60 seconds)

This courseware cannot generate video or MP3 directly; the storyboard and narration below can be given to a video tool.

Shot 1 · 0–15s
Visual: a GitHub icon sends a token flying toward an STS shield; behind the shield, four lines branch out: ECR, ECS, EKS, Lambda.
Narration: wherever you deploy, GitHub does one thing: it uses an OIDC token to exchange for temporary credentials.
Shot 2 · 15–35s
Visual: four cards flip over, showing each one's deployment API.
Narration: ECS means registering a task definition and then updating the service; EKS means first getting the cluster endpoint and then authorizing through access entries; Lambda means updating code, publishing a version and switching the alias.
Shot 3 · 35–60s
Visual: the App Runner card turns gray, and an arrow points to ECS Express Mode.
Narration: App Runner no longer accepts new customers. For new projects, choose ECS Express Mode, which sets up the Fargate service, load balancing and auto scaling in one API call.
or get a quiz score of ≥ 70%

Module 2 · OIDC federation: GitHub → IAM

05:00 – 14:00 · One account-level 'I trust this issuer', plus one role-level 'only trust this branch/environment of this repository'
9 minconfigure-aws-credentials v6.3.0Immutable subject since 2026-07-15★★★★★
Learning objectives
  • Create an IAM OIDC identity provider (URL https://token.actions.githubusercontent.com, audience sts.amazonaws.com), and explain why the thumbprint no longer needs to be maintained by hand.
  • Write a minimal trust policy with token.actions.githubusercontent.com:aud and :sub conditions, correctly distinguishing legacy format and immutable format subjects, and the four subject forms: branch / tag / environment / PR.
  • Be able to use aws-actions/configure-aws-credentials@v6 of role-to-assume,role-duration-seconds,role-session-name,role-chaining and know that session duration and role chaining are capped at 1 hour.
Prerequisites: Lesson 3 OIDC principles; an IAM role = trust policy + permissions policy. Importance:★★★★★ (all later modules depend on it)

What: three things

ObjectLocationPurposeKey value
IAM OIDC identity providerOne per AWS account (the same URL can only be created once within an account)Tells STS: JWTs signed by this issuer can be trusted by roles in this accountURL https://token.actions.githubusercontent.com; audience (client ID) sts.amazonaws.com
IAM role + trust policyOne per repository/environment (least privilege)Specifies which tokens may assume this rolePrincipal.Federated = provider ARN; Action = sts:AssumeRoleWithWebIdentity; Condition checks aud and sub
Workflow permissionsworkflow or job level permissionsAllows the runner to request an OIDC token from GitHubid-token: write (+ contents: read)

Why: what is better than access keys

  • No long-term secrets: GitHub stores no AWS keys at all; the only exposure is the temporary credentials within a single run (1 hour by default).
  • Fine-grained trust: the trust policy can be limited to the main branch of a certain repository or the prod environment of a certain repository; a fork or another repository gets a different sub, so STS rejects it.
  • Auditable: CloudTrail's AssumeRoleWithWebIdentity event records the token's subject and other details; the role session name defaults to GitHubActions (which can be customized to the run ID), so AWS operations can be traced to a specific run.

How: seven steps of the token exchange

  1. the job declares id-token: write, so the runner gets ACTIONS_ID_TOKEN_REQUEST_URL and ACTIONS_ID_TOKEN_REQUEST_TOKEN environment variables.
  2. configure-aws-credentials Use them to request a JWT from the GitHub OIDC service; the audience defaults to sts.amazonaws.com.
  3. GitHub issues the JWT with iss=https://token.actions.githubusercontent.com as issuer, containing sub,aud,repository,repository_id,repository_owner_id,ref,environment,job_workflow_ref and other claims.
  4. The Action calls STS AssumeRoleWithWebIdentity (this call itself needs no AWS credentials), passing RoleArn, the token, session name and duration.
  5. STS uses iss to find this account's OIDC provider, fetches the JWKS to verify the signature and validity period, and checks whether the aud is in the provider's audience list.
  6. STS evaluates the trust policy conditions (aud,sub, and the GitHub-specific claim keys supported since 2026).
  7. After passing, it returns temporary credentials (ASIA… starting with AccessKeyId + SecretAccessKey + SessionToken + Expiration); the Action exports them as environment variables, masks them in the logs, and subsequent aws CLI / SDK commands use them automatically.

Is the thumbprint still needed? (verified)

IAM documentation states that AWS uses its trusted root CA library to verify the TLS certificate of the OIDC provider's JWKS endpoint; it falls back to thumbprint verification only when the IdP certificate was not issued by these trusted CAs, the certificate cannot be retrieved, or TLS 1.3 is required. configure-aws-credentials The README also states that 'if a thumbprint is specified, it will be ignored'. So for GitHub,there is no need to calculate and rotate the thumbprint by hand; the console fills in a value automatically when creating the provider, and the CLI's --thumbprint-list can be omitted.

Four forms of the subject (sub)

TriggerLegacy format (created before 2026-07-15 and not opted in)Immutable format (new repository / renamed / transferred / opted in)
Job references environmentrepo:octo-dev/myapp:environment:prodrepo:octo-dev@123456/myapp@789012:environment:prod
Push to a branch (no environment)repo:octo-dev/myapp:ref:refs/heads/mainrepo:octo-dev@123456/myapp@789012:ref:refs/heads/main
Push a tagrepo:octo-dev/myapp:ref:refs/tags/v1.2.0repo:octo-dev@123456/myapp@789012:ref:refs/tags/v1.2.0
pull_request event (no environment)repo:octo-dev/myapp:pull_requestrepo:octo-dev@123456/myapp@789012:pull_request
Most common pitfalls (1) Once a job has written environment: prod, the sub becomes …:environment:prod,no longer includes the branch; writing ref:refs/heads/main in the trust policy will be rejected. (2) After 2026-07-15, old repositories that are renamed or transferred also switch to the immutable format, and a trust policy that used to work will suddenly fail with Not authorized to perform sts:AssumeRoleWithWebIdentity. (3) The choice of @ as the separator is because it cannot appear in GitHub usernames or repository names; the point of the immutable format is that after a name is released it may be taken by someone else, while numeric IDs are never reused.

How to write conditions under the immutable format

  • Exact match (recommended): StringEquals → "repo:octo-dev@123456/myapp@789012:environment:prod".
  • Any branch of the same repository: StringLike → "repo:octo-dev@123456/myapp@789012:ref:refs/heads/*".
  • Accept both formats during the transition: StringLike 's value can be an array, for example listing both the legacy and immutable formats at once; after migration, remove the legacy format.
  • GitHub-specific claim keys (released by AWS on 2026-02-02): STS can now also check the trust policy for token.actions.githubusercontent.com:repository_id,:repository_owner_id,:environment,:ref,:job_workflow_ref,:actor_id and other keys; the IAM documentation recommends preferring immutable ID-type keys. This makes organization-level trust locked to the organization ID possible (Module 6).

Session duration and role chaining

ParameterDefault / rangeNotes
role-duration-secondsDefault 3600 (1 hour), can be set to 900–43200Cannot exceed the role's MaxSessionDuration (a role attribute, 1–12 hours, default 1 hour), otherwise STS reports The requested DurationSeconds exceeds the MaxSessionDuration set for this role
role-chaining: trueUse the credentials already in the current environment to call AssumeRole another roleIAM rule: role-chained sessions last at most 1 hour, so requests longer than 1 hour fail outright
role-session-nameDefault GitHubActionsrecommended to set to gh-${{ github.run_id }}, so runs can be correlated in CloudTrail
audienceDefault sts.amazonaws.comIf you change it, the OIDC provider's audience list and the aud condition in the trust policy must both be updated
Common misconceptions (1) 'The OIDC provider makes it secure': the provider only 'trusts tokens issued by GitHub',any GitHub repository can get such a token; the real boundary is the sub condition in the role trust policy; GitHub docs explicitly require evaluating sub. (2) 'Using ForAllValues:StringLike is more flexible' in an Allow statement: the README specifically warns that when a claim is missing or misspelled ForAllValues , it returns true, so use StringEquals/StringLike. (3) 'The role ARN is a secret': an ARN is not a credential, so it can be stored in repository/environment variables; there is no need to publicize it, though.

Sequence diagram: GitHub runner ↔ GitHub OIDC ↔ AWS STS ↔ AWS services

runner (job) GitHub OIDC issuer AWS STS + IAM ECR / ECS API ① GET $ACTIONS_ID_TOKEN_REQUEST_URL&audience=sts.amazonaws.com (2) JWT (iss, aud, sub, repository_id…, RS256 signed) ③ AssumeRoleWithWebIdentity(RoleArn, WebIdentityToken, RoleSessionName, DurationSeconds) (4) Fetch /.well-known/openid-configuration and JWKS (cached) (5) Find the provider with the same URL in the accountVerify signature · exp · aud ∈ audience list(6) Evaluate the trust policy conditionsaud = sts…, does sub match? ⑦ Credentials {AccessKeyId: ASIA…, SessionToken, Expiration: +1h} (8) SigV4-signed call: ecr:GetAuthorizationToken, ecs:UpdateService … (permissions are determined by the role's permissions policy) CloudTrail records AssumeRoleWithWebIdentity on the STS side, and calls made by assumed-role/ROLE/gh-RUNID on the service side
Figure 2-1: the OIDC token only flows between the runner and STS; business APIs are accessed only after temporary credentials are obtained

Anatomy of a trust policy

"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:octo-dev@123456/myapp@789012:environment:dev" }} Issued by: must be anOIDC provider already registered in this account For whom: aud must equal sts.amazonaws.com(matching the provider's audience list) Who: sub = which repository (including the numeric ID)which environment/branch/tag of it← the real security boundary
Figure 2-2: the three questions of a trust policy: who issues it, for whom, and who it applies to

Core animation: OIDC → STS AssumeRoleWithWebIdentity token exchange

Select a scenario, then click 'Next' or 'Autoplay'. The highlighted box shows the current handler; the terminal below shows the workflow log and the STS response. Failure scenarios stop at the step where the failure actually happens and show the original error text from the Action log.

runnerconfigure-aws-credentials@v6 GitHub OIDCtoken.actions.githubusercontent.com AWS STSProvider · signature verificationaud audience list Role trust policyaud / sub conditionsMaxSessionDuration ECR / ECSSigV4 call
Select a scenario to start.
$ # workflow log

Core commands and parameters

Command / inputPurposeKey parameters / notes
aws iam create-open-id-connect-providerCreate OIDC provider (once per account)--url https://token.actions.githubusercontent.com --client-id-list sts.amazonaws.com; --thumbprint-list can be omitted
aws iam list-open-id-connect-providersList existing providersIf it already exists, creating it again reports an error EntityAlreadyExists
aws iam create-role --assume-role-policy-documentCreate the CI role--max-session-duration 3600 (seconds, 1–12 hours)
aws iam update-assume-role-policyUpdate the trust policyUse it when changing the format (legacy → immutable); it takes effect within seconds
gh variable set AWS_ROLE_ARNWrite the role ARN to repository/environment variables--env dev Write to an environment-level variable
role-to-assumeARN of the role to assumeRequired for OIDC mode
aws-regionRegionRequired; this lesson uses ca-central-1
role-duration-seconds / role-session-name / role-chainingSession controlSee the principles page
mask-aws-account-idMask the account number in logsConsider enabling for public repositories
source ~/gh-part4.env
# 1) OIDC provider (skip if it already exists in the account)
aws iam list-open-id-connect-providers --query 'OpenIDConnectProviderList[].Arn' --output text | grep -q token.actions \
  || aws iam create-open-id-connect-provider \
       --url https://token.actions.githubusercontent.com \
       --client-id-list sts.amazonaws.com \
       --tags Key=course,Value=gh-part4
aws iam get-open-id-connect-provider \
  --open-id-connect-provider-arn arn:aws:iam::$ACCOUNT_ID:oidc-provider/token.actions.githubusercontent.com \
  --query '{aud:ClientIDList,thumb:ThumbprintList}'
{
    "aud": ["sts.amazonaws.com"],
    "thumb": ["…value filled in automatically by IAM, not relied on during verification…"]
}

Pin Actions by SHA (recommended for production)

git ls-remote https://github.com/aws-actions/configure-aws-credentials refs/tags/v6.3.0
git ls-remote https://github.com/aws-actions/amazon-ecr-login refs/tags/v2.1.7
e1253824e5c10ff9df46874f81ed3ec929e19cfd	refs/tags/v6.3.0
03f1aad4c6c7ffd436567f42f9384779290529bd	refs/tags/v2.1.7
- uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0
- uses: aws-actions/amazon-ecr-login@03f1aad4c6c7ffd436567f42f9384779290529bd # v2.1.7

How to verify: Dependabot can recognize SHAs with version comments and open upgrade PRs (Lesson 5). Common mistake: Copying a SHA from someone else's blog without checking it; it may point to an old version or even a tampered commit.

Lab 2: Establish OIDC trust and have the workflow prove who I am (about 8 min)

Create GitHub environments dev and prod (prod gets approval later in Module 6)
gh api -X PUT repos/$GH_OWNER/myapp/environments/dev
gh api -X PUT repos/$GH_OWNER/myapp/environments/prod
Print the real sub first: create in the myapp repository .github/workflows/whoami.yml (decode the claims only, without printing the token itself):
name: whoami
on: workflow_dispatch
permissions:
  id-token: write
  contents: read
jobs:
  claims:
    runs-on: ubuntu-latest
    environment: dev
    steps:
      - name: Show OIDC claims (not the token)
        run: |
          TOKEN=$(curl -sS -H "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \
            "$ACTIONS_ID_TOKEN_REQUEST_URL&audience=sts.amazonaws.com" | jq -r .value)
          echo "$TOKEN" | cut -d. -f2 | tr '_-' '/+' | base64 -d 2>/dev/null \
            | jq '{iss, aud, sub, repository, repository_id, repository_owner_id, environment, ref}'
git add .github/workflows/whoami.yml && git commit -m "ci: add whoami" && git push
gh workflow run whoami.yml && sleep 15
gh run view --log $(gh run list --workflow whoami.yml -L1 --json databaseId -q '.[0].databaseId') | grep -A12 '"iss"'
{
  "iss": "https://token.actions.githubusercontent.com",
  "aud": "sts.amazonaws.com",
  "sub": "repo:octo-dev@123456/myapp@789012:environment:dev",
  "repository": "octo-dev/myapp",
  "repository_id": "789012",
  "repository_owner_id": "123456",
  "environment": "dev",
  "ref": "refs/heads/main"
}

The base64url segments of a JWT may lack padding, so base64 -d sometimes reports 'invalid input' but still outputs the complete JSON; 2>/dev/null that is what this is for. Do not echo the $TOKEN itself: while it is valid, it can be used to exchange for credentials.

Create the dev role based on the printed sub
SUB_DEV="repo:octo-dev@123456/myapp@789012:environment:dev"   # ← replace with the sub from your log
cat > trust-dev.json <<EOF
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": { "Federated": "arn:aws:iam::$ACCOUNT_ID:oidc-provider/token.actions.githubusercontent.com" },
    "Action": "sts:AssumeRoleWithWebIdentity",
    "Condition": {
      "StringEquals": {
        "token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
        "token.actions.githubusercontent.com:sub": "$SUB_DEV"
      }
    }
  }]
}
EOF
aws iam create-role --role-name gh-myapp-dev-deploy \
  --assume-role-policy-document file://trust-dev.json --max-session-duration 3600 \
  --tags Key=course,Value=gh-part4 --query Role.Arn --output text
gh variable set AWS_ROLE_ARN --env dev --body "arn:aws:iam::$ACCOUNT_ID:role/gh-myapp-dev-deploy"
gh variable set AWS_REGION --body ca-central-1
arn:aws:iam::111122223333:role/gh-myapp-dev-deploy
✓ Created variable AWS_ROLE_ARN for octo-dev/myapp
✓ Created variable AWS_REGION for octo-dev/myapp
Append two steps to the end of whoami.yml to exchange for credentials
      - uses: aws-actions/configure-aws-credentials@v6
        with:
          role-to-assume: ${{ vars.AWS_ROLE_ARN }}
          aws-region: ${{ vars.AWS_REGION }}
          role-session-name: gh-${{ github.run_id }}
      - run: aws sts get-caller-identity
{
    "UserId": "AROAEXAMPLE:gh-9876543210",
    "Account": "111122223333",
    "Arn": "arn:aws:sts::111122223333:assumed-role/gh-myapp-dev-deploy/gh-9876543210"
}
Negative test: remove the job's environment: dev , run again, and observe the failure (the sub becomes …:ref:refs/heads/main), then restore it. This is the first troubleshooting case in Module 7.
Acceptance CloudTrail → Event history → Event name AssumeRoleWithWebIdentity, where you should see one success and one failure; the errorCode of the failed event is AccessDenied.

Case 1: All deployments fail after the repository is renamed

Problem: In August 2026, a team renamed web-legacy to storefront, and the next day all AWS deployments failed: Not authorized to perform sts:AssumeRoleWithWebIdentity. Root cause: Renaming after 2026-07-15 switches the repository to the immutable subject, while the trust policy still uses the legacy format (and the old name). Fix: Use the whoami workflow to print the new sub, and change the trust policy to an StringLike array that temporarily accepts both the new and old values; once confirmed, delete the old value. Prevention: Before renaming or transferring a repository, check all cloud trust relationships (AWS roles, Azure federated credentials, GCP workload identity pools).

Case 2: An overly broad wildcard lets 'any repository deploy to production'

Problem: A security audit found the production role's condition was StringLike sub = repo:my-org/*, so anyone in the organization could create a new repository, write a workflow and get production credentials. Fix: The production role trusts only repo:my-org@ORGID/infra-deploy@REPOID:environment:prod, and required approvals and branch restrictions are configured on the prod environment. Configuration: Use IAM Access Analyzer to check trust policies regularly.

Case 3: Long-running task credentials expire

Problem: A large data migration job ran for 90 minutes and began reporting ExpiredToken. Fix: Raise the role's MaxSessionDuration to 2 hours,role-duration-seconds: 7200; but if you use role-chaining, the limit is still 1 hour, so you can only split the task or re-run it midway configure-aws-credentials.

Common errors and fixes

Could not assume role with OIDC: Not authorized to perform sts:AssumeRoleWithWebIdentity

Cause: STS signature verification passed, but the trust policy conditions are not met. The most common cause is a sub mismatch (legacy vs immutable format, environment vs branch, letter case, repository rename); the next most common are a wrong aud condition or a wrong role ARN.

aws iam get-role --role-name gh-myapp-dev-deploy --query Role.AssumeRolePolicyDocument
# Compare with the sub printed by the whoami workflow

Fix: Make the condition exactly match the actual sub; during the transition, use a StringLike array.

Could not assume role with OIDC: No OpenIDConnect provider found in your account for https://token.actions.githubusercontent.com

Cause: There is no OIDC provider for this URL in the target account (the account where the role lives). This is most common in multi-account setups: the provider was created only in the dev account and forgotten in the prod account. IAM documentation states that the OIDC provider referenced by a trust policy must be in the same account as the role.

aws iam list-open-id-connect-providers
It looks like you might be trying to authenticate with OIDC. Did you mean to set the `id-token` permission?

Cause: The job does not have id-token: write, so the runner cannot get the token request URL; this is usually followed by Credentials could not be loaded, please check your action inputs: Could not load credentials from any providers.

Fix: Add permissions: { id-token: write, contents: read }. Note that runs from a fork pull_request cannot get the id-token: write (GitHub limits token permissions for fork PRs), so do not perform cloud deployments from fork PRs.

An error occurred (InvalidIdentityToken) when calling the AssumeRoleWithWebIdentity operation: Incorrect token audience

Cause: The token's aud is not in the OIDC provider's audience list (for example, a custom audience input was set, or the provider's audience was written as a different value). Fix:aws iam add-client-id-to-open-id-connect-provider or restore the default sts.amazonaws.com.

The requested DurationSeconds exceeds the MaxSessionDuration set for this role.

Fix: Lower role-duration-seconds, or aws iam update-role --role-name R --max-session-duration 7200. In a role chain, the duration cannot exceed 3600.

Command-line questions
1. Change the dev role's trust policy to accept both the legacy and immutable formats (transition period).
cat > trust-dual.json <<EOF
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
 "Principal":{"Federated":"arn:aws:iam::$ACCOUNT_ID:oidc-provider/token.actions.githubusercontent.com"},
 "Action":"sts:AssumeRoleWithWebIdentity",
 "Condition":{"StringEquals":{"token.actions.githubusercontent.com:aud":"sts.amazonaws.com"},
  "StringLike":{"token.actions.githubusercontent.com:sub":[
    "repo:octo-dev/myapp:environment:dev",
    "repo:octo-dev@123456/myapp@789012:environment:dev"]}}}]}
EOF
aws iam update-assume-role-policy --role-name gh-myapp-dev-deploy --policy-document file://trust-dual.json
2. In CloudTrail, check the results of the last 10 AssumeRoleWithWebIdentity calls.
aws cloudtrail lookup-events --lookup-attributes AttributeKey=EventName,AttributeValue=AssumeRoleWithWebIdentity \
  --max-results 10 --query 'Events[].[EventTime,Username]' --output table
Scenario analysis questions
A colleague suggests: 'To keep it simple, trust repo:my-org/* for the production role, then decide the branch in the workflow.' Evaluate this.

Not acceptable. Workflow files are controlled by whoever has write access to the repository; any repository in the organization could write a workflow that makes no decisions and get production credentials. The constraint must live on the AWS side (the trust policy's sub pinned to the repository ID + environment:prod), combined with GitHub-side environment approvals and deployment branch restrictions. You can also lock to immutable IDs with the repository_id/repository_owner_id condition keys supported since 2026.

Tutorial videos

No GitHub → AWS OIDC video was found that was verified via oEmbed and matches the 2026 immutable subject format. The following are verified related videos; for the specific configuration, follow this lesson and the official documentation.

▶
GitHub Actions Tutorial - Basic Concepts and CI/CD Pipeline with Docker — TechWorld with Nana
English · Basic review of Actions; the video uses the older approach of long-term credentials, which this lesson replaces with OIDC

Official documentation

Video storyboard script (about 90 seconds)

Shot 1 · 0–20s
Visual: in GitHub Secrets, a key called AWS_ACCESS_KEY_ID is crossed out and replaced with a ticket that expires.
Narration: no keys are stored; each run gets a short-lived ticket. The ticket is issued by GitHub and is valid for a very short time.
Shot 2 · 20–45s
Visual: the JWT expands into three lines, iss, aud and sub; the @123456 and @789012 in sub flash.
Narration: the most important part is sub. After July 15, 2026, new repositories' sub includes immutable numeric IDs, so even if a name is taken, it cannot be impersonated.
Shot 3 · 45–70s
Visual: the STS shield checks off in turn: issuer, signature, audience, trust policy conditions.
Narration: STS first confirms the issuer is registered in the account, then verifies the signature and audience, and finally compares each condition of the role's trust policy.
Shot 4 · 70–90s
Visual: temporary credentials starting with ASIA are returned, a one-hour countdown begins, and then the image is pushed and the service is updated.
Narration: once approved, you get one hour of temporary credentials; pushing images and updating services both use them. When time runs out, they expire automatically.
or get a quiz score of ≥ 70%

Module 3 · Build and push to ECR

14:00 – 21:00 · Tags are for people, digests are for machines; immutable tags make sure 'this version' always points to the same image
7 minamazon-ecr-login v2.1.7IMMUTABLE · scan on push★★★★
Learning objectives
  • Write a minimal ECR permission for the CI role that can only push to the myapp repository, and log in with aws-actions/amazon-ecr-login@v2 .
  • Understand IMMUTABLE the impact of tags on CI (re-running the same commit fails to push), and design an sha-<commit> tag strategy.
  • From docker/build-push-action get the digest, and use the digest in later deployments; repo@sha256:… read the scan results at push time.
Prerequisites: The ECR section of Docker Lesson 4 (repositories, lifecycle policies, scanning). Importance:★★★★

What amazon-ecr-login does

It calls ecr:GetAuthorizationToken to get a Docker login token (valid for 12 hours), then runs docker login to <account>.dkr.ecr.<region>.amazonaws.com, and passes the registry address to later steps via the output registry . Main inputs:

InputDefaultDescription
registriesCurrent accountComma-separated account IDs, used to log in to multiple (including cross-account) registries
registry-typeprivatepublic When logging in to ECR Public (public.ecr.aws, only fetches the token in us-east-1)
mask-passwordtrue (since v2)When true, the docker password is not output; set to false only when the password must be passed to a later job
skip-logoutfalseLogs out by default at the end of the job

Why: immutable tags + digest

  • The risk of mutable tags: myapp:latest Today it points to A, tomorrow it is overwritten to point to B; rolling back to yesterday's latest simply does not exist. ECS resolves the tag to a digest at deploy time, but a new deployment or scale-out may pull a different image.
  • IMMUTABLE: with the repository configured, pushing an existing tag returns ImageTagAlreadyExistsException; sha-3f2a9c1 once it exists, it always refers to the same content. You can also use IMMUTABLE_WITH_EXCLUSION to keep a few tags (such as latest) mutable.
  • digest: sha256:… is the hash of the image manifest content; as long as the content does not change, the digest does not change. When deploying, write …/myapp@sha256:… is the strongest guarantee, and it also maps cleanly to artifact attestations (Lesson 5).

How: the push flow in CI

  1. configure-aws-credentials Get temporary credentials.
  2. amazon-ecr-login Log in with registry, which outputs
  3. (optional) First aws ecr describe-images to check whether sha-${GITHUB_SHA} already exists; if it does, skip the build to avoid hitting IMMUTABLE on a re-run.
  4. docker/build-push-action Build and push, output digest.
  5. Scanning: basic scanning on push (native AWS technology, OS package CVEs) or enhanced scanning (Amazon Inspector, OS + language packages, continuous scanning); read the results with aws ecr describe-image-scan-findings or wait image-scan-complete , and decide whether to block based on severity.
  6. Pass registry/myapp@digest to the deployment job as a job output.

Minimum-privilege policy (CI role)

ActionResourceWhy
ecr:GetAuthorizationToken*This API does not support resource-level permissions
ecr:BatchCheckLayerAvailability,InitiateLayerUpload,UploadLayerPart,CompleteLayerUpload,PutImagerepository ARNPush image layers and manifests
ecr:BatchGetImage,GetDownloadUrlForLayer,DescribeImages,DescribeImageScanFindingsrepository ARNPull cache, check whether it exists, read scan results

Comparison with Azure (Lesson 3)

ACRECR
Loginaz acr login (after azure/login)amazon-ecr-login@v2
Tag protectionLock a single tag/manifest (az acr repository update --write-enabled false)Repository-level IMMUTABLE (with optional exception filters)
ScanningDefender for ContainersBasic scanning / Inspector enhanced scanning
Common misconceptions (1) 'IMMUTABLE makes re-running the workflow fail, so don't turn it on': the right approach is to check whether the tag exists first and then decide whether to build. (2) 'A successful push means it is secure': scanning is asynchronous, so results may not be ready when the push completes. (3) 'The ECR login token expires quickly': the authorization token is valid for 12 hours, longer than an STS session (1 hour by default); login failures are usually caused by STS credentials or permissions.

From commit to digest

commit 3f2a9c1push main STS temporary credentialsgh-myapp-dev-deploy(Module 2) amazon-ecr-loginGetAuthorizationToken→ docker login (12h) build-push-actiontag sha-3f2a9c1…output: digest ECR myappIMMUTABLEscanOnPushLifecycle policy Three ways to reference the same image 111122223333.dkr.ecr.ca-central-1.amazonaws.com/myapp:sha-3f2a9c1e… ← immutable tag (human-readable, traceable to the commit) 111122223333.dkr.ecr.ca-central-1.amazonaws.com/myapp@sha256:9b1c…e04 ← digest (for deployment, content-addressed) myapp:latest ← do not use for deployment (this lab's repository does not push latest)
Figure 3-1: the complete path for CI pushing an image

Interactive simulation: mutable tag vs immutable tag vs digest

Click the buttons to simulate pushing and deploying. Watch how the repository's tag → digest mapping changes, and which image the ECS task actually runs.

ECR repository myapp
ECS service myapp-dev is running
Select an action.
$ # CI log

Core commands and parameters

CommandPurposeNotes
aws ecr create-repository --image-tag-mutability IMMUTABLE --image-scanning-configuration scanOnPush=trueCreate an immutable repository that scans on pushThe encryption method cannot be changed after creation
aws ecr put-registry-scanning-configurationRegistry-level scanning rule (recommended)--scan-type BASIC|ENHANCED
aws ecr describe-images --image-ids imageTag=sha-…Check whether the tag existsReturns ImageNotFoundException
aws ecr wait image-scan-completewhen it does not exist; wait for the scan to completethen describe-image-scan-findings
aws ecr put-lifecycle-policyAutomatically clean up old imagesKeep only the most recent N sha-*
aws iam put-role-policyAdd an inline policy to the CI roleThis lesson adds ECR permissions to the dev role
source ~/gh-part4.env
aws ecr create-repository --repository-name myapp \
  --image-tag-mutability IMMUTABLE \
  --image-scanning-configuration scanOnPush=true \
  --tags Key=course,Value=gh-part4 \
  --query 'repository.[repositoryUri,imageTagMutability]' --output text
cat > lifecycle.json <<'EOF'
{"rules":[
 {"rulePriority":1,"description":"untagged after 1 day","selection":{"tagStatus":"untagged","countType":"sinceImagePushed","countUnit":"days","countNumber":1},"action":{"type":"expire"}},
 {"rulePriority":2,"description":"keep last 20 sha-*","selection":{"tagStatus":"tagged","tagPrefixList":["sha-"],"countType":"imageCountMoreThan","countNumber":20},"action":{"type":"expire"}}
]}
EOF
aws ecr put-lifecycle-policy --repository-name myapp --lifecycle-policy-text file://lifecycle.json >/dev/null
111122223333.dkr.ecr.ca-central-1.amazonaws.com/myapp   IMMUTABLE

Add ECR push permissions to the dev role

cat > ecr-push.json <<EOF
{"Version":"2012-10-17","Statement":[
 {"Sid":"Auth","Effect":"Allow","Action":"ecr:GetAuthorizationToken","Resource":"*"},
 {"Sid":"PushPullMyapp","Effect":"Allow","Action":[
   "ecr:BatchCheckLayerAvailability","ecr:InitiateLayerUpload","ecr:UploadLayerPart",
   "ecr:CompleteLayerUpload","ecr:PutImage","ecr:BatchGetImage","ecr:GetDownloadUrlForLayer",
   "ecr:DescribeImages","ecr:DescribeImageScanFindings"],
  "Resource":"arn:aws:ecr:$AWS_REGION:$ACCOUNT_ID:repository/myapp"}]}
EOF
aws iam put-role-policy --role-name gh-myapp-dev-deploy --policy-name ecr-push-myapp --policy-document file://ecr-push.json

Lab 3: CI build and push immutable image (about 6 min)

Create the repository and permissions: Run the two commands from the "Commands" tab.
Create the .github/workflows/deploy.yml build job (Module 4 appends the deploy job to the same file):
name: deploy
on:
  push:
    branches: [main]
  workflow_dispatch:
permissions:
  id-token: write
  contents: read
concurrency:
  group: deploy-${{ github.ref }}
  cancel-in-progress: false
env:
  ECR_REPOSITORY: myapp
jobs:
  build:
    runs-on: ubuntu-latest
    environment: dev            # push the image with the dev role (sub = …:environment:dev)
    outputs:
      image: ${{ steps.out.outputs.image }}
    steps:
      - uses: actions/checkout@v7
      - uses: aws-actions/configure-aws-credentials@v6
        with:
          role-to-assume: ${{ vars.AWS_ROLE_ARN }}
          aws-region: ${{ vars.AWS_REGION }}
          role-session-name: gh-${{ github.run_id }}
      - id: ecr
        uses: aws-actions/amazon-ecr-login@v2
      - id: exists
        run: |
          if aws ecr describe-images --repository-name $ECR_REPOSITORY \
               --image-ids imageTag=sha-${GITHUB_SHA} --query 'imageDetails[0].imageDigest' --output text 2>/dev/null > digest.txt; then
            echo "digest=$(cat digest.txt)" >> "$GITHUB_OUTPUT"; echo "found=true" >> "$GITHUB_OUTPUT"
          else
            echo "found=false" >> "$GITHUB_OUTPUT"
          fi
      - uses: docker/setup-buildx-action@v4
        if: steps.exists.outputs.found == 'false'
      - id: build
        if: steps.exists.outputs.found == 'false'
        uses: docker/build-push-action@v7
        with:
          context: .
          push: true
          provenance: false
          tags: ${{ steps.ecr.outputs.registry }}/${{ env.ECR_REPOSITORY }}:sha-${{ github.sha }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
      - id: out
        env:
          REGISTRY: ${{ steps.ecr.outputs.registry }}
          DIGEST: ${{ steps.build.outputs.digest || steps.exists.outputs.digest }}
        run: echo "image=$REGISTRY/$ECR_REPOSITORY@$DIGEST" >> "$GITHUB_OUTPUT"
      - name: Scan gate (CRITICAL = fail)
        run: |
          aws ecr wait image-scan-complete --repository-name $ECR_REPOSITORY --image-id imageTag=sha-${GITHUB_SHA}
          aws ecr describe-image-scan-findings --repository-name $ECR_REPOSITORY --image-id imageTag=sha-${GITHUB_SHA} \
            --query 'imageScanFindings.findingSeverityCounts' --output json | tee counts.json
          test "$(jq -r '.CRITICAL // 0' counts.json)" -eq 0

provenance: false Make buildx push only a single image manifest so it is easy to match in the ECR console and scan results; if you need SLSA provenance, use the attestations from Lesson 5 instead. concurrency Prevents deployments from two pushes from interleaving.

Push and observe
git add .github/workflows/deploy.yml && git commit -m "ci: build and push to ECR" && git push
gh run watch $(gh run list --workflow deploy.yml -L1 --json databaseId -q '.[0].databaseId')
aws ecr describe-images --repository-name myapp \
  --query 'imageDetails[].[imageTags[0],imageDigest,imageScanStatus.status]' --output table
---------------------------------------------------------------------------------
|                                DescribeImages                                 |
+--------------------------------------+-------------------------+--------------+
|  sha-3f2a9c1e5b…                     |  sha256:9b1c…e04         |  COMPLETE    |
+--------------------------------------+-------------------------+--------------+
Re-run to verify idempotency: On the Actions page, click "Re-run all jobs" for the same run. The build job should show "found=true", skip the build, and output the same digest; you will not see ImageTagAlreadyExistsException.

Case 1: rollback to "last week's latest" fails

Problem: A service had been deploying :latest, and after an incident, when we tried to roll back, we found the old image had been overwritten, and the lifecycle policy had deleted it as an untagged image. Fix: Set the repository to IMMUTABLE and use tags of the form sha-<commit>, deploy by digest, and have the lifecycle policy clean up only untagged images and images beyond the latest N of sha-*. Result: Rollback = redeploy the task definition revision with the old digest.

Case 2: scan gate false positive blocks releases

Problem: A base image had a CRITICAL CVE with no fix yet, and all releases were blocked. Fix: The gate only blocks CRITICAL findings that have an available fix (enhanced scanning results have a fixAvailable field), add a time-limited exception process, and switch to a smaller base image. Limitation: Basic and enhanced scanning use different fields, so write the gate script for the scan type you actually use.

Case 3: share one ECR across multiple accounts

Problem: The dev, stage, and prod accounts each have their own ECR, and the same image is pushed three times; the digest matches, but governance is complex. Fix: Create one ECR in a shared services account, and have the repository policy allow each environment account's task execution role to pull; alternatively, use ECR cross-account replication. CI pushes only once to the shared account, and each environment deploys by digest (Module 6).

Common errors and fixes

tag invalid: The image tag 'sha-3f2a…' already exists in the 'myapp' repository and cannot be overwritten because the repository is immutable.

Cause: The tag already exists in an IMMUTABLE repository (usually because the workflow was re-run). Fix: First, run describe-images to check before you build (see the lab); do not switch back to MUTABLE just to make the push go through.

User: arn:aws:sts::111122223333:assumed-role/gh-myapp-dev-deploy/gh-… is not authorized to perform: ecr:InitiateLayerUpload on resource: arn:aws:ecr:ca-central-1:111122223333:repository/myapp

Cause: The role's permission policy is missing the push actions, or the region or repository name in Resource is wrong.

aws iam get-role-policy --role-name gh-myapp-dev-deploy --policy-name ecr-push-myapp
name unknown: The repository with name 'myapp' does not exist in the registry with id '111122223333'

Cause: The repository was not created, was created in a different region, or aws-region does not match the repository's region. Fix:aws ecr describe-repositories --region ca-central-1.

Error: Could not login to registry 111122223333.dkr.ecr.ca-central-1.amazonaws.com / not authorized to perform: ecr:GetAuthorizationToken

Cause: Missing ecr:GetAuthorizationToken (Resource must be *), or the previous configure-aws-credentials step actually failed. Fix: Check the previous step's logs first, and check the policy.

Waiter ImageScanComplete failed: Waiter encountered a terminal failure state / ScanNotFoundException

Cause: Scan on push is not enabled for the repository, the registry has switched to enhanced scanning (results are in Inspector, with different fields), or the image type is not supported. Fix:aws ecr get-registry-scanning-configuration Confirm the scan type.

Command-line exercises
1. Find the digest for tag sha-3f2a9c1.
aws ecr describe-images --repository-name myapp --image-ids imageTag=sha-3f2a9c1 \
  --query 'imageDetails[0].imageDigest' --output text
2. List the count of each severity level in the latest scan results for the myapp image.
aws ecr describe-image-scan-findings --repository-name myapp --image-id imageTag=sha-3f2a9c1 \
  --query 'imageScanFindings.findingSeverityCounts'
Scenario analysis
The team wants to update latest on every push so developers can pull it locally, while production needs immutable images. How would you design this?

Set the repository to IMMUTABLE_WITH_EXCLUSION, with an exception filter that allows only latest; CI pushes both sha-… and latest, and deployments always use the digest (or the digest resolved from the sha tag). Alternatively, put dev images in a separate MUTABLE repository.

Verified instructional videos

▶
Amazon Elastic Container Registry (Amazon ECR) Explained | Amazon Web Services — Amazon Web Services
English · ECR concepts overview
▶
AWS re:Invent 2023 - Dive deep into Amazon ECR (CON405) — AWS Events
English · Deep dive: replication, scanning, pull-through cache, and performance

Official documentation

Video storyboard (about 60 seconds)

Shot 1 · 0–20s
Visual: the latest tag is like a sticky note, torn off and stuck onto each new image.
Narration: a mutable tag is like a sticky note anyone can move. When you roll back, you cannot find yesterday's.
Shot 2 · 20–40s
Visual: an IMMUTABLE lock icon, and the second push is stopped by a red X.
Narration: in an immutable repository, a tag can point to only one image; when you re-run the pipeline, check first, then build.
Shot 3 · 40–60s
Visual: a sha256 fingerprint stamp is applied to the task definition.
Narration: deploy by digest. If the content does not change, the fingerprint does not change, so scan results, attestations, and running tasks can all be matched one to one.
or score ≥ 70% on the quiz

Module 4 · Deploy to ECS on Fargate

21:00 – 30:00 · Render the task definition → register a new revision → update the service → wait for stability → verify that it is really stable on the new revision
9 minrender v1.9.1 · deploy v2.6.4 (node24)Circuit breaker auto-rollback★★★★★
Learning objectives
  • Use amazon-ecs-render-task-definition@v1 to write the digest into the task definition, and use amazon-ecs-deploy-task-definition@v2 to register a revision and update the service.
  • Write the minimum ECS deployment permissions for the CI role, and understand iam:PassRole why they are needed and how to use iam:PassedToService to tighten them.
  • Configure wait-for-service-stability, and understand the deployment circuit breaker's failure detection and auto-rollback, and know that "wait for stable succeeded" does not mean "new version is live"; learn about ECS native blue/green.
Prerequisites: Docker Lesson 4: task definitions, services, and rolling deployment parameters. Importance:★★★★★

What: the split of work between the two official Actions

ActionWhat it doesKey inputsOutputs
amazon-ecs-render-task-definition@v1Only edits the file, no API calls: Replaces the image in the specified container with the new value, producing a temporary task definition filetask-definition (file path; you can also use task-definition-family/-arn to read from AWS),container-name,image; also supports environment-variables,secrets,command,docker-labels, logging configuration, etc.task-definition (path of the rendered file)
amazon-ecs-deploy-task-definition@v2RegisterTaskDefinition → UpdateService → (optional) wait for stability; also supports CodeDeploy blue/green and run-task (e.g., database migrations)task-definition,service,cluster,wait-for-service-stability: true,wait-for-minutes (default 30, max 6 hours),force-new-deploymenttask-definition-arn,codedeploy-deployment-id,run-task-arn

Both Actions currently run on node24 (in action.yml, using: 'node24' verified 2026-11-15). When not providing service the deploy Action only registers the task definition and does not deploy. The Action will not create the service for you. The service must be created beforehand with the CLI or IaC.

Why: why "render" instead of handwriting the JSON every time

The rest of the task definition fields (CPU/memory, logging, health checks, execution role) are reviewed by people and versioned in the repository; only the image reference changes with each build. render ensures "only change image", preventing the CI script from accidentally changing other fields.

How: state changes during one ECS deployment

  1. Register a new revision myapp:N+1 (image = …/myapp@sha256:…).
  2. UpdateService Create a new deployment (PRIMARY), and the old one becomes ACTIVE; rolloutState = IN_PROGRESS.
  3. Start new tasks based on maximumPercent/minimumHealthyPercent ; once new tasks pass container health checks (and ALB health checks, if any), stop the old tasks.
  4. When all replacements are complete → rolloutState = COMPLETED, and the event has reached a steady state.
  5. Circuit breaker: if new tasks repeatedly fail to reach RUNNING or fail health checks, once the failure count reaches the threshold, rolloutState = FAILED; with rollback=true enabled, the last successful service revision is deployed automatically. The threshold is half of the desired task count, minimum 3 and maximum 200 (see the official documentation).
Key detail: waiting for stability is not the same as the new version succeeding After a circuit breaker rollback, the service reaches a steady state again on the old revision. Therefore, in addition to wait-for-service-stability, the workflow should also check that the PRIMARY deployment's taskDefinition value matches the value this run output as task-definition-arn, and rolloutState is COMPLETED (see the "Verify" step in the lab).

Minimum ECS permissions for the CI role

ActionResourceNotes
ecs:RegisterTaskDefinition,ecs:DescribeTaskDefinition*No revision ARN exists at registration time, and the official README also uses *
ecs:UpdateService,ecs:DescribeServicesarn:aws:ecs:REGION:ACCT:service/myapp-lab/myapp-devCan only deploy this one service
iam:PassRoleARN of the task execution role (and task role)Hands the role over to ECS; use the condition iam:PassedToService = ecs-tasks.amazonaws.com to prevent it from being used for other services

Blue/green and progressive rollout

ApproachMechanismGitHub side
Rolling + circuit breaker (this lesson)ECS deployment controller replaces tasks in batches; automatic rollback on failuredeploy Action + verification step
ECS native blue/green (deploymentConfiguration.strategy = BLUE_GREEN)Old and new revisions run at the same time; traffic is shifted through ALB/NLB listener rules, Service Connect, or VPC Lattice; bake time during which the blue environment is kept for fast rollback; lifecycle hooks can invoke Lambda or pause waiting for ContinueServiceDeploymentThe same deploy Action (the service configuration determines the strategy); AWS has added linear and canary strategies to the ECS deployment controller; check the official documentation for the exact fields
CodeDeploy blue/green (CODE_DEPLOY controller)Traditional approach; requires an AppSpec and a deployment groupthe deploy Action's codedeploy-* inputs
Common misconceptions (1) "The deploy Action creates the service" - no. (2) "Writing :sha-xxx tags in the task definition is the same as writing the digest" - ECS resolves tags to a digest by default and keeps versions consistent, but writing the digest directly makes the task definition itself auditable and independent of resolution. (3) "The circuit breaker can detect business errors" - it only checks whether tasks can start and pass health checks; business metric anomalies require CloudWatch alarms to trigger rollback (deployment alarms can be used together with the circuit breaker).

Workflow's two jobs and ECS internal states

job: buildECR push (Module 3)outputs.image =…/myapp@sha256:9b1c… job: deploy-devneeds: build · environment: devrender → deploy → verify(OIDC exchanges credentials again) ECS APIRegisterTaskDefinition → :7UpdateService(myapp-dev, :7)DescribeServices polling job: deploy-prodenvironment: prodRequired approval (Module 6)same digest ECS service myapp-dev (desired=2, min 100%, max 200%, circuitBreaker rollback=true) deployment PRIMARY :7rolloutState IN_PROGRESS New task RUNNING + HEALTHYOld task :6 stopped COMPLETEDsteady state ✓ New tasks repeatedly fail ≥ thresholdrolloutState FAILED Auto-rollback to :6 → service stable on the old revision⚠ the waiter may "succeed"; you must verify that PRIMARY is :7
Figure 4-1 build → deploy-dev → deploy-prod; success and circuit-breaker rollback paths inside ECS

Animation: rolling deployment and deployment circuit breaker

desired=2, maximumPercent=200, minimumHealthyPercent=100. Choose "healthy image" or "bad image (exits on start)", and observe task replacement, failure count, circuit breaking and rollback, as well as the results of the deploy and verify steps in the workflow.

Tasks
Deployment status
Service currently running revision :6 (2 tasks).
$ aws ecs describe-services …

Core commands and parameters

CommandPurposeNotes
aws ecs create-service … --deployment-configuration "…deploymentCircuitBreaker={enable=true,rollback=true}"Create the service onceUpdated by the workflow afterward
aws ecs describe-services --query 'services[0].deployments'Check PRIMARY/ACTIVE and rolloutStateCircuit breaker info is in rolloutStateReason
aws ecs list-service-deployments / describe-service-deploymentsService deployment history (including rollback records)More structured than events
aws ecs wait services-stableWait for stabilitythe deploy Action uses the same kind of waiter internally
aws ecs update-service --task-definition myapp:6Manual rollbackJust specify the old revision
aws ecs describe-tasks --query 'tasks[].stoppedReason'See why tasks stoppedFirst list-tasks --desired-status STOPPED

Add ECS deployment permissions to the dev role

source ~/gh-part4.env
cat > ecs-deploy.json <<EOF
{"Version":"2012-10-17","Statement":[
 {"Sid":"TaskDef","Effect":"Allow","Action":["ecs:RegisterTaskDefinition","ecs:DescribeTaskDefinition"],"Resource":"*"},
 {"Sid":"Service","Effect":"Allow","Action":["ecs:UpdateService","ecs:DescribeServices"],
  "Resource":"arn:aws:ecs:$AWS_REGION:$ACCOUNT_ID:service/myapp-lab/myapp-dev"},
 {"Sid":"PassExecRole","Effect":"Allow","Action":"iam:PassRole",
  "Resource":"arn:aws:iam::$ACCOUNT_ID:role/myappTaskExecutionRole",
  "Condition":{"StringEquals":{"iam:PassedToService":"ecs-tasks.amazonaws.com"}}}]}
EOF
aws iam put-role-policy --role-name gh-myapp-dev-deploy --policy-name ecs-deploy-myapp-dev --policy-document file://ecs-deploy.json

Task definition template in the repository .aws/task-definition.json

mkdir -p .aws
cat > .aws/task-definition.json <<EOF
{
  "family": "myapp",
  "requiresCompatibilities": ["FARGATE"],
  "networkMode": "awsvpc",
  "cpu": "256",
  "memory": "512",
  "runtimePlatform": {"cpuArchitecture": "X86_64", "operatingSystemFamily": "LINUX"},
  "executionRoleArn": "arn:aws:iam::$ACCOUNT_ID:role/myappTaskExecutionRole",
  "containerDefinitions": [{
    "name": "web",
    "image": "PLACEHOLDER",
    "essential": true,
    "portMappings": [{"containerPort": 5000, "protocol": "tcp"}],
    "healthCheck": {
      "command": ["CMD-SHELL", "python -c \"import urllib.request; urllib.request.urlopen('http://localhost:5000/healthz', timeout=3)\" || exit 1"],
      "interval": 15, "timeout": 5, "retries": 3, "startPeriod": 20
    },
    "logConfiguration": {"logDriver": "awslogs", "options": {
      "awslogs-group": "/ecs/myapp", "awslogs-region": "$AWS_REGION", "awslogs-stream-prefix": "myapp"}}
  }]
}
EOF

Common mistake: Leaving "image" empty causes registration to fail; use PLACEHOLDER as a placeholder, which render replaces. cpu/memory must be a combination supported by Fargate (256/512 is the smallest size).

Lab 4: deploy myapp-dev with a workflow and verify it (about 8 min)

First, deploy manually once (so the service exists; use the digest pushed in Module 3 for the image)
source ~/gh-part4.env
DIGEST=$(aws ecr describe-images --repository-name myapp --query 'sort_by(imageDetails,&imagePushedAt)[-1].imageDigest' --output text)
IMAGE=$ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com/myapp@$DIGEST
jq --arg img "$IMAGE" '.containerDefinitions[0].image=$img' .aws/task-definition.json > /tmp/td.json
aws ecs register-task-definition --cli-input-json file:///tmp/td.json --query 'taskDefinition.revision'
aws ecs create-service --cluster $CLUSTER --service-name myapp-dev --task-definition myapp \
  --desired-count 2 --launch-type FARGATE \
  --network-configuration "awsvpcConfiguration={subnets=[$SUBNETS],securityGroups=[$TASK_SG],assignPublicIp=ENABLED}" \
  --deployment-configuration "minimumHealthyPercent=100,maximumPercent=200,deploymentCircuitBreaker={enable=true,rollback=true}" \
  --propagate-tags SERVICE --tags key=course,value=gh-part4 --query 'service.status' --output text
aws ecs wait services-stable --cluster $CLUSTER --services myapp-dev && echo STABLE
1
ACTIVE
STABLE
Commit the task definition template and append a deploy-dev job at the end of deploy.yml
  deploy-dev:
    needs: build
    runs-on: ubuntu-latest
    environment: dev
    steps:
      - uses: actions/checkout@v7
      - uses: aws-actions/configure-aws-credentials@v6
        with:
          role-to-assume: ${{ vars.AWS_ROLE_ARN }}
          aws-region: ${{ vars.AWS_REGION }}
          role-session-name: gh-${{ github.run_id }}
      - id: render
        uses: aws-actions/amazon-ecs-render-task-definition@v1
        with:
          task-definition: .aws/task-definition.json
          container-name: web
          image: ${{ needs.build.outputs.image }}
      - id: deploy
        uses: aws-actions/amazon-ecs-deploy-task-definition@v2
        with:
          task-definition: ${{ steps.render.outputs.task-definition }}
          cluster: myapp-lab
          service: myapp-dev
          wait-for-service-stability: true
          wait-for-minutes: 10
      - name: Verify new revision is PRIMARY and COMPLETED
        env:
          WANT: ${{ steps.deploy.outputs.task-definition-arn }}
        run: |
          read -r GOT STATE <<< "$(aws ecs describe-services --cluster myapp-lab --services myapp-dev \
            --query 'services[0].deployments[?status==`PRIMARY`]|[0].[taskDefinition,rolloutState]' --output text)"
          echo "want=$WANT got=$GOT state=$STATE"
          test "$GOT" = "$WANT" && test "$STATE" = "COMPLETED"
git add .aws/task-definition.json .github/workflows/deploy.yml
git commit -m "ci: deploy to ECS dev" && git push
gh run watch $(gh run list --workflow deploy.yml -L1 --json databaseId -q '.[0].databaseId')
Deployment started. Watch this deployment's progress in the Amazon ECS console: https://ca-central-1.console.aws.amazon.com/ecs/v2/clusters/myapp-lab/services/myapp-dev/events?region=ca-central-1
Waiting for the service to become stable. …
want=arn:aws:ecs:ca-central-1:111122223333:task-definition/myapp:2 got=arn:aws:ecs:ca-central-1:111122223333:task-definition/myapp:2 state=COMPLETED
Access the application (the task has a public IP; the security group only allows your IP)
TASK=$(aws ecs list-tasks --cluster $CLUSTER --service-name myapp-dev --query 'taskArns[0]' --output text)
ENI=$(aws ecs describe-tasks --cluster $CLUSTER --tasks $TASK \
  --query "tasks[0].attachments[0].details[?name=='networkInterfaceId'].value" --output text)
IP=$(aws ec2 describe-network-interfaces --network-interface-ids $ENI --query 'NetworkInterfaces[0].Association.PublicIp' --output text)
curl -s http://$IP:5000/healthz; echo; curl -s http://$IP:5000/
ok
Hello from ip-172-31-…, hits=N/A (redis not connected)
Circuit breaker rollback drill Located inCapstone labstep 6: use workflow_dispatch to deploy a revision that exits on start, observe FAILED → automatic rollback, and how the Verify step turns the workflow red.

Case 1: pipeline is all green, but production is still on the old version

Problem: The new version exited immediately on startup because an environment variable was missing, and the circuit breaker rolled back to the old revision; the deploy step's wait for stability still finished, the pipeline showed success, and the team thought it had gone live. Fix: Add a Verify step that checks the PRIMARY revision and rolloutState; subscribe to EventBridge events for ECS service deployment state changes and push them to the chat tool. Lesson:"Stable" is a service-level state, not proof that "my version succeeded".

Case 2: overly broad PassRole leads to privilege escalation

Problem: The CI role policy included iam:PassRole on *. An attacker registered a task definition in a compromised PR workflow, passed the most privileged role in the account as the task role, and got admin credentials inside the container. Fix: Allow PassRole only for specific execution and task role ARNs, and add iam:PassedToService condition; run deployments only in protected environments.

Case 3: database migration and deployment order

Problem: The new version depends on a new table schema, and errors appeared after deployment. Fix: Use the deploy Action's run-task: true + wait-for-task-stopped: true to first run a migration using the same task definition (overriding the container with the migration command), then update the service once it succeeds. Limitation:run-task-container-overrides Do not accept untrusted input (action.yml has an explicit warning).

Common errors and fixes

User: …assumed-role/gh-myapp-dev-deploy/… is not authorized to perform: iam:PassRole on resource: arn:aws:iam::111122223333:role/myappTaskExecutionRole

Cause: Registering a task definition passes the execution role to ECS, which requires PassRole. Fix: Add PassRole as shown on the Commands tab (with the PassedToService condition); if the task definition also has taskRoleArn, include it as well.

ServiceNotFoundException: Service not found. / ClusterNotFoundException

Cause: The service does not exist (the Action does not create it), the cluster name is wrong, or the region is wrong. Fix:aws ecs describe-services --cluster myapp-lab --services myapp-dev.

Error: Resource is not in the state servicesStable / waiter timed out

Cause: New tasks never become stable (health checks fail, image pulls fail, or resources are insufficient), and the circuit breaker is not enabled or has not reached its threshold yet.

aws ecs describe-services --cluster myapp-lab --services myapp-dev --query 'services[0].events[:5].message'
aws ecs list-tasks --cluster myapp-lab --service-name myapp-dev --desired-status STOPPED
aws ecs describe-tasks --cluster myapp-lab --tasks TASK_ARN --query 'tasks[0].[stoppedReason,containers[0].reason]'
CannotPullContainerError: … failed to resolve ref … : not found

Cause: The image URI or digest is wrong, or the execution role lacks ECR pull permission (AmazonECSTaskExecutionRolePolicy), or the task's subnet cannot reach ECR (no public IP and no NAT/VPC endpoint).

(service myapp-dev) deployment ecs-svc/… deployment failed: tasks failed to start. / rolloutState FAILED

Cause: The circuit breaker was triggered. Check rolloutStateReason and the stopped tasks' stoppedReason (e.g., Essential container in task exited). After fixing, redeploy.

Command-line exercises
1. Check the revision and rolloutState of the current PRIMARY deployment for myapp-dev.
aws ecs describe-services --cluster myapp-lab --services myapp-dev \
  --query 'services[0].deployments[?status==`PRIMARY`]|[0].[taskDefinition,rolloutState,rolloutStateReason]' --output text
2. Manually roll back to revision 1.
aws ecs update-service --cluster myapp-lab --service myapp-dev --task-definition myapp:1
aws ecs wait services-stable --cluster myapp-lab --services myapp-dev
Scenario analysis
The team requires "prod deployments must first send 10% of traffic to the new version and observe it for 10 minutes". How would you implement this with the workflow structure in this lesson?

Change the prod service to use ECS native progressive strategies with ALB (canary/linear, or BLUE_GREEN + bake time + pause hooks); the workflow still only calls the deploy Action; configure deployment failure detection and automatic rollback on CloudWatch alarms. On the GitHub side, keep the required approval for the prod environment and the Verify step, and increase wait-for-minutes so it covers the observation period.

Verified instructional videos

▶
Circuit Breakers for Amazon ECS — Containers from the Couch
English · Deployment circuit breaker: how it works, with a demo
▶
The Complete Guide to ECS Blue/Green Deployments on AWS — AWS Developers
English · ECS native blue/green deployment
▶
AWS re:Invent 2025 - Deep Dive: ECS Managed Instances & Blue/Green for Resilient Services (CNS416) — AWS Events
English · Deep dive into blue/green and lifecycle hooks

Official documentation

Video storyboard (about 75 seconds)

Shot 1 · 0–20s
Visual: the image line in the task definition JSON is highlighted and replaced with the digest.
Narration: the render step does one thing: write the new image into the task definition, leaving the other fields as reviewed.
Shot 2 · 20–45s
Visual: two blue new tasks appear beside two green old tasks; once healthy, the old tasks fade out.
Narration: the service starts new tasks first, up to the maximum percent, and stops the old tasks only after the new ones are healthy, so capacity never drops.
Shot 3 · 45–75s
Visual: new tasks keep turning red, with counter 1, 2, 3; the circuit breaker trips and the service goes back to the old version; the Verify step turns red in the pipeline.
Narration: when new tasks repeatedly fail, the circuit breaker rolls back automatically. Note that after rollback the service is still stable, so double-check that the running version is actually yours.
or score ≥ 70% on the quiz

Module 5 · Deploy to EKS and Lambda

30:00 – 38:00 · EKS: IAM authentication + access entry authorization; Lambda: publish immutable versions, shift traffic with alias weights
8 minEKS access entries · Helm 4Lambda versions + weighted aliases★★★★
Learning objectives
  • Explain the two layers of permissions for CI role access to EKS: IAM (eks:DescribeCluster) + EKS access entry (permissions inside Kubernetes), and associate a namespace-scoped access policy with it.
  • In the workflow, use aws eks update-kubeconfig to generate a kubeconfig, and use kubectl set image or helm upgrade --install --rollback-on-failure to deploy by digest.
  • Use aws-actions/aws-lambda-deploy@v1 or the CLI to update the Lambda code and publish a version, and use the alias additional version weights for a 10% canary and one-click rollback.
Prerequisites: K8s Lesson 7 (EKS access entries, Pod Identity); Lambda basics. Importance:★★★★

What: EKS's two gates

LayerWho decidesWhat CI needsError on failure
AWS APIIAMeks:DescribeCluster (update-kubeconfig uses it to get the endpoint and CA)AccessDeniedException … eks:DescribeCluster
Kubernetes APIEKS authentication (IAM identity → access entry) + Kubernetes authorization (access policy / RBAC)For the CI role, create an access entry, and associate a policy such as AmazonEKSEditPolicy (namespace scope)error: You must be logged in to the server (Unauthorized) (no access entry) or Forbidden (entry exists but permissions are insufficient)

The user in the kubeconfig uses the exec plugin aws eks get-token: it uses the current AWS credentials (the temporary credentials obtained via OIDC) to generate a presigned STS GetCallerIdentity request as a bearer token, and EKS uses it to identify the IAM identity —assumed-role sessions are mapped back to the role ARN, so the access entry uses the role ARN, not the session ARN. The cluster's authentication mode must be API or API_AND_CONFIG_MAP (the old aws-auth ConfigMap approach is no longer recommended).

Common access policies (namespace or cluster scope)

PolicyRoughly equivalent toFor CI?
AmazonEKSClusterAdminPolicycluster-adminNo
AmazonEKSAdminPolicyadmin (can manage RBAC within the namespace)Usually not needed
AmazonEKSEditPolicyedit (can modify most namespace resources)Recommended, scoped to the application namespace
AmazonEKSViewPolicyviewRead-only check job

What: Lambda versions and aliases

  • $LATEST: a mutable "working copy" that UpdateFunctionCode changes.
  • Version (version): PublishVersion generates an immutable snapshot (code + configuration), numbered 1, 2, 3….
  • Alias (alias): a pointer to a version (e.g., live), callers and event sources reference only the alias; the alias can set AdditionalVersionWeights, sending part of the traffic to a second version. This is Lambda's native canary.
  • Deployment package: zip (up to 50 MB uploaded directly, larger ones via S3) or a container image (must be in ECR, max 10 GB). Container images must implement the Lambda runtime interface; a Flask web app like myapp can run with an extension such as AWS Lambda Web Adapter (see its project documentation).

Why: why CI should "publish a version and switch the alias" instead of changing $LATEST directly

Changing $LATEST directly switches all traffic to the new code instantly, so if something goes wrong, you can only deploy again. After publishing a version, the alias can first give the new version 10%, then go to 100% after observing metrics; rolling back only requires pointing the alias back to the old version,taking effect within seconds, with no rebuild needed.

How: two GitHub approaches

aws-actions/aws-lambda-deploy@v1AWS CLI
Update codepackage-type: Zip + code-artifacts-dir, or package-type: Image + image-uriaws lambda update-function-code --zip-file / --image-uri
Publish versionpublish Default true, outputs version--publish or aws lambda publish-version
Switch aliasThe Action does not switch aliases; use the CLI afterwardaws lambda update-alias --routing-config
Otherdry-run validates permissions; optionally via s3-bucket uploadSAM/CodeDeploy can automate ones like Canary10Percent5Minutes, etc.
Common misconceptions (1) "If the EKS creator can access it, the CI role can too" - the cluster creator is granted an admin access entry by default; all other identities must be created explicitly. (2) "Lambda alias weights can point to $LATEST" - additional version weights can only be used for published versions. (3) "Pods on EKS access AWS with the CI role" - pods should use the runtime role from EKS Pod Identity or IRSA, completely separate from the CI role.

EKS: from OIDC temporary credentials to kubectl apply

Temporary credentialsassumed-role/gh-myapp-dev-deploy update-kubeconfigeks:DescribeCluster→ endpoint + CA aws eks get-tokenPresigned STSGetCallerIdentity EKS API serverAuthentication: role ARN → access entry?Authorization: AmazonEKSEditPolicy @ ns myapp No access entry→ Unauthorized Wrong namespace→ Forbidden IAM permissions stop at DescribeCluster;What you can do inside Kubernetes is determined entirely by access entries and policies
Figure 5-1 EKS authentication (who you are) and authorization (what you can do)

Lambda: versions and aliases

$LATESTUpdateFunctionCode Publish Version 6 Version 7 (new) Alias livev6 90% + v7 10% Callers / API GatewayReference only myapp-fn:live Rollback = update-alias back to version 6 and clear the weights (seconds, no rebuild needed)
Figure 5-2 versions are immutable, aliases can move

Interactive: Lambda alias weighted traffic shifting

After dragging the weight slider, click "Send 50 requests" to observe how requests are split between version 6 and version 7; version 7 can be switched to "defective" to see how the error rate changes with the weight, then practice rolling back.

Version 7 weight: 10%
v6 successv7 successv7 error
Alias live currently: v6 100%.
$ aws lambda get-alias --function-name myapp-fn --name live

EKS: authorize the CI role and deploy

CommandPurposeNotes
aws eks describe-cluster --query cluster.accessConfigCheck the authentication modeRequires API or API_AND_CONFIG_MAP
aws eks create-access-entry --principal-arn ROLE_ARNCreate an access entry for the CI role--type STANDARD (default)
aws eks associate-access-policy --access-scope type=namespace,namespaces=myappAssociate access policyCI gets only the application namespace
aws eks update-kubeconfig --name eks-labGenerate kubeconfigAWS CLI and kubectl are preinstalled on the runner (see the runner image manifest)
kubectl auth can-iVerify permissions-n myapp
# Run once by the cluster admin (the cluster reuses eks-lab from K8s Lesson 7)
ROLE_ARN=arn:aws:iam::$ACCOUNT_ID:role/gh-myapp-dev-deploy
aws eks create-access-entry --cluster-name eks-lab --principal-arn $ROLE_ARN --type STANDARD
aws eks associate-access-policy --cluster-name eks-lab --principal-arn $ROLE_ARN \
  --policy-arn arn:aws:eks::aws:cluster-access-policy/AmazonEKSEditPolicy \
  --access-scope type=namespace,namespaces=myapp
# Add minimum IAM-side permissions for the CI role
aws iam put-role-policy --role-name gh-myapp-dev-deploy --policy-name eks-describe --policy-document \
  "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"eks:DescribeCluster\",\"Resource\":\"arn:aws:eks:$AWS_REGION:$ACCOUNT_ID:cluster/eks-lab\"}]}"
  deploy-eks:
    needs: build
    runs-on: ubuntu-latest
    environment: dev
    steps:
      - uses: actions/checkout@v7
      - uses: aws-actions/configure-aws-credentials@v6
        with:
          role-to-assume: ${{ vars.AWS_ROLE_ARN }}
          aws-region: ${{ vars.AWS_REGION }}
      - run: aws eks update-kubeconfig --name eks-lab --region ${{ vars.AWS_REGION }}
      - run: kubectl auth can-i patch deployments -n myapp
      # Option A: kubectl
      - run: |
          kubectl -n myapp set image deployment/myapp web=${{ needs.build.outputs.image }}
          kubectl -n myapp rollout status deployment/myapp --timeout=180s
      # Option B: Helm 4 (--rollback-on-failure is the new name for Helm 3's --atomic)
      # - run: helm upgrade --install myapp ./chart -n myapp --set image.ref=${{ needs.build.outputs.image }} --rollback-on-failure --timeout 5m

Lambda: publish version and weighted alias

CommandPurpose
aws lambda update-function-code --function-name F --zip-file fileb://f.zip --publishUpdate code and publish a version (for container images, use --image-uri …@sha256:…)
aws lambda wait function-updated-v2 --function-name FWait for the update to finish before publishing or switching aliases
aws lambda update-alias --function-name F --name live --function-version 6 --routing-config '{"AdditionalVersionWeights":{"7":0.1}}'v6 90% / v7 10%
aws lambda update-alias --function-name F --name live --function-version 7 --routing-config '{"AdditionalVersionWeights":{}}'Shift all traffic to v7
      - id: lambda
        uses: aws-actions/aws-lambda-deploy@v1
        with:
          function-name: myapp-fn
          code-artifacts-dir: lambda/
          handler: handler.handler
          runtime: python3.13
          publish: true
      - name: Canary 10%
        env:
          NEW: ${{ steps.lambda.outputs.version }}
        run: |
          OLD=$(aws lambda get-alias --function-name myapp-fn --name live --query FunctionVersion --output text)
          aws lambda update-alias --function-name myapp-fn --name live --function-version "$OLD" \
            --routing-config "{\"AdditionalVersionWeights\":{\"$NEW\":0.1}}"

The CI role needs lambda:GetFunctionConfiguration,UpdateFunctionCode,UpdateFunctionConfiguration,PublishVersion,GetAlias,UpdateAlias (scoped to the function ARN); if the Action may create a function, it also needs CreateFunction and iam:PassRole on the execution role (as listed in the README).

Lab 5 (optional, about 6 min): Lambda alias 10% canary

The EKS part reuses the cluster from K8s Lesson 7; just read through it on the Commands tab (a running EKS cluster incurs charges every hour). The Lambda lab is almost free (within the free tier).

Admin creates the function and execution role
mkdir -p lambda && cat > lambda/handler.py <<'EOF'
import os
def handler(event, context):
    return {"statusCode": 200, "body": f"myapp-fn version {context.function_version}"}
EOF
(cd lambda && zip -q ../fn.zip handler.py)
aws iam create-role --role-name myapp-fn-exec --assume-role-policy-document \
  '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"lambda.amazonaws.com"},"Action":"sts:AssumeRole"}]}'
aws iam attach-role-policy --role-name myapp-fn-exec --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
sleep 10
aws lambda create-function --function-name myapp-fn --runtime python3.13 --handler handler.handler \
  --zip-file fileb://fn.zip --role arn:aws:iam::$ACCOUNT_ID:role/myapp-fn-exec --publish --query Version --output text
aws lambda create-alias --function-name myapp-fn --name live --function-version 1
1
{ "AliasArn": "arn:aws:lambda:ca-central-1:111122223333:function:myapp-fn:live", "FunctionVersion": "1", … }
Add Lambda permissions to the dev role, then put the aws-lambda-deploy + canary steps from the Commands tab into a deploy-lambda job (environment: dev).
aws iam put-role-policy --role-name gh-myapp-dev-deploy --policy-name lambda-deploy --policy-document "{
 \"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[
  \"lambda:GetFunctionConfiguration\",\"lambda:UpdateFunctionCode\",\"lambda:UpdateFunctionConfiguration\",
  \"lambda:PublishVersion\",\"lambda:GetAlias\",\"lambda:UpdateAlias\"],
 \"Resource\":[\"arn:aws:lambda:$AWS_REGION:$ACCOUNT_ID:function:myapp-fn\",\"arn:aws:lambda:$AWS_REGION:$ACCOUNT_ID:function:myapp-fn:*\"]}]}"
Observe traffic splitting: after changing the handler's return text and pushing, the workflow publishes version 2 and gives it 10%.
for i in $(seq 1 20); do aws lambda invoke --function-name myapp-fn:live --query ExecutedVersion --output text /tmp/out.json; done | sort | uniq -c
aws lambda get-alias --function-name myapp-fn --name live --query '[FunctionVersion,RoutingConfig]'
     18 1
      2 2
["1", {"AdditionalVersionWeights": {"2": 0.1}}]
Full shift or rollback
aws lambda update-alias --function-name myapp-fn --name live --function-version 2 --routing-config '{"AdditionalVersionWeights":{}}'   # full
aws lambda update-alias --function-name myapp-fn --name live --function-version 1 --routing-config '{"AdditionalVersionWeights":{}}'   # rollback

Case 1: all CI jobs get Unauthorized after upgrading the EKS authentication mode

Problem: The platform team switched the cluster from CONFIG_MAP to API mode and deleted aws-auth, but did not create access entries for each team's CI role. Fix: Before switching, first use API_AND_CONFIG_MAP as a transition: migrate every aws-auth mapping to an access entry and verify with kubectl auth can-i before switching to API.

Case 2: one CI role holds cluster admin

Problem: For convenience, the CI role was associated with AmazonEKSClusterAdminPolicy (cluster scope), and a compromised workflow deleted the kube-system components in it. Fix: Use one CI role per application, associating only AmazonEKSEditPolicy with its own namespace; platform components are synced inside the cluster by GitOps (Argo CD/Flux), and CI only updates the image version in Git.

Case 3: Lambda canary exposes a problem; rollback in seconds

Problem: The new version parses a certain type of event incorrectly. Fix: The alias gives only 10%; after a CloudWatch error-rate alarm fires, the rollback job in the workflow (workflow_dispatch) runs update-alias to point back to the old version; the impact is limited to 10% of traffic for a few minutes. For further automation, use CodeDeploy's Lambda deployment configurations to automate the "observe then roll back" cycle.

Common errors and fixes

error: You must be logged in to the server (Unauthorized)

Cause: The CI role has no EKS access entry (or the cluster is still in CONFIG_MAP mode with no mapping in aws-auth); it may also be that the kubeconfig points to a different cluster or region.

aws sts get-caller-identity
aws eks list-access-entries --cluster-name eks-lab
aws eks describe-cluster --name eks-lab --query cluster.accessConfig.authenticationMode
Error from server (Forbidden): deployments.apps "myapp" is forbidden: User "arn:aws:sts::…:assumed-role/gh-myapp-dev-deploy/…" cannot patch resource "deployments" in API group "apps" in the namespace "myapp"

Cause: The access entry exists but has no associated policy, or the policy scope does not include that namespace. Fix:aws eks list-associated-access-policies --cluster-name eks-lab --principal-arn ROLE_ARN, then associate.

An error occurred (ResourceConflictException) when calling the UpdateFunctionCode operation: The operation cannot be performed at this time. An update is in progress for resource

Cause: The previous update has not finished (LastUpdateStatus = InProgress). Fix:aws lambda wait function-updated-v2 --function-name F before proceeding; in the workflow, add concurrency.

InvalidParameterValueException: … AdditionalVersionWeights … $LATEST

Cause: Alias weights can only be used with published versions. Fix: First run PublishVersion (or --publish), and use the returned version number.

Command-line exercises
1. Check which access policies the CI role is associated with on eks-lab.
aws eks list-associated-access-policies --cluster-name eks-lab \
  --principal-arn arn:aws:iam::$ACCOUNT_ID:role/gh-myapp-dev-deploy
2. Set the live alias to v3 80% / v4 20%.
aws lambda update-alias --function-name myapp-fn --name live --function-version 3 \
  --routing-config '{"AdditionalVersionWeights":{"4":0.2}}'
Scenario analysis
The company has a shared EKS platform, and the platform team does not want each application's CI to access the Kubernetes API directly. How would you design the GitHub deployment?

Use GitOps: the application CI only builds and pushes the image (OIDC → ECR), then opens a PR or commits to the deployment configuration repository to update the image digest; Argo CD/Flux inside the cluster pulls and syncs. This way the CI role needs no EKS access entry, and Kubernetes permissions are concentrated in the GitOps controller inside the cluster; approvals are enforced through the configuration repository's rulesets and CODEOWNERS.

Verified instructional videos

▶
AWS EKS - Create Kubernetes cluster on Amazon EKS | the easy way — TechWorld with Nana
English · EKS cluster basics (recorded earlier; for access entries, follow this lesson and K8s Lesson 7)
▶
EKS Pod Identity vs IRSA | Securely Connect Kubernetes Pods to AWS Services — Containers from the Couch
English · Runtime identity (separate from CI identity)
▶
Amazon EKS Auto Mode | Fully Automated Kubernetes Clusters — AWS Developers
English · EKS Auto Mode overview

No verified video on "GitHub Actions + Lambda alias weighting" was found; please refer to the documentation and storyboard below.

Official documentation

Video storyboard (about 60 seconds)

Shot 1 · 0–20s
Visual: two gates; the first is labeled IAM, the second is labeled Access Entry.
Narration: deploying to EKS means passing two gates: IAM only gets you the cluster endpoint, and access entries decide what you can do inside Kubernetes.
Shot 2 · 20–40s
Visual: Lambda version cards freeze one by one, and the live alias slides like a pointer between versions.
Narration: once published, a Lambda version is immutable; an alias is a pointer that can move.
Shot 3 · 40–60s
Visual: traffic bar at 90/10, an error red dot appears, and the pointer instantly goes back to the old version.
Narration: give the new version 10% of the traffic first; if something goes wrong, point the alias back, and the rollback takes just seconds.
or score ≥ 70% on the quiz

Module 6 · Multi-account and environment promotion

38:00 – 45:00 · Build once, promote by digest; one account, one role, and one GitHub environment per environment
7 minenvironment approvals · allowed-account-idsOrganization-level trust: repository_owner_id★★★★★
Learning objectives
  • Design a dev / stage / prod multi-account structure: create the OIDC provider in each account (one per account), with each role trusting …:environment:<env>, and on the GitHub side use the environment-level variable AWS_ROLE_ARN.
  • Use the GitHub environment's required reviewers and deployment branch restrictions to protect prod, and use allowed-account-ids to prevent "the credentials are right but the account is wrong".
  • Compare "direct OIDC per account" with "central role + role chaining", and understand org-level trust patterns based on repository_owner_id,job_workflow_ref org-level trust patterns.
Prerequisites: Module 2; Lesson 2 on environments. Importance:★★★★★

What: recommended account and identity layout

AccountWhat it holdsGitHub sideSub trusted by the role
shared-services (tooling account)ECR (single image source), optional central CI rolebuild job (environment: build or branch-restricted)repo:org@OID/myapp@RID:environment:build
devECS cluster/service myapp-devenvironment: dev (automatic)…:environment:dev
stagemyapp-stageenvironment: stage (main only)…:environment:stage
prodmyapp-prodenvironment: prod (required approval + main/tags only)…:environment:prod

Key points: The OIDC provider must be in the same account as the role that trusts it (as required by the IAM documentation), so one is created in each account; ECR lives in the shared account, and the repository policy allows the task execution roles in each environment account (or, using aws:PrincipalOrgID restricted to this organization) to pull.

Why: why one role per environment

  • Blast radius: if the dev role is misused, the impact is limited to the dev account.
  • Approvals are really effective: GitHub environment approvals only control whether a job may start; if the dev job could also assume the prod role, approvals would be meaningless. The environment:prod only appears in jobs that passed the prod protection rules, tying GitHub approvals to AWS trust.
  • Clear auditing: in CloudTrail, assumed-role/gh-myapp-prod-deploy/gh-RUNID maps directly to one approved run.

How: GitHub environment protection rules (availability verified)

RuleEffectPlan restrictions
Required reviewersUp to 6 users or teams; any one approval lets the deployment continue; you can check "Prevent self-review"Free/Pro/Team: public repositories only; private repositories require Enterprise
Wait timerStarts only after N minutes of delaySame as above
Deployment branches and tagsOnly allow main or v* tags to deploy to this environmentAvailable for all public repositories; also available for Pro/Team private repositories
Environment variables / secretsvars.AWS_ROLE_ARN Scoped per environmentOn the Free plan, environment secrets are for public repositories only

Two cross-account patterns

A. Direct OIDC per account (recommended)B. Central role + role chaining
ApproachCreate an OIDC provider and environment role in each account; the job calls AssumeRoleWithWebIdentityCreate OIDC only in the tooling account; the job first assumes the central role, then role-chaining: true assumes the environment account role (which trusts the central role)
ProsShort chain; sub conditions apply directly in the target account; sessions can last up to 12 hoursOIDC trust managed centrally
ConsEach account must maintain a provider (roll out in bulk with IaC/StackSets)Sessions last at most 1 hour; the target account cannot see the original sub and can only trust the central role (session tags can carry context)

Org-level OIDC trust pattern

Platform teams often want "any repository in the organization can use the same role to deploy to sandbox". In the past, the only option was to write StringLike sub = repo:my-org/*, which is too broad and depends on a mutable organization name. AWS, on 2026-02-02 announced that STS supports validating specific claims from IdPs such as GitHub; the GitHub keys listed in the IAM documentation include actor,actor_id,job_workflow_ref,repository,repository_id,repository_owner_id,workflow,ref,environment,enterprise_id. From this, the following more robust org-level conditions can be written:

  • token.actions.githubusercontent.com:repository_owner_id = the organization's numeric ID (immutable, so renaming the org has no effect);
  • token.actions.githubusercontent.com:environment = sandbox (requires the job to use this environment; the IAM documentation notes that if the condition includes environment, the workflow must configure an environment);
  • token.actions.githubusercontent.com:job_workflow_ref = the reusable deployment workflow maintained by the platform team (for example my-org/deploy-workflows/.github/workflows/ecs.yml@refs/heads/main), meaning only jobs that go through the standard deployment flow can get credentials (see Lesson 5 for reusable workflows).

On the GitHub side, you can also use the REST API to customize the org's sub template (include_claim_keys); for repositories already using the immutable format, the repo segment always includes the numeric owner/repo IDs. Before changing the template, you must first add matching conditions on the AWS side, or new tokens will be rejected.

Common misconceptions (1) "The environment approval passed, so it is safe" - if the AWS role does not check environment:prod, any job can bypass the approval and assume the role directly. (2) "One OIDC provider can serve all accounts" - no; the provider referenced by the trust policy must be in the role's account. (3) "Rebuilding the image once more for prod is safer" - on the contrary, promotion must use the same digest; otherwise, what you tested is not what you ship.

Promotion pipeline: build once, deploy three times

buildenv: build→ digest 9b1c… deploy-devenv: dev (automatic)Account 2222… deploy-stageenv: stage (main only)Account 3333… deploy-prodenv: prod (approval)Account 4444… Approvers≤ 6 users/teamsPrevent self-review AWS side: each account = OIDC provider + one environment role dev accountgh-myapp-dev-deploysub = …myapp@RID:environment:devECS: UpdateService myapp-dev stage accountgh-myapp-stage-deploysub = …:environment:stageallowed-account-ids: 3333… prod accountgh-myapp-prod-deploysub = …:environment:prodOnly approved jobs have this sub
Figure 6-1 GitHub environment protection × AWS trust conditions = the real promotion gate

Interactive: trust matrix simulator

Choose "requesting job" and "target role" to simulate STS evaluation. Observe why only combinations that satisfy both the environment and the repository ID succeed.

Requesting job
Target role
Choose a job and a role.
$ # STS evaluation process

Core commands and configuration

Command / configurationPurpose
gh api -X PUT repos/OWNER/myapp/environments/prod --input prod-env.jsonSet reviewers and deployment branch policy
gh api -X POST repos/OWNER/myapp/environments/prod/deployment-branch-policies -f name=main -f type=branchOnly allow main to deploy to prod
gh variable set AWS_ROLE_ARN --env prod --body …Environment-level role ARN
allowed-account-ids: "444455556666"configure-aws-credentials verifies that the credentials belong to the expected account
aws ecr set-repository-policyShared-account ECR allows accounts in the organization to pull
# prod environment: yourself as the reviewer (personal public repo lab); only allow branches in the protected branch policy
MY_ID=$(gh api user --jq .id)
cat > prod-env.json <<EOF
{ "wait_timer": 0,
  "prevent_self_review": false,
  "reviewers": [ { "type": "User", "id": $MY_ID } ],
  "deployment_branch_policy": { "protected_branches": false, "custom_branch_policies": true } }
EOF
gh api -X PUT repos/$GH_OWNER/myapp/environments/prod --input prod-env.json >/dev/null
gh api -X POST repos/$GH_OWNER/myapp/environments/prod/deployment-branch-policies -f name=main -f type=branch

Team repositories should set prevent_self_review: true, and set the reviewer to the team ("type":"Team"). In a personal lab only you exist, so turn it off; otherwise no one can approve.

Repository policy for the shared-account ECR (organization pull)

{
  "Version": "2012-10-17",
  "Statement": [{
    "Sid": "OrgPull",
    "Effect": "Allow",
    "Principal": "*",
    "Action": ["ecr:BatchGetImage", "ecr:GetDownloadUrlForLayer"],
    "Condition": { "StringEquals": { "aws:PrincipalOrgID": "o-exampleorgid" } }
  }]
}

Org-level trust (sandbox role example)

{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": { "Federated": "arn:aws:iam::555566667777:oidc-provider/token.actions.githubusercontent.com" },
    "Action": "sts:AssumeRoleWithWebIdentity",
    "Condition": {
      "StringEquals": {
        "token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
        "token.actions.githubusercontent.com:repository_owner_id": "123456",
        "token.actions.githubusercontent.com:environment": "sandbox",
        "token.actions.githubusercontent.com:job_workflow_ref": "my-org/deploy-workflows/.github/workflows/ecs.yml@refs/heads/main"
      },
      "StringLike": {
        "token.actions.githubusercontent.com:sub": "repo:my-org@123456/*"
      }
    }
  }]
}

Keeping a sub condition is good practice (GitHub's documentation calls for evaluating sub); the repo:my-org@123456/* only matches repositories that use the immutable format; repositories on the old format need separate entries. Confirm the case and format of claim values against your actual token (print them first with a whoami workflow).

Lab 6: single-account simulation of "the prod role only trusts the prod environment" (about 6 min)

Real multi-account setups require AWS Organizations; this lab simulates one in a single account with two roles and two services. The structure is identical; when moving to multiple accounts, create the prod role and service in the prod account and create an OIDC provider there.

Configure prod environment protection: run the first part of the Commands tab.
Create the prod role (trusts only environment:prod)
source ~/gh-part4.env
SUB_PROD="${SUB_DEV%:environment:dev}:environment:prod"; echo $SUB_PROD
sed "s#$SUB_DEV#$SUB_PROD#" trust-dev.json > trust-prod.json
aws iam create-role --role-name gh-myapp-prod-deploy --assume-role-policy-document file://trust-prod.json \
  --max-session-duration 3600 --tags Key=course,Value=gh-part4 --query Role.Arn --output text
# Permissions: no ECR push (deploys by digest; image pulls are done by the task execution role), and can only update myapp-prod
# Note: SUB_DEV, trust-dev.json, and ecs-deploy.json come from Modules 2/4; set SUB_DEV again if you open a new terminal
sed 's#myapp-dev#myapp-prod#' ecs-deploy.json > ecs-deploy-prod.json
aws iam put-role-policy --role-name gh-myapp-prod-deploy --policy-name ecs-deploy-myapp-prod --policy-document file://ecs-deploy-prod.json
gh variable set AWS_ROLE_ARN --env prod --body "arn:aws:iam::$ACCOUNT_ID:role/gh-myapp-prod-deploy"
repo:octo-dev@123456/myapp@789012:environment:prod
arn:aws:iam::111122223333:role/gh-myapp-prod-deploy
✓ Created variable AWS_ROLE_ARN for octo-dev/myapp
Create the myapp-prod service (same as Module 4 step 1, with the service name changed to myapp-prod, and desired-count set to 1 to save money).
Add the deploy-prod job: copy deploy-dev and change three things: needs: [build, deploy-dev],environment: prod,service: myapp-prod (also update the service name in the Verify step), and add
      - uses: aws-actions/configure-aws-credentials@v6
        with:
          role-to-assume: ${{ vars.AWS_ROLE_ARN }}
          aws-region: ${{ vars.AWS_REGION }}
          role-session-name: gh-${{ github.run_id }}
          allowed-account-ids: ${{ vars.AWS_ACCOUNT_ID }}   # first run gh variable set AWS_ACCOUNT_ID --env prod --body <account>
Push and approve: the Actions page shows "deploy-prod — Waiting for review"; click Review deployments → prod → Approve and deploy.
gh run list --workflow deploy.yml -L1
gh api repos/$GH_OWNER/myapp/actions/runs/RUN_ID/pending_deployments --jq '.[].environment.name'
prod
Privilege test: temporarily change deploy-dev's role-to-assume to the prod role ARN and run it once; it should fail with Not authorized to perform sts:AssumeRoleWithWebIdentity (sub is environment:dev). Restore it after testing.

Case 1: approval bypassed

Problem: The prod environment had approvals configured, but the prod role trusted repo:org/app:ref:refs/heads/main. Someone created a new workflow without an environment, ran it on main, and got prod credentials directly. Fix: The prod role trusts only environment:prod; at the same time, use a ruleset to restrict who can change .github/workflows/ (CODEOWNERS + required review).

Case 2: stage credentials deployed to the prod account

Problem: When copying and pasting a workflow, the stage environment's variable was pointed at the prod role ARN, and that prod role's trust policy incorrectly allowed stage. Fix: Correct the trust policy; add allowed-account-ids, so mismatched accounts fail immediately; generate environment variables centrally with IaC instead of filling them in by hand.

Case 3: managing OIDC providers across hundreds of accounts

Problem: The platform team must maintain OIDC providers and deployment roles across 300 accounts. Fix: Use CloudFormation StackSets (service-managed permissions, auto-deployed by OU) or Terraform to roll out the providers and an "org-level sandbox role" centrally, with trust conditions using repository_owner_id and job_workflow_ref; roles in production accounts are still granted precisely by repository and environment.

Common errors and fixes

No OpenIDConnect provider found in your account for https://token.actions.githubusercontent.com (fails only in prod)

Cause: The prod account has no OIDC provider. Fix: In the prod account, run create-open-id-connect-provider, or roll it out centrally with StackSets.

The account ID of the provided credentials is not in 'allowed-account-ids'

Cause:allowed-account-ids The guard is working: the credentials belong to another account (a misconfigured variable). Fix: Check the environment variable AWS_ROLE_ARN and AWS_ACCOUNT_ID. For the exact error text, refer to the Action log.

deploy-prod stays "Waiting" with no approve button

Cause: You are not on the reviewer list, or "Prevent self-review" is checked and you are the one who triggered the run; required reviewers are not available for private repositories on Free/Pro/Team. Fix: Check the environment settings, or use gh api repos/O/R/actions/runs/ID/pending_deployments to view them.

Branch "feature/x" is not allowed to deploy to prod due to environment protection rules.

Cause: The deployment branch policy only allows main. This is expected behavior.

Command-line exercises
1. List the protection rules of the prod environment.
gh api repos/$GH_OWNER/myapp/environments/prod --jq '{rules: [.protection_rules[].type], branch: .deployment_branch_policy}'
2. List the deployment branch policies allowed for the prod environment.
gh api repos/$GH_OWNER/myapp/environments/prod/deployment-branch-policies --jq '.branch_policies[].name'
Scenario analysis
The company requires that "any prod change must be approved through the change ticket system". How do you implement this in GitHub + AWS deployments?

Configure a custom deployment protection rule on the prod environment (a GitHub App deployment protection rule, where the ticket system calls back to approve or reject), then layer required reviewers on top; on the AWS side, the prod role trusts only environment:prod, so jobs that fail the protection rule never get credentials. For audits, link the GitHub deployment record, the ticket number, and the session name in CloudTrail gh-RUNID.

Instructional videos

No oEmbed-verified video on "GitHub OIDC + AWS multi-account promotion" was found. The following verified videos can serve as background:

▶
AWS re:Invent 2024 - Unleashing the power of Amazon ECS for platform teams (SVS330) — AWS Events
English · How platform teams provide ECS to multiple application teams

Official documentation

Video storyboard (about 60 seconds)

Shot 1 · 0–20s
Visual: one image digest moves along a conveyor belt through the dev, stage, and prod rooms in turn.
Narration: the image is built only once and is promoted in turn with the same fingerprint.
Shot 2 · 20–40s
Visual: an approver stands at the prod door, and the lock reads environment:prod.
Narration: GitHub approval decides whether a job can start, and the AWS trust policy only accepts tokens with environment colon prod. You need both locks.
Shot 3 · 40–60s
Visual: every account has an OIDC badge.
Narration: remember, the OIDC provider must be in the same account as the role; create one in each account and manage them in bulk with IaC.
or score ≥ 70% on the quiz

Module 7 · Hands-on cloud deployment troubleshooting

45:00 – 54:00 · Rule out layer by layer: token → STS trust → IAM permissions → service behavior
9 minCloudTrail · ECS events · can-iInteractive troubleshooting tree★★★★★
Learning objectives
  • When you see an error, first determine which layer it belongs to: the GitHub token, STS trust, the IAM permission policy, or the ECR/ECS/EKS behavior itself.
  • Use the whoami workflow, CloudTrail AssumeRoleWithWebIdentity events,simulate-principal-policy, ECS service events and stopped-task reasons,kubectl auth can-i.
  • Fix these independently: Not authorized to perform sts:AssumeRoleWithWebIdentity,No OpenIDConnect provider found, ECR login failures, ECS deployments stuck or tripping the circuit breaker, and EKS Unauthorized.
Prerequisites: Modules 2–6. Importance:★★★★★

Four-layer troubleshooting model

LayerTypical errorsPrimary evidenceCommon root causes
(1) GitHub tokenDid you mean to set the `id-token` permission?,Could not load credentials from any providersthe workflow's permissions; the triggering event (fork PR?)Missing id-token: write; the caller of a reusable workflow did not grant the permission; fork PR
(2) STS trustNot authorized to perform sts:AssumeRoleWithWebIdentity,No OpenIDConnect provider found,Incorrect token audience,DurationSeconds exceedsthe sub printed by whoami; get-role 's trust policy; CloudTrailsub format (old vs. immutable, environment vs. branch), provider not in that account, aud, duration
(3) IAM permissionsis not authorized to perform: ecr:… / ecs:… / iam:PassRoleThe Action and Resource ARN in the error; simulate-principal-policymissing action, wrong region or name in Resource, PassRole, SCP or permissions boundary denial
(4) Service behaviorCannotPullContainerError,ResourceInitializationError, circuit breaker FAILED,Unauthorized (EKS)ECS service events,stoppedReason, CloudWatch logs, EKS access entriesimage, network, health checks, execution role; missing access entry

Why layers matter

Although they all look like "deployment failed", the person who fixes each one differs by layer: (1) and (2) are the workflow author or IAM administrator; (3) is the IAM administrator (possibly also involving organization SCPs); (4) is the application or platform team. Locate the layer first, then find the right person; this can cut the mean time to fix from "hours of blame-shifting" to a few minutes.

Where the key evidence comes from

  • whoami workflow (Module 2): print the actual sub/aud/repository_id/environment, and compare it word for word with the trust policy.
  • CloudTrail event history: event name AssumeRoleWithWebIdentity (an STS event, recorded in the region or on the global endpoint); successful events include assumedRoleUser, and failed events have errorCode/errorMessage; subsequent service calls are recorded as assumed-role/role/session-name .
  • Policy simulation: aws iam simulate-principal-policy --policy-source-arn ROLE_ARN --action-names ecs:UpdateService --resource-arns SERVICE_ARN, with results of allowed / implicitDeny / explicitDeny. Note that it does not evaluate every case (such as some SCPs and session policies); go by the actual error.
  • ECS: from describe-services the events,deployments[].rolloutStateReason; from describe-tasks , the stoppedReason and the container reason/exitCode.
  • GitHub debug logs: when re-running, check "Enable debug logging", or set the repository variable or secret ACTIONS_STEP_DEBUG=true.
Common misconceptions (1) "Not authorized to perform sts:AssumeRoleWithWebIdentity is a permissions policy problem" - no, it is a trust policy (or the role ARN is wrong / the role does not exist) problem, and adding permissions to the role will not help. (2) "An ECR login failure is an ECR problem" - most of the time, the credentials from the previous step were not obtained or are missing GetAuthorizationToken. (3) "A stalled ECS deployment means the Action is broken" - the Action is only polling; the real cause is in the service events.

Troubleshooting path overview

(1) Token layerpermissions.id-token?fork PR?Reusable workflow permission inheritance? (2) STS trust layerProvider in this account?aud = sts.amazonaws.com?sub matches exactly? Duration? (3) IAM permissions layerAction/Resource in the errorPassRole? SCP?simulate-principal-policy (4) Service layerECS events / stoppedReasonEKS access entryLambda update status Locating tip: see which step failed configure-aws-credentials fails → (1) or (2) | ecr-login / build-push fails → (3) (ECR permissions) or the repository does not exist deploy-task-definition reports AccessDenied → (3); stuck at "Waiting for the service to become stable" → (4) kubectl reports Unauthorized → access entry; Forbidden → access policy scope; Verify step fails → circuit-breaker rollback (4)
Figure 7-1 quickly identify the layer from the failed step

Fault diagnosis challenge: read the logs and pick the root cause

Each level shows a realistic workflow log; choose the root cause you think it is, and the system will reveal the answer, the layer, and the fix command. 6 levels in total.

Troubleshooting command cheat sheet

ScenarioCommand
View trust policyaws iam get-role --role-name R --query Role.AssumeRolePolicyDocument
View provideraws iam list-open-id-connect-providers; get-open-id-connect-provider --open-id-connect-provider-arn …
Look up STS events in CloudTrailaws cloudtrail lookup-events --lookup-attributes AttributeKey=EventName,AttributeValue=AssumeRoleWithWebIdentity --max-results 5
Simulate permissionsaws iam simulate-principal-policy --policy-source-arn ROLE_ARN --action-names ecs:UpdateService --resource-arns SVC_ARN
ECS eventsaws ecs describe-services --cluster C --services S --query 'services[0].events[:10].[createdAt,message]' --output text
Reasons for stopped tasksaws ecs list-tasks --cluster C --service-name S --desired-status STOPPED → describe-tasks --query 'tasks[].[stoppedReason,containers[0].exitCode,containers[0].reason]'
Container logsaws logs tail /ecs/myapp --since 15m
EKS identity and permissionsaws eks list-access-entries; kubectl auth can-i --list -n myapp
Decode authorization failure messages in CloudTrailaws sts decode-authorization-message --encoded-message … (some services such as EC2 return encoded messages)
# View the most recent failed AssumeRoleWithWebIdentity
aws cloudtrail lookup-events \
  --lookup-attributes AttributeKey=EventName,AttributeValue=AssumeRoleWithWebIdentity --max-results 10 \
  --query 'Events[].CloudTrailEvent' --output text | jq -c 'select(.errorCode) | {eventTime, errorCode, errorMessage, role: .requestParameters.roleArn}'
{"eventTime":"2026-11-15T14:02:11Z","errorCode":"AccessDenied","errorMessage":"Not authorized to perform sts:AssumeRoleWithWebIdentity","role":"arn:aws:iam::111122223333:role/gh-myapp-prod-deploy"}

CloudTrail event history has a delay of a few minutes; for multi-region setups, query the correct region (STS regional endpoint events are recorded in the corresponding region).

Lab 7: create three failures and fix them (about 8 min)

Failure A: sub mismatch——change the dev role's trust to the old format (assuming your repository uses the immutable format):
source ~/gh-part4.env
OLD_SUB="repo:$GH_OWNER/myapp:environment:dev"
sed "s#$SUB_DEV#$OLD_SUB#" trust-dev.json > trust-broken.json
aws iam update-assume-role-policy --role-name gh-myapp-dev-deploy --policy-document file://trust-broken.json
gh workflow run whoami.yml
Error: Could not assume role with OIDC: Not authorized to perform sts:AssumeRoleWithWebIdentity

Diagnosis: whoami's first step still prints the real sub (including the @numeric ID); compare it with the get-role result. Fix: aws iam update-assume-role-policy --role-name gh-myapp-dev-deploy --policy-document file://trust-dev.json.

Failure B: missing PassRole——temporarily delete the PassRole statement from the ECS deployment policy, then re-run deploy:
jq 'del(.Statement[] | select(.Sid=="PassExecRole"))' ecs-deploy.json > ecs-nopass.json
aws iam put-role-policy --role-name gh-myapp-dev-deploy --policy-name ecs-deploy-myapp-dev --policy-document file://ecs-nopass.json
aws iam simulate-principal-policy --policy-source-arn arn:aws:iam::$ACCOUNT_ID:role/gh-myapp-dev-deploy \
  --action-names iam:PassRole --resource-arns arn:aws:iam::$ACCOUNT_ID:role/myappTaskExecutionRole \
  --query 'EvaluationResults[0].EvalDecision' --output text
implicitDeny

In the workflow, the deploy step reports is not authorized to perform: iam:PassRole. Fix: re-apply put-role-policy … file://ecs-deploy.json.

Failure C: task does not start——change the task definition's port health check to 5001 (the app actually listens on 5000), then push:
sed -i 's#localhost:5000/healthz#localhost:5001/healthz#' .aws/task-definition.json
git commit -am "test: break health check" && git push
# A few minutes later
aws ecs describe-services --cluster $CLUSTER --services myapp-dev \
  --query 'services[0].deployments[].[status,taskDefinition,rolloutState,rolloutStateReason]' --output text
PRIMARY  …task-definition/myapp:3  IN_PROGRESS  ECS deployment ecs-svc/… in progress.
ACTIVE   …task-definition/myapp:2  COMPLETED   …
… then …
PRIMARY  …task-definition/myapp:2  COMPLETED   ECS deployment circuit breaker: rolling back to deploymentId ecs-svc/…

The stopped task's stoppedReason looks like Task failed container health checks. In the workflow, the Verify step fails (want=:3, got=:2). Fix: restore 5000 and push again. Use the actual events for the exact wording.

Case 1: reusable workflow cannot get a token

Problem: The team extracted deployment into a reusable workflow; after calling it, configure-aws-credentials reported an id-token permission problem. Root cause: The called workflow cannot have more permissions than the caller grants; the caller job does not have id-token: write. Fix: Declare on the caller job permissions: { id-token: write, contents: read }. Also note: at this point the token's job_workflow_ref points to the called workflow and can be used in trust conditions (Module 6).

Case 2: explicit deny from an organization SCP

Problem: The role permissions policy and the trust policy are both correct, but ecs:UpdateService it is still denied, and the simulation shows allowed. Root cause: An organization SCP denied calls outside the allowed regions list (the team mistakenly used us-east-1). Fix: Correct aws-region. Lesson: When the error text contains "with an explicit deny in a service control policy", go straight to the organization administrator.

Case 3: a 200-way matrix job triggers STS throttling

Problem: A 200-way matrix job exchanges credentials at the same time, and some runs report Rate exceeded/Throttling. Fix: configure-aws-credentials has built-in retries (retry-max-attempts), and use strategy.max-parallel to limit concurrency; or first run all AWS-dependent steps in a single job.

Interactive troubleshooting tree

Start from the symptom you see, answer the questions step by step, and get the diagnosis and fix commands.

Quick reference for error messages

Could not assume role with OIDC: Not authorized to perform sts:AssumeRoleWithWebIdentity

The trust policy condition is not met, or the role ARN is wrong. Compare the sub printed by whoami with the trust policy; check whether an environment is used, whether the repository was renamed or transferred, and whether the immutable subject format is in use.

Could not assume role with OIDC: No OpenIDConnect provider found in your account for https://token.actions.githubusercontent.com

The role's account does not have the provider. In a multi-account setup, check each account one by one.

no basic auth credentials / denied: Your authorization token has expired. Reauthenticate and try again.

ecr-login was not run before the push (for example, you logged in in another job but not in this one), or the ECR token has expired (12 hours). In the same job that pushes the image, run amazon-ecr-login.

ResourceInitializationError: unable to pull secrets or registry auth: … unable to retrieve ecr registry auth …

Fargate tasks cannot reach ECR or Secrets Manager: the private subnet has no NAT and no VPC endpoints, or the public subnet does not assign a public IP, or the execution role lacks permissions.

The security token included in the request is expired

The job runs longer than the session duration. Increase role-duration-seconds (it must not exceed MaxSessionDuration; role chaining is limited to 1 hour), or re-run configure before long steps.

Command-line exercises
1. Use one command to check whether the dev role can run UpdateService on myapp-dev.
aws iam simulate-principal-policy --policy-source-arn arn:aws:iam::$ACCOUNT_ID:role/gh-myapp-dev-deploy \
  --action-names ecs:UpdateService \
  --resource-arns arn:aws:ecs:ca-central-1:$ACCOUNT_ID:service/myapp-lab/myapp-dev \
  --query 'EvaluationResults[0].EvalDecision' --output text
2. List the reasons for the last 3 stopped tasks of myapp-dev.
for t in $(aws ecs list-tasks --cluster myapp-lab --service-name myapp-dev --desired-status STOPPED --max-items 3 --query 'taskArns[]' --output text); do
  aws ecs describe-tasks --cluster myapp-lab --tasks $t --query 'tasks[0].[stoppedReason,containers[0].exitCode]' --output text; done
Scenario analysis
On Monday morning, AWS deployments failed in all repositories at the same time with Not authorized to perform sts:AssumeRoleWithWebIdentity. On Friday everything was fine, and nobody changed IAM. What could it be? How would you investigate?

"All repositories at once" points to a shared change: (1) the organization administrator changed the org-level OIDC sub template (include_claim_keys) over the weekend, so the sub format changed; (2) the organization or repositories were bulk-opted into the immutable subject format, or the organization was renamed or transferred; (3) someone modified the shared trust policy or an SCP. To investigate: run whoami to check whether the sub changed; check the OIDC settings changes in the GitHub organization audit log; check IAM events in CloudTrail UpdateAssumeRolePolicy events. Fix: temporarily use a StringLike array in the trust policy to accept both the old and new formats, then migrate everything in one go.

Instructional videos

No verified video dedicated to troubleshooting GitHub to AWS OIDC was found. The following verified videos relate to the ECS part of this module:

▶
Circuit Breakers for Amazon ECS — Containers from the Couch
English · Circuit breaker trigger and rollback behavior
▶
How to Setup AWS ECS Fargate with a Load Balancer | Step by Step — Be A Better Dev
English · Network and security group configuration, helps you understand image pull and health check failures

Official documentation

Video storyboard script (about 60 seconds)

Shot 1 · 0–15s
Visual: four floors, each with one label: token, trust, permissions, service.
Narration: when a deployment fails, don't panic. First work out which layer the problem is in.
Shot 2 · 15–40s
Visual: two sub values side by side, with the difference (@123456) highlighted.
Narration: the most common trust failure is a mismatch between the sub in the token and the sub in the policy. Print both and compare them character by character.
Shot 3 · 40–60s
Visual: the ECS events list scrolls and stops at "circuit breaker: rolling back".
Narration: for service-layer problems, check the ECS events and the stopped task reasons. The answer is almost always there.
or score ≥ 70% on the quiz

Module 8 · Cost, Cleanup, and Self-Check

54:00 – 60:00 · Know where the money goes, delete everything in dependency order, and revoke all trust relationships
6 minutesCleanup scriptCosts are based on the AWS Pricing Calculator★★★★
Learning objectives
  • List the billable items in this lesson's lab: Fargate vCPU and memory, public IPv4, ECR storage, CloudWatch logs, (optional) ALB, EKS cluster, Lambda.
  • Clean up in the correct dependency order: service, then task definition, then cluster, then security group; ECR; logs; Lambda; IAM role (delete its policies first); OIDC provider (confirm nobody is using it).
  • Clean up the GitHub side: environments, variables, and the lab workflow. Then complete this lesson's self-check.
Importance:★★★★ (forgetting cleanup is the most common "incident" in cloud labs)

What: the cost breakdown for this lesson

ResourceBilling methodUsage in this lessonNotes
Fargate tasksPer vCPU-second + GB-second (1-minute minimum)2 dev + 1 prod, 0.25 vCPU / 0.5 GBBilling stops only when the service is stopped
Public IPv4 addressEach address is billed hourly (since 2024-02)One per task with a public IPThis is the hidden cost of the "no ALB" approach
ECRBilled per GB-month of storage; no data transfer fee for pulls to ECS in the same regionA few images of about 100 MB eachLifecycle policies control growth
CloudWatch LogsPer GB ingested + storageVery littleThis lesson sets a 3-day retention
ALB (Express Mode or production)Per hour + LCUNot created in this lessonExpress Mode creates an ALB automatically
EKS clusterCluster per hour (extended-support versions cost more) + nodesRead-only in this lessonIf you reuse the cluster from the K8s lesson, remember to delete it promptly
LambdaPer request + GB-second, with a free tierA few dozen invocationsEssentially zero
IAM, OIDC providers, STS, ECS clustersFree—But they are security assets that must be cleaned up
GitHub ActionsStandard GitHub-hosted runners are free for public repositories; private repositories consume the included minutes quotaOver a dozen runsSee the GitHub billing documentation for details

Why: why the cleanup order matters

  • You cannot delete an ECS cluster while it still has services; a service with running tasks needs to be --force (or scaled to 0 first).
  • A security group still referenced by a task ENI cannot be deleted. Wait until the tasks have fully stopped and the ENI is released.
  • If an IAM role still has inline or managed policies attached, delete-role the deletion fails. Delete the policies first.
  • An OIDC provider is an account-level shared resource: if roles in other teams also trust it, deleting it will make all their deployments fail with No OpenIDConnect provider found. Only delete it in a dedicated lab account.

How: safe cleanup checklist

  1. AWS: roles (dev/prod), EKS access entries, OIDC provider (lab account only).
  2. GitHub: delete the dev/prod environments (along with their environment variables), the repository variable AWS_REGION/AWS_ACCOUNT_ID, and the lab workflow (whoami.yml).
  3. Local: delete temporary JSON files that contain account information (trust-*.json etc.; they contain no secrets, but there is no need to keep them).
  4. You can keep the budget alerts as long-term protection.
Common misconceptions (1) "Setting desiredCount to 0 stops the charges": the tasks stop, but ECR, logs, and the ALB (if any) are still billed. (2) "Deleting the repository revokes AWS trust": the AWS role still exists. If the trust policy uses the old name-based format, someone who re-registers a repository with the same name could, in theory, satisfy the condition. This is exactly the problem that immutable subjects solve, and it is also why the role must be deleted. (3) "The OIDC provider can be deleted at any time": it may be another team's dependency.

Cleanup dependency graph (delete from top to bottom)

ECS service (--force) Task definition revisions ECS cluster · Security group ECR repository (--force) Log group /ecs/myapp Lambda function + execution role IAM role policiesdelete-role-policy / detach IAM roles dev / prod / exec OIDC providerOnly if no other role uses it GitHub sideEnvironments dev / prod(including environment variables and approvals)Repository variable AWS_REGIONwhoami.ymldeploy.yml can be kept(it cannot run without credentials) Red = incurs charges; blue = security assets (free, but must be cleaned up)
Figure 8-1: stop the billable resources first, then reclaim identities and trust

Interactive: lab cost estimator

Unit prices are illustrative (based on public us-east-1 prices, slightly overestimated for the Canada Central region) and only help you grasp the order of magnitude. For actual costs, rely on the AWS Pricing Calculator and your billing statement.

Number of Fargate tasks: 3
vCPU per task: Memory (GB):
Running hours: 2 h
ECR storage (GB): 1

Cleanup commands

CommandPurpose
aws ecs delete-service --cluster C --service S --forceDelete the service (no need to scale to 0 first)
aws ecs wait services-inactiveWait for the service deletion to complete
aws ecs deregister-task-definition → delete-task-definitionsDeregister first, then delete the revisions
aws ecr delete-repository --repository-name myapp --forceDelete the repository along with its images
aws iam list-role-policies / list-attached-role-policiesFind the policies to delete
aws iam delete-open-id-connect-providerDelete the provider (use caution)
gh api -X DELETE repos/O/R/environments/devDelete a GitHub environment

Lab 8: one-command cleanup (about 5 minutes)

Confirm the account first The script deletes resources. Before running it, run aws sts get-caller-identity, and confirm that it is the lab account. In the script, DELETE_OIDC_PROVIDER defaults to no.
#!/usr/bin/env bash
set -uo pipefail
source ~/gh-part4.env
DELETE_OIDC_PROVIDER=${DELETE_OIDC_PROVIDER:-no}
echo "Account: $(aws sts get-caller-identity --query Account --output text)  Region: $AWS_REGION"

# 1) ECS service, task definitions, cluster
for s in myapp-dev myapp-prod; do
  aws ecs delete-service --cluster $CLUSTER --service $s --force >/dev/null 2>&1 && echo "deleting service $s"
done
aws ecs wait services-inactive --cluster $CLUSTER --services myapp-dev myapp-prod 2>/dev/null
for td in $(aws ecs list-task-definitions --family-prefix myapp --query 'taskDefinitionArns[]' --output text); do
  aws ecs deregister-task-definition --task-definition $td >/dev/null
done
INACTIVE=$(aws ecs list-task-definitions --family-prefix myapp --status INACTIVE --query 'taskDefinitionArns[]' --output text)
[ -n "$INACTIVE" ] && aws ecs delete-task-definitions --task-definitions $INACTIVE >/dev/null
aws ecs delete-cluster --cluster $CLUSTER >/dev/null && echo "cluster deleted"

# 2) ECR, logs
aws ecr delete-repository --repository-name myapp --force >/dev/null && echo "ecr deleted"
aws logs delete-log-group --log-group-name /ecs/myapp && echo "log group deleted"

# 3) Lambda (optional lab)
aws lambda delete-function --function-name myapp-fn 2>/dev/null && echo "lambda deleted"
aws logs delete-log-group --log-group-name /aws/lambda/myapp-fn 2>/dev/null

# 4) Security group (wait for the ENI to be released)
for i in 1 2 3 4 5 6; do
  aws ec2 delete-security-group --group-id $TASK_SG 2>/dev/null && { echo "sg deleted"; break; }
  echo "sg still in use, retry in 20s"; sleep 20
done

# 5) IAM roles (delete policies first)
for r in gh-myapp-dev-deploy gh-myapp-prod-deploy myappTaskExecutionRole myapp-fn-exec; do
  aws iam get-role --role-name $r >/dev/null 2>&1 || continue
  for p in $(aws iam list-role-policies --role-name $r --query 'PolicyNames[]' --output text); do
    aws iam delete-role-policy --role-name $r --policy-name $p; done
  for a in $(aws iam list-attached-role-policies --role-name $r --query 'AttachedPolicies[].PolicyArn' --output text); do
    aws iam detach-role-policy --role-name $r --policy-arn $a; done
  aws iam delete-role --role-name $r && echo "role $r deleted"
done

# 6) OIDC provider (only after confirming no other roles depend on it)
PROVIDER=arn:aws:iam::$ACCOUNT_ID:oidc-provider/token.actions.githubusercontent.com
if [ "$DELETE_OIDC_PROVIDER" = "yes" ]; then
  aws iam delete-open-id-connect-provider --open-id-connect-provider-arn $PROVIDER && echo "oidc provider deleted"
else
  echo "kept OIDC provider (set DELETE_OIDC_PROVIDER=yes to delete)"
fi

# 7) GitHub side
gh api -X DELETE repos/$GH_OWNER/myapp/environments/dev  && echo "env dev deleted"
gh api -X DELETE repos/$GH_OWNER/myapp/environments/prod && echo "env prod deleted"
gh variable delete AWS_REGION 2>/dev/null
echo "Done. Remember: git rm .github/workflows/whoami.yml"
chmod +x cleanup-gh-part4.sh && ./cleanup-gh-part4.sh
# Verify: all of the following should be empty or return NotFound
aws ecs list-services --cluster myapp-lab 2>&1 | head -2
aws ecr describe-repositories --repository-names myapp 2>&1 | head -1
aws iam list-roles --query "Roles[?starts_with(RoleName,'gh-myapp')].RoleName"
aws resourcegroupstaggingapi get-resources --tag-filters Key=course,Values=gh-part4 --query 'ResourceTagMappingList[].ResourceARN'
An error occurred (ClusterNotFoundException) when calling the ListServices operation: Cluster not found.
An error occurred (RepositoryNotFoundException) …
[]
[]

EKS access entries (if you created any): aws eks delete-access-entry --cluster-name eks-lab --principal-arn ROLE_ARN. Tag API results may lag by a few minutes.

Case 1: the bill one month after the training ended

Problem: 30 trainees each created an Express Mode service. After class, they deleted only the "service" and not the automatically created ALB and public addresses, so a month later the bill showed hundreds of dollars in load balancer and IPv4 charges. Approach: Tag all lab resources course with a tag; after class, use the tagging API to find leftovers; set budget alerts for the lab account and, optionally, Budget Actions that automatically apply a deny policy.

Case 2: deleting the wrong OIDC provider

Problem: A developer ran someone else's cleanup script in the shared dev account. It deleted the OIDC provider, which broke dev deployments across the whole company. Approach: The OIDC provider is managed by the platform team as IaC, and an SCP denies non-platform roles from calling iam:DeleteOpenIDConnectProvider; labs run in separate accounts.

Case 3: a departed employee's personal repository can still deploy

Problem: An early PoC role trusts repo:alice/poc:*, and after Alice left, her repository still existed, so the role could still be assumed. Approach: Periodically use IAM Access Analyzer to list the roles that trust external OIDC, along with their last-used time (RoleLastUsed), delete roles that have not been used for a long time, and use immutable subjects and organization ID conditions for new roles.

Common errors during cleanup

An error occurred (DependencyViolation) when calling the DeleteSecurityGroup operation: resource sg-… has a dependent object

The task ENI has not been released yet. Wait 1–2 minutes and retry (the script already includes retries). Use aws ec2 describe-network-interfaces --filters Name=group-id,Values=$TASK_SG to see what is holding it.

An error occurred (DeleteConflict) when calling the DeleteRole operation: Cannot delete entity, must delete policies first.

The role still has policies attached. First delete-role-policy (inline) and detach-role-policy (managed).

ClusterContainsServicesException: The Cluster cannot be deleted while Services are active.

The service has not finished deleting. Wait for aws ecs wait services-inactive to complete, then delete the cluster.

RepositoryNotEmptyException: The repository with name 'myapp' … cannot be deleted because it still contains images

Add --force.

Command-line exercises
1. List all roles in the account that trust GitHub OIDC.
for r in $(aws iam list-roles --query 'Roles[].RoleName' --output text); do
  aws iam get-role --role-name $r --query 'Role.AssumeRolePolicyDocument' --output json \
    | grep -q token.actions.githubusercontent.com && echo $r; done
2. Check when a given role was last used.
aws iam get-role --role-name gh-myapp-dev-deploy --query 'Role.RoleLastUsed'
Scenario analysis (self-check for this lesson)
Without looking at the slides, write out all the AWS objects and GitHub configuration needed to get a GitHub deployment to ECS working, starting from a new AWS account.

AWS: OIDC provider (URL + audience sts.amazonaws.com); deployment role (trust aud + sub, with sub pinned to the repository ID and environment); role permissions (ECR push, ECS register/update/describe, PassRole for the execution role); ECR repository (IMMUTABLE + scanning + lifecycle); ECS cluster, log group, task execution role, security group, service (circuit breaker rollback). GitHub: environment (prod approval + branch restrictions), environment variable AWS_ROLE_ARN, repository variable AWS_REGION, workflow (permissions id-token: write, build → deploy-dev → deploy-prod, Verify step, concurrency), task definition template.

Verified instructional videos

▶
Cost optimization on AWS Fargate — Containers from the Couch
English · Fargate cost optimization approaches (Spot, sizing, Graviton)

Official documentation

Video storyboard script (about 45 seconds)

Shot 1 · 0–15s
Visual: a billing meter running, with four small tables for Fargate, IPv4, ECR, and logs.
Narration: labs are cheap, but forgetting to clean up is expensive. Stop the billable resources first.
Shot 2 · 15–30s
Visual: strike through the service, cluster, repository, and log group, from top to bottom.
Narration: delete in dependency order: service, task definition, cluster, security group, then the repository and logs.
Shot 3 · 30–45s
Visual: the IAM roles and the OIDC badge are reclaimed, and the GitHub environment is deleted.
Narration: finally, revoke trust. Delete the roles, and only after confirming nobody is using it, delete the OIDC provider. Then clean up the GitHub environments and variables.
or score ≥ 70% on the quiz

Command cheat sheet

The most commonly used configuration snippets and commands for GitHub → AWS deployments
Printable

Required for workflows

permissions:
  id-token: write
  contents: read
jobs:
  deploy:
    environment: prod
    steps:
      - uses: aws-actions/configure-aws-credentials@v6
        with:
          role-to-assume: ${{ vars.AWS_ROLE_ARN }}
          aws-region: ca-central-1
          role-session-name: gh-${{ github.run_id }}
          allowed-account-ids: ${{ vars.AWS_ACCOUNT_ID }}

OIDC provider and trust policy

aws iam create-open-id-connect-provider \
  --url https://token.actions.githubusercontent.com \
  --client-id-list sts.amazonaws.com      # thumbprint can be omitted

# Trust conditions (immutable format)
"StringEquals": {
  "token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
  "token.actions.githubusercontent.com:sub":
    "repo:OWNER@OWNER_ID/REPO@REPO_ID:environment:prod" }

subject format

environment : repo:O/R:environment:prod
branch      : repo:O/R:ref:refs/heads/main
tag         : repo:O/R:ref:refs/tags/v1.0.0
PR          : repo:O/R:pull_request
immutable   : repo:O@OID/R@RID:…  (repositories created, renamed, or transferred since 2026-07-15)
When an environment is used, the sub does not contain the branch!

ECR

aws ecr create-repository --repository-name myapp \
  --image-tag-mutability IMMUTABLE --image-scanning-configuration scanOnPush=true
aws ecr describe-images --repository-name myapp --image-ids imageTag=sha-$SHA
aws ecr wait image-scan-complete --repository-name myapp --image-id imageTag=sha-$SHA
aws ecr describe-image-scan-findings --repository-name myapp --image-id imageTag=sha-$SHA \
  --query imageScanFindings.findingSeverityCounts

ECS deployment (Action)

- id: render
  uses: aws-actions/amazon-ecs-render-task-definition@v1
  with: { task-definition: .aws/task-definition.json, container-name: web, image: ${{ needs.build.outputs.image }} }
- id: deploy
  uses: aws-actions/amazon-ecs-deploy-task-definition@v2
  with:
    task-definition: ${{ steps.render.outputs.task-definition }}
    cluster: myapp-lab
    service: myapp-dev
    wait-for-service-stability: true
# Then verify that PRIMARY == steps.deploy.outputs.task-definition-arn and COMPLETED

ECS troubleshooting and rollback

aws ecs describe-services --cluster C --services S \
  --query 'services[0].deployments[].[status,taskDefinition,rolloutState,rolloutStateReason]' --output text
aws ecs describe-services --cluster C --services S --query 'services[0].events[:5].message'
aws ecs list-tasks --cluster C --service-name S --desired-status STOPPED
aws ecs update-service --cluster C --service S --task-definition myapp:N   # manual rollback

EKS

aws eks create-access-entry --cluster-name X --principal-arn ROLE_ARN
aws eks associate-access-policy --cluster-name X --principal-arn ROLE_ARN \
  --policy-arn arn:aws:eks::aws:cluster-access-policy/AmazonEKSEditPolicy \
  --access-scope type=namespace,namespaces=myapp
aws eks update-kubeconfig --name X --region ca-central-1
kubectl auth can-i patch deployments -n myapp
helm upgrade --install myapp ./chart -n myapp --rollback-on-failure --timeout 5m

Lambda

aws lambda update-function-code --function-name F --zip-file fileb://f.zip --publish
aws lambda wait function-updated-v2 --function-name F
aws lambda update-alias --function-name F --name live --function-version OLD \
  --routing-config '{"AdditionalVersionWeights":{"NEW":0.1}}'
aws lambda update-alias --function-name F --name live --function-version NEW \
  --routing-config '{"AdditionalVersionWeights":{}}'

Troubleshooting

aws iam get-role --role-name R --query Role.AssumeRolePolicyDocument
aws iam list-open-id-connect-providers
aws cloudtrail lookup-events --lookup-attributes AttributeKey=EventName,AttributeValue=AssumeRoleWithWebIdentity
aws iam simulate-principal-policy --policy-source-arn ROLE_ARN --action-names ecs:UpdateService --resource-arns SVC_ARN

Error → layer

ErrorLayer / fix
Did you mean to set the id-token permission?Token: add id-token: write
Not authorized to perform sts:AssumeRoleWithWebIdentityTrust: compare the sub
No OpenIDConnect provider foundTrust: create the provider in that account
Incorrect token audienceTrust: aud / audience list
not authorized to perform: iam:PassRolePermissions: PassRole + PassedToService
ImageTagAlreadyExists / cannot be overwrittenECR: check before you build
rolloutState FAILED / circuit breakerService: stoppedReason
EKS Unauthorized / ForbiddenAccess entry / access policy scope

Capstone lab + final quiz

myapp: CI → OIDC → ECR (immutable) → ECS Fargate (dev automatic / prod approval) → circuit breaker rollback drill → cleanup
≈ 45 minutesCost < $0.5 (clean up promptly)
Scenario

You are the owner of myapp. The security team requires: no long-lived AWS keys may be stored in GitHub; production deployments must be approved by a person and may only come from main; images must be immutable and deployed by digest; failed deployments must roll back automatically, and the pipeline must show red honestly. Complete the full pipeline in the lab account, rehearse one failed rollback, and finally clean up all resources.

Required permissions: An administrator identity in the lab account that can create IAM roles and OIDC providers, ECR, ECS, EC2 security groups, and CloudWatch Logs; and admin access to the public myapp repository on GitHub. Security risk: A broad trust policy lets other repositories gain deployment permissions. Use an exact sub. Cost: 3 tasks at 0.25 vCPU plus 3 public IPv4 addresses running for 1 hour cost on the order of $0.1; ECR and logs are negligible.

Setup: complete the pre-class setup and the Module 1 lab (cluster, log group, security group, task execution role),source ~/gh-part4.env.
Identity: create the OIDC provider; use whoami to print the sub; create gh-myapp-dev-deploy (environment:dev) and gh-myapp-prod-deploy (environment:prod), respectively attach ECR push (dev only) and the ECS deployment permissions for the matching service; set the environment variable AWS_ROLE_ARN,AWS_ACCOUNT_ID and the repository variable AWS_REGION.
Repository and services: create an IMMUTABLE ECR repository and a lifecycle policy; deploy manually once to create myapp-dev (desired 2) and myapp-prod (desired 1), both with circuit breaker rollback enabled.
Complete workflow: .github/workflows/deploy.yml
name: deploy
on:
  push:
    branches: [main]
  workflow_dispatch:
    inputs:
      crash:
        description: "Drill: deploy a revision that exits immediately (dev only)"
        type: boolean
        default: false
permissions:
  id-token: write
  contents: read
concurrency:
  group: deploy-main
  cancel-in-progress: false
env:
  ECR_REPOSITORY: myapp
  CLUSTER: myapp-lab

jobs:
  build:
    runs-on: ubuntu-latest
    environment: dev
    outputs:
      image: ${{ steps.out.outputs.image }}
    steps:
      - uses: actions/checkout@v7
      - uses: aws-actions/configure-aws-credentials@v6
        with:
          role-to-assume: ${{ vars.AWS_ROLE_ARN }}
          aws-region: ${{ vars.AWS_REGION }}
          role-session-name: gh-${{ github.run_id }}
      - id: ecr
        uses: aws-actions/amazon-ecr-login@v2
      - id: exists
        run: |
          if D=$(aws ecr describe-images --repository-name $ECR_REPOSITORY --image-ids imageTag=sha-$GITHUB_SHA \
                 --query 'imageDetails[0].imageDigest' --output text 2>/dev/null); then
            echo "found=true" >> "$GITHUB_OUTPUT"; echo "digest=$D" >> "$GITHUB_OUTPUT"
          else echo "found=false" >> "$GITHUB_OUTPUT"; fi
      - uses: docker/setup-buildx-action@v4
        if: steps.exists.outputs.found == 'false'
      - id: build
        if: steps.exists.outputs.found == 'false'
        uses: docker/build-push-action@v7
        with:
          context: .
          push: true
          provenance: false
          tags: ${{ steps.ecr.outputs.registry }}/${{ env.ECR_REPOSITORY }}:sha-${{ github.sha }}
      - id: out
        env:
          REGISTRY: ${{ steps.ecr.outputs.registry }}
          DIGEST: ${{ steps.build.outputs.digest || steps.exists.outputs.digest }}
        run: echo "image=$REGISTRY/$ECR_REPOSITORY@$DIGEST" >> "$GITHUB_OUTPUT"

  deploy-dev:
    needs: build
    runs-on: ubuntu-latest
    environment: dev
    steps:
      - uses: actions/checkout@v7
      - uses: aws-actions/configure-aws-credentials@v6
        with:
          role-to-assume: ${{ vars.AWS_ROLE_ARN }}
          aws-region: ${{ vars.AWS_REGION }}
          role-session-name: gh-${{ github.run_id }}
          allowed-account-ids: ${{ vars.AWS_ACCOUNT_ID }}
      - name: Prepare task definition (drill aware)
        env:
          CRASH: ${{ inputs.crash }}
        run: |
          if [ "$CRASH" = "true" ]; then
            jq '.containerDefinitions[0].command=["sh","-c","echo simulated crash; exit 1"]' .aws/task-definition.json > td.json
          else cp .aws/task-definition.json td.json; fi
      - id: render
        uses: aws-actions/amazon-ecs-render-task-definition@v1
        with:
          task-definition: td.json
          container-name: web
          image: ${{ needs.build.outputs.image }}
      - id: deploy
        uses: aws-actions/amazon-ecs-deploy-task-definition@v2
        with:
          task-definition: ${{ steps.render.outputs.task-definition }}
          cluster: ${{ env.CLUSTER }}
          service: myapp-dev
          wait-for-service-stability: true
          wait-for-minutes: 15
      - name: Verify
        env:
          WANT: ${{ steps.deploy.outputs.task-definition-arn }}
        run: |
          read -r GOT STATE <<< "$(aws ecs describe-services --cluster $CLUSTER --services myapp-dev \
            --query 'services[0].deployments[?status==`PRIMARY`]|[0].[taskDefinition,rolloutState]' --output text)"
          echo "want=$WANT got=$GOT state=$STATE"
          test "$GOT" = "$WANT" && test "$STATE" = "COMPLETED"

  deploy-prod:
    needs: [build, deploy-dev]
    if: github.ref == 'refs/heads/main' && inputs.crash != true
    runs-on: ubuntu-latest
    environment: prod
    steps:
      - uses: actions/checkout@v7
      - uses: aws-actions/configure-aws-credentials@v6
        with:
          role-to-assume: ${{ vars.AWS_ROLE_ARN }}
          aws-region: ${{ vars.AWS_REGION }}
          role-session-name: gh-${{ github.run_id }}
          allowed-account-ids: ${{ vars.AWS_ACCOUNT_ID }}
      - id: render
        uses: aws-actions/amazon-ecs-render-task-definition@v1
        with:
          task-definition: .aws/task-definition.json
          container-name: web
          image: ${{ needs.build.outputs.image }}
      - id: deploy
        uses: aws-actions/amazon-ecs-deploy-task-definition@v2
        with:
          task-definition: ${{ steps.render.outputs.task-definition }}
          cluster: ${{ env.CLUSTER }}
          service: myapp-prod
          wait-for-service-stability: true
          wait-for-minutes: 15
      - name: Verify
        env:
          WANT: ${{ steps.deploy.outputs.task-definition-arn }}
        run: |
          read -r GOT STATE <<< "$(aws ecs describe-services --cluster $CLUSTER --services myapp-prod \
            --query 'services[0].deployments[?status==`PRIMARY`]|[0].[taskDefinition,rolloutState]' --output text)"
          echo "want=$WANT got=$GOT state=$STATE"
          test "$GOT" = "$WANT" && test "$STATE" = "COMPLETED"

Note: the prod role needs UpdateService permission on myapp-prod UpdateService permission (Module 6). dev and prod register revisions in the same task definition family myapp, revision numbers differ but the image digest is the same. In push events, inputs.crash is empty, and inputs.crash != true holds.

Normal release: push to main → build → deploy-dev completes automatically → deploy-prod shows "Waiting for review" → approval → prod completes. Verify that both services run the same digest:
for s in myapp-dev myapp-prod; do
  TD=$(aws ecs describe-services --cluster myapp-lab --services $s --query 'services[0].taskDefinition' --output text)
  echo "$s $(aws ecs describe-task-definition --task-definition $TD --query 'taskDefinition.containerDefinitions[0].image' --output text)"
done
myapp-dev  111122223333.dkr.ecr.ca-central-1.amazonaws.com/myapp@sha256:9b1c…e04
myapp-prod 111122223333.dkr.ecr.ca-central-1.amazonaws.com/myapp@sha256:9b1c…e04
Circuit breaker rollback drill:
gh workflow run deploy.yml -f crash=true
gh run watch $(gh run list --workflow deploy.yml -L1 --json databaseId -q '.[0].databaseId')
aws ecs describe-services --cluster myapp-lab --services myapp-dev \
  --query 'services[0].deployments[].[status,taskDefinition,rolloutState,rolloutStateReason]' --output text

Expected: build skips the build step (the image already exists); the new deploy-dev task exits right after it starts, and the circuit breaker marks the deployment FAILED and rolls it back within a few minutes; the Verify step fails (want=:N+1, got=:N), and the workflow turns red; deploy-prod does not run. The stopped task's stoppedReason is Essential container in task exited (the actual value may vary).

Privilege and approval verification: confirm that the dev job cannot assume the prod role (Module 6 privilege test). In CloudTrail, find the AssumeRoleWithWebIdentity and the session name gh-RUNID for the prod deployment.
Cleanup: run theModule 8 cleanup script cleanup-gh-part4.sh, and use the tagging API to confirm that nothing remains.
Acceptance checklist

Open-ended self-check (6 questions)

1. In your own words, explain why GitHub environment approval is only meaningful when it works together with the environment:prod condition in the AWS trust policy?

Approval only controls whether a job can start. Only when the AWS side requires the sub to contain environment:prod, can you ensure that credentials are issued only to jobs that passed approval. If either one is missing, the other side can be bypassed.

2. A repository created in 2025 was transferred to a new organization in 2026-09, and deployments started failing. Give the diagnosis and fix steps.

After the transfer, the subject switches to the immutable format (and the owner has changed). Use whoami to print the new sub; update the trust policy (use a StringLike array during the transition period); if the transfer crosses organizations, also check the organization-level condition (repository_owner_id).

3. Compare ECS rolling updates with the circuit breaker against native ECS blue/green deployments. What is each one suited for?

Rolling update + circuit breaker: simple and light on resources, suitable for most internal services. Blue/green: you can validate with test traffic before shifting traffic, and roll back within seconds during the bake time; suitable for external services with high availability and fast rollback requirements, but resources double during deployment and it requires ALB, Service Connect, or similar components.

4. Why should the CI role be separate from the ECS task role and execution role? What risks come with merging them?

The CI role handles deployment (register, update, PassRole), and the runtime role handles the application's access to AWS. Merging them would give the application container deployment permissions (so a compromise could change deployments), or give CI access to application data, which violates least privilege.

5. Design a trust policy for "all repositories in the organization can deploy to the sandbox account, but only through the platform team's standard workflow".

Conditions: aud = sts.amazonaws.com; repository_owner_id = organization ID; environment = sandbox; job_workflow_ref = the path of the platform's reusable workflow and a protected ref; keep the StringLike constraint on sub limited to this organization.

6. Your workflow gets Forbidden when deploying to EKS, but deploying to ECS works. List your troubleshooting order.

Confirm that get-caller-identity returns the expected role → list-access-entries includes that role → check the policies and namespace scope from list-associated-access-policies → kubectl auth can-i for the specific verb and resource → determine whether custom RBAC (kubernetes-groups) is needed.

Sources and version notes

Verification basis for all technical facts in this lesson (verified on 2026-11-15)
TopicVerified conclusionSource (accessed 2026-11-15)
configure-aws-credentialsv6.3.0 (tag SHA e1253824…),using: node24; OIDC requires id-token: write; audience defaults to sts.amazonaws.com; role-duration-seconds defaults to 3600, range 900–43200; thumbprint "will be ignored if specified"; warns against using ForAllValues; the README explains the immutable sub from 2026-07-15 and the corresponding errors; supports allowed-account-ids,role-chainingREADME · action.yml · git ls-remote
GitHub OIDCissuer https://token.actions.githubusercontent.com sub formats for environment, branch, tag, and PR; immutable subject repo:OWNER@ID/REPO@ID:…: repositories created after 2026-07-15 use it by default, repositories renamed or transferred afterward also switch, and older repositories can opt in at the organization or repository level; not applicable to GHES; sub template customization APIOIDC reference · OIDC in AWS
IAM OIDC providerAWS validates the JWKS endpoint certificate against trusted root CAs and falls back to the thumbprint only in specific cases; a provider supports up to 100 audiences and 5 thumbprints; the provider referenced in a trust policy must be in the same account as the roleCreate an OIDC identity provider
GitHub-specific condition keysOn 2026-02-02, AWS announced that STS validates IdP-specific claims. The IAM documentation lists the GitHub keys: actor, actor_id, job_workflow_ref, repository, repository_id, repository_owner_id, workflow, ref, environment, enterprise_idWhat's New · IAM condition keys
Session duration and role chainingAssumeRole duration is up to 12 hours (limited by the role's MaxSessionDuration); role chaining sessions last at most 1 hour, and anything longer fails immediatelyIAM roles terms
amazon-ecr-loginLatest v2.1.7 (tag SHA 03f1aad4…), node24; mask-password defaults to true; registry-type defaults to private; output registryReleases · action.yml
ECS render / deployrender v1.9.1 (node24; inputs include image, environment-variables, secrets, command, and so on); deploy v2.6.4 (node24,wait-for-minutes defaults to 30, maximum 6 hours; output task-definition-arn; minimum permissions: RegisterTaskDefinition, UpdateService, DescribeServices, PassRole)deploy README · render README · action.yml
ECS deployment behaviorRolling deployments can use the circuit breaker and CloudWatch alarms to detect failures and roll back; image tags resolve to a digest by default (versionConsistency); native blue/green includes bake time and lifecycle hooks (Lambda or pause)Rolling update · Blue/green
App Runner / Express ModeApp Runner no longer accepts new customers; existing customers can keep using it, but it gets no new features; ECS Express Mode is recommended (an image plus two IAM roles; Express Mode itself is free); GitHub Action amazon-ecs-deploy-express-service latest v1.2.2. The stop-accepting date 2026-04-30 comes from the verification record of the Docker lesson in the same repository (the document page itself does not state a date)App Runner availability change
aws-lambda-deployLatest tag v1.1.2 (README example uses v1.1.0), node24; package-type Zip/Image, publish defaults to true, dry-run, output versionREADME · action.yml
GitHub environmentsRequired reviewers and wait timers under Free/Pro/Team are available only for public repositories; deployment branch restrictions are available for private repositories on Pro/Team; up to 6 reviewers; under Free, environment secrets are only available for public repositoriesDeployments and environments
Other Action versionsactions/checkout v7.0.1, docker/build-push-action v7.4.0, docker/setup-buildx-action v4.4.1 (git ls-remote --tags)GitHub repository tags

Video verification notes

The following videos had their titles and channels verified through the YouTube oEmbed API on 2026-11-15: AWS Developers, "Deploying a Modern Application Stack to AWS Fargate with Amazon ECS - AWS Online Tech Talks" (Nv7s-N8ZxQA), "The Complete Guide to ECS Blue/Green Deployments on AWS" (xnHD_dCzE_E), "Amazon EKS Auto Mode | Fully Automated Kubernetes Clusters" (s9d61eYkGzs); Amazon Web Services, "Amazon Elastic Container Registry (Amazon ECR) Explained" (GtbTmvMcKRg); AWS Events, "AWS re:Invent 2023 - Dive deep into Amazon ECR (CON405)" (PHuKrcsAaDw), "AWS re:Invent 2025 - Deep Dive: ECS Managed Instances & Blue/Green for Resilient Services (CNS416)" (88PFI55eKzs), "AWS re:Invent 2024 - Unleashing the power of Amazon ECS for platform teams (SVS330)" (T-fFyEsLXXE); Containers from the Couch, "Circuit Breakers for Amazon ECS" (Y2Ez9M7A95Y), "EKS Pod Identity vs IRSA" (aUjJSorBE70), "Cost optimization on AWS Fargate" (Cnmejv98sv0); TechWorld with Nana, "AWS EKS - Create Kubernetes cluster on Amazon EKS | the easy way" (p6xDCz00TxU), "GitHub Actions Tutorial - Basic Concepts and CI/CD Pipeline with Docker" (R8_veQiYBjI); Bret Fisher, "Serverless for container fans via Amazon ECS and AWS Lambda" (7fjJqokRlKI); Be A Better Dev, "How to Setup AWS ECS Fargate with a Load Balancer | Step by Step" (o7s-eigrMAI). No verified video matching the 2026 immutable subject format for GitHub to AWS OIDC was found, so the related module provides a storyboard script instead.

Audio narration notes

The "Audio" tab uses the browser's Web Speech API (speechSynthesis, en-US) to read the narration script aloud in real time, and English terms are pronounced with en-US. The result depends on the voices installed on the system. This courseware has no embedded MP3; for offline audio, pass the narration script to any TTS tool to generate it.

Known limitations

  • Account numbers 111122223333, owner/repo IDs 123456/789012, digests, revision numbers, IP addresses, and times are all example values.
  • The exact wording of Action logs and AWS event messages may change slightly between versions; for outputs labeled "example" in the text, the actual output takes precedence. For circuit breaker thresholds and the specific fields for blue/green, linear, and canary deployments, refer to the official ECS documentation.
  • Cost figures are order-of-magnitude estimates that exclude taxes and free tiers; the AWS Pricing Calculator and your bill are authoritative.
  • To save costs, the labs use the default VPC public subnets, tasks with public IPs, and no ALB. This does not meet a production security baseline. For production architecture, see Docker Lesson 4.
  • The multi-account part is simulated in a single account; a real multi-account setup requires AWS Organizations and an OIDC provider in each account. The EKS part depends on the cluster from K8s Lesson 7 and only provides commands and reading material.
  • GitHub-specific claim keys in organization-level trust are a new 2026 feature. Before relying on a claim value format, first confirm it by printing it with the whoami workflow.