GitHub Hour 4: Moving to the Cloud (AWS)
- 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/subconditions 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-loginto 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:AssumeRoleWithWebIdentityand similar typical errors.
1-hour time plan
| # | Time | Module | Core content | Animation / interaction | Lab (AWS account · ca-central-1) |
|---|---|---|---|---|---|
| 0 | Before class | Warm-up and AWS setup | AWS CLI v2, lab IAM identity, budget alert, get owner/repo numeric IDs | OIDC prerequisite self-check | aws sts get-caller-identity |
| 1 | 00–05 | Choosing an AWS deployment architecture | ECS Fargate / Express Mode / EKS / Lambda; App Runner status; GitHub Actions needed | Architecture decision tool | Confirm region and quotas |
| 2 | 05–14 | OIDC federation: GitHub → IAM | OIDC provider, trust policy aud/sub, immutable subject,configure-aws-credentials@v6, session duration, and role chaining | Core animation: OIDC → STS token exchange (including failure scenarios) | Create OIDC provider + role, have the workflow print its identity |
| 3 | 14–21 | Build and push to ECR | amazon-ecr-login@v2, IMMUTABLE, scan on push, digest, lifecycle policy | Tag vs digest push simulation | CI push sha- tag |
| 4 | 21–30 | Deploy to ECS on Fargate | Render task definition, deploy service, wait for stability, circuit-breaker rollback, native blue/green | Rolling deployment + circuit breaker state machine | Workflow deploys myapp-dev |
| 5 | 30–38 | Deploy to EKS and Lambda | EKS access entries, update-kubeconfig, kubectl/helm; Lambda image/zip, versions and weighted aliases | Lambda alias traffic shifting | (Optional) Lambda alias 10% canary |
| 6 | 38–45 | Multi-account and environment promotion | Account isolation, one role per environment, environment approvals, organization-level trust (repository_owner_id) | Promotion pipeline and trust matrix | prod role trusts only environment:prod |
| 7 | 45–54 | Troubleshooting cloud deployments | AssumeRoleWithWebIdentity denied, No OpenIDConnect provider, ECR login, ECS stuck, EKS Unauthorized | Interactive troubleshooting tree | Deliberately cause a sub mismatch and fix it |
| 8 | 54–60 | Cost, cleanup and self-check | Cost breakdown, cleanup order, safe removal (roles, providers, repository variables) | Cost estimator | One-click cleanup script |
| — | After class | Cheat sheet · Capstone lab | CI → OIDC → ECR (immutable) → ECS (dev automatic / prod approval) → circuit-breaker rollback → cleanup | Final quiz (12 questions) | Capstone lab |
Knowledge Coverage Matrix
| Target skill | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands / Action | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Choose an AWS compute service by scenario | ✓ | · | · | ✓ | ✓ | · | · | ✓ | Decision table | M1 |
| No keys: OIDC → STS temporary credentials | · | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | · | configure-aws-credentials@v6 | M2 |
| Write a minimal working trust policy (aud/sub/immutable format) | · | ✓ | · | · | · | ✓ | ✓ | · | aws iam create-role | M2/M6 |
| Push immutable images and reference them by digest | · | · | ✓ | ✓ | ✓ | · | ✓ | · | amazon-ecr-login@v2,docker/build-push-action | M3 |
| ECS deployment, wait for stability, circuit-breaker rollback | · | · | · | ✓ | · | ✓ | ✓ | · | amazon-ecs-deploy-task-definition@v2 | M4 / capstone |
| EKS access entries and CI deployment | · | · | · | · | ✓ | · | ✓ | · | aws eks create-access-entry | M5 (reading) |
| Lambda version/alias progressive rollout | ✓ | · | · | · | ✓ | · | · | · | aws lambda update-alias --routing-config | M5 (optional) |
| Multi-account, environment approvals and promotion | · | ✓ | · | · | · | ✓ | · | · | environment:,vars.AWS_ROLE_ARN | Capstone |
| Troubleshooting cloud deployment failures | · | ✓ | ✓ | ✓ | ✓ | · | ✓ | · | CloudTrail,describe-services | M7 |
| Cost control and full cleanup | · | · | ✓ | · | · | · | · | ✓ | aws ecs delete-service --force | M8 |
Topics not covered in this lab (and where to learn them)
| Topic | Why it is not in this lab | Where to learn it |
|---|---|---|
| Dockerfile, multi-stage builds, ECS task definition fields and ALB details | Containers are covered in the Docker course; this lab only covers how GitHub drives them | Docker Lesson 4 (AWS ECS/ECR/EKS) |
| EKS cluster creation, VPC CNI, Karpenter, Pod Identity | Belongs to Kubernetes platform operations | K8s Lesson 7 (EKS) |
| Managing OIDC providers, roles and ECS resources with Terraform | This lab uses the CLI so every step is visible; production should use IaC | Terraform course Lesson 4 (AWS) |
| Azure federated credentials (Entra workload identity) | Covered in the previous lesson; this lab maps one-to-one to it | Lesson 3 (Azure) |
| Reusable workflows, artifact attestations, pinning Action SHAs and hardening | Belongs to the 'production-grade Actions' topic | Lesson 5 |
| Git credentials, branches and merging | Covered in the Git course | Git 8-hour course |
How to use these course materials
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.
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).
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.
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)
- 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
myapprepository (the Flask + gunicorn app from the Docker course, listening on 5000, serving/healthz, with the Dockerfile in the repository root)./healthzIt does not depend on Redis, and this lab does not deploy Redis, so the page showinghits=N/Ais 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,
ghCLI (alreadygh 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 identity | IAM role | Cloud identity that a GitHub workload assumes |
| Federated identity credential (issuer + subject + audience) | IAM OIDC identity provider + role trust policy conditions | AWS splits 'who to trust' into two layers: an account-level provider + role-level conditions |
azure/login@v3 | aws-actions/configure-aws-credentials@v6 | both are needed permissions: id-token: write |
audience api://AzureADTokenExchange | audience sts.amazonaws.com | Action defaults; no need to write manually |
| ACR / Container Apps / AKS | ECR / ECS Fargate / EKS | Image 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"
}
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.
Module 1 · Choosing an AWS deployment architecture
- 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.
What: four mainstream destinations
| ECS on Fargate | ECS Express Mode | EKS | Lambda | |
|---|---|---|---|---|
| What you deliver | Image + task definition JSON + service configuration | Image + two IAM roles (one API call) | Image + Kubernetes manifests / Helm chart | Zip package or container image + function configuration |
| What AWS manages for you | Servers, scheduling, rolling deployments | On top of ECS, automatically creates an ALB (with TLS), auto scaling, networking, logging | Control plane (Auto Mode also manages nodes) | All servers and scaling; billed per request |
| GitHub deployment Action | amazon-ecs-render-task-definition@v1 + amazon-ecs-deploy-task-definition@v2 | amazon-ecs-deploy-express-service@v1 | No official dedicated Action: aws eks update-kubeconfig + kubectl/helm | aws-lambda-deploy@v1 or AWS CLI / SAM |
| Core permissions needed by the CI role | ecs:RegisterTaskDefinition,ecs:UpdateService,ecs:DescribeServices,iam:PassRole | create/update of Express services + iam:PassRole | eks:DescribeCluster + EKS access entries (Kubernetes permissions) | lambda:UpdateFunctionCode,PublishVersion,UpdateAlias |
| Typical cost starting point | Billed by task vCPU/memory-seconds | Express Mode itself is free; you pay only for the underlying resources (Fargate, ALB, etc.) | Cluster hourly fee + nodes/Fargate | Requests + 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)
| Need | Azure | AWS |
|---|---|---|
| Managed containers, least operations | Container Apps | ECS Express Mode / ECS on Fargate |
| Managed Kubernetes | AKS | EKS |
| Functions | Functions | Lambda |
| Image registry | ACR | ECR |
| CI identity | Entra federated credential | IAM OIDC provider + role |
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
Decision flow
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.
Core commands: survey the foundation of the account
| Command | Purpose | Notes |
|---|---|---|
aws ec2 describe-vpcs --filters Name=is-default,Values=true | Find the default VPC | This lab uses the public subnets of the default VPC, avoiding NAT gateway charges |
aws ecs create-cluster --cluster-name myapp-lab | Create ECS cluster | The 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-3032A538 | Check Fargate on-demand vCPU quota | New account quotas may be low; check before large deployments |
aws apprunner list-services | Check whether you are an existing App Runner customer | Calls 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 step | Requires --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)
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.
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).
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/AmazonECSTaskExecutionRolePolicycat > ~/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
aws 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).
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
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
Official documentation
- AWS App Runner availability change (including the migration to ECS Express Mode guide)
- Amazon ECS Express Mode
- GitHub Docs: Deploying to Amazon ECS
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.
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.
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.
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.
Module 2 · OIDC federation: GitHub → IAM
- Create an IAM OIDC identity provider (URL
https://token.actions.githubusercontent.com, audiencests.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:audand:subconditions, 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@v6ofrole-to-assume,role-duration-seconds,role-session-name,role-chainingand know that session duration and role chaining are capped at 1 hour.
What: three things
| Object | Location | Purpose | Key value |
|---|---|---|---|
| IAM OIDC identity provider | One 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 account | URL https://token.actions.githubusercontent.com; audience (client ID) sts.amazonaws.com |
| IAM role + trust policy | One per repository/environment (least privilege) | Specifies which tokens may assume this role | Principal.Federated = provider ARN; Action = sts:AssumeRoleWithWebIdentity; Condition checks aud and sub |
| Workflow permissions | workflow or job level permissions | Allows the runner to request an OIDC token from GitHub | id-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
AssumeRoleWithWebIdentityevent records the token's subject and other details; the role session name defaults toGitHubActions(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
- the job declares
id-token: write, so the runner getsACTIONS_ID_TOKEN_REQUEST_URLandACTIONS_ID_TOKEN_REQUEST_TOKENenvironment variables. configure-aws-credentialsUse them to request a JWT from the GitHub OIDC service; the audience defaults tosts.amazonaws.com.- GitHub issues the JWT with
iss=https://token.actions.githubusercontent.comas issuer, containingsub,aud,repository,repository_id,repository_owner_id,ref,environment,job_workflow_refand other claims. - The Action calls STS
AssumeRoleWithWebIdentity(this call itself needs no AWS credentials), passing RoleArn, the token, session name and duration. - STS uses
issto find this account's OIDC provider, fetches the JWKS to verify the signature and validity period, and checks whether theaudis in the provider's audience list. - STS evaluates the trust policy conditions (
aud,sub, and the GitHub-specific claim keys supported since 2026). - 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 subsequentawsCLI / 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)
| Trigger | Legacy format (created before 2026-07-15 and not opted in) | Immutable format (new repository / renamed / transferred / opted in) |
|---|---|---|
Job references environment | repo:octo-dev/myapp:environment:prod | repo:octo-dev@123456/myapp@789012:environment:prod |
| Push to a branch (no environment) | repo:octo-dev/myapp:ref:refs/heads/main | repo:octo-dev@123456/myapp@789012:ref:refs/heads/main |
| Push a tag | repo:octo-dev/myapp:ref:refs/tags/v1.2.0 | repo:octo-dev@123456/myapp@789012:ref:refs/tags/v1.2.0 |
| pull_request event (no environment) | repo:octo-dev/myapp:pull_request | repo:octo-dev@123456/myapp@789012:pull_request |
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_idand 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
| Parameter | Default / range | Notes |
|---|---|---|
role-duration-seconds | Default 3600 (1 hour), can be set to 900–43200 | Cannot 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: true | Use the credentials already in the current environment to call AssumeRole another role | IAM rule: role-chained sessions last at most 1 hour, so requests longer than 1 hour fail outright |
role-session-name | Default GitHubActions | recommended to set to gh-${{ github.run_id }}, so runs can be correlated in CloudTrail |
audience | Default sts.amazonaws.com | If you change it, the OIDC provider's audience list and the aud condition in the trust policy must both be updated |
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
Anatomy of a trust policy
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.
Core commands and parameters
| Command / input | Purpose | Key parameters / notes |
|---|---|---|
aws iam create-open-id-connect-provider | Create 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-providers | List existing providers | If it already exists, creating it again reports an error EntityAlreadyExists |
aws iam create-role --assume-role-policy-document | Create the CI role | --max-session-duration 3600 (seconds, 1–12 hours) |
aws iam update-assume-role-policy | Update the trust policy | Use it when changing the format (legacy → immutable); it takes effect within seconds |
gh variable set AWS_ROLE_ARN | Write the role ARN to repository/environment variables | --env dev Write to an environment-level variable |
role-to-assume | ARN of the role to assume | Required for OIDC mode |
aws-region | Region | Required; this lesson uses ca-central-1 |
role-duration-seconds / role-session-name / role-chaining | Session control | See the principles page |
mask-aws-account-id | Mask the account number in logs | Consider 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)
gh api -X PUT repos/$GH_OWNER/myapp/environments/dev gh api -X PUT repos/$GH_OWNER/myapp/environments/prod
.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.
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
- 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"
}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.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.
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.json2. 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
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.
Official documentation
- GitHub Docs: Configuring OpenID Connect in Amazon Web Services
- GitHub Docs: OpenID Connect reference (claims, subject formats, immutable subjects)
- aws-actions/configure-aws-credentials README
- IAM: Create an OIDC identity provider (thumbprint notes)
- IAM: Available keys for OIDC federation (GitHub-specific keys)
Video storyboard script (about 90 seconds)
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.
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.
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.
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.
Module 3 · Build and push to ECR
- 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
IMMUTABLEthe impact of tags on CI (re-running the same commit fails to push), and design ansha-<commit>tag strategy. - From
docker/build-push-actionget the digest, and use the digest in later deployments;repo@sha256:…read the scan results at push time.
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:
| Input | Default | Description |
|---|---|---|
registries | Current account | Comma-separated account IDs, used to log in to multiple (including cross-account) registries |
registry-type | private | public When logging in to ECR Public (public.ecr.aws, only fetches the token in us-east-1) |
mask-password | true (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-logout | false | Logs out by default at the end of the job |
Why: immutable tags + digest
- The risk of mutable tags:
myapp:latestToday 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-3f2a9c1once it exists, it always refers to the same content. You can also useIMMUTABLE_WITH_EXCLUSIONto keep a few tags (such aslatest) 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
configure-aws-credentialsGet temporary credentials.amazon-ecr-loginLog in withregistry, which outputs- (optional) First
aws ecr describe-imagesto check whethersha-${GITHUB_SHA}already exists; if it does, skip the build to avoid hitting IMMUTABLE on a re-run. docker/build-push-actionBuild and push, outputdigest.- 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-findingsorwait image-scan-complete, and decide whether to block based on severity. - Pass
registry/myapp@digestto the deployment job as a job output.
Minimum-privilege policy (CI role)
| Action | Resource | Why |
|---|---|---|
ecr:GetAuthorizationToken | * | This API does not support resource-level permissions |
ecr:BatchCheckLayerAvailability,InitiateLayerUpload,UploadLayerPart,CompleteLayerUpload,PutImage | repository ARN | Push image layers and manifests |
ecr:BatchGetImage,GetDownloadUrlForLayer,DescribeImages,DescribeImageScanFindings | repository ARN | Pull cache, check whether it exists, read scan results |
Comparison with Azure (Lesson 3)
| ACR | ECR | |
|---|---|---|
| Login | az acr login (after azure/login) | amazon-ecr-login@v2 |
| Tag protection | Lock a single tag/manifest (az acr repository update --write-enabled false) | Repository-level IMMUTABLE (with optional exception filters) |
| Scanning | Defender for Containers | Basic scanning / Inspector enhanced scanning |
From commit to digest
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.
Core commands and parameters
| Command | Purpose | Notes |
|---|---|---|
aws ecr create-repository --image-tag-mutability IMMUTABLE --image-scanning-configuration scanOnPush=true | Create an immutable repository that scans on push | The encryption method cannot be changed after creation |
aws ecr put-registry-scanning-configuration | Registry-level scanning rule (recommended) | --scan-type BASIC|ENHANCED |
aws ecr describe-images --image-ids imageTag=sha-… | Check whether the tag exists | Returns ImageNotFoundException |
aws ecr wait image-scan-complete | when it does not exist; wait for the scan to complete | then describe-image-scan-findings |
aws ecr put-lifecycle-policy | Automatically clean up old images | Keep only the most recent N sha-* |
aws iam put-role-policy | Add an inline policy to the CI role | This 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)
.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.
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 | +--------------------------------------+-------------------------+--------------+
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.
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'
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
Official documentation
Video storyboard (about 60 seconds)
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.
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.
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.
Module 4 · Deploy to ECS on Fargate
- Use
amazon-ecs-render-task-definition@v1to write the digest into the task definition, and useamazon-ecs-deploy-task-definition@v2to register a revision and update the service. - Write the minimum ECS deployment permissions for the CI role, and understand
iam:PassRolewhy they are needed and how to useiam:PassedToServiceto 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.
What: the split of work between the two official Actions
| Action | What it does | Key inputs | Outputs |
|---|---|---|---|
amazon-ecs-render-task-definition@v1 | Only edits the file, no API calls: Replaces the image in the specified container with the new value, producing a temporary task definition file | task-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@v2 | RegisterTaskDefinition → 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-deployment | task-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
- Register a new revision
myapp:N+1(image =…/myapp@sha256:…). UpdateServiceCreate a new deployment (PRIMARY), and the old one becomes ACTIVE; rolloutState =IN_PROGRESS.- Start new tasks based on
maximumPercent/minimumHealthyPercent; once new tasks pass container health checks (and ALB health checks, if any), stop the old tasks. - When all replacements are complete → rolloutState =
COMPLETED, and the eventhas reached a steady state. - Circuit breaker: if new tasks repeatedly fail to reach RUNNING or fail health checks, once the failure count reaches the threshold, rolloutState =
FAILED; withrollback=trueenabled, 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).
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
| Action | Resource | Notes |
|---|---|---|
ecs:RegisterTaskDefinition,ecs:DescribeTaskDefinition | * | No revision ARN exists at registration time, and the official README also uses * |
ecs:UpdateService,ecs:DescribeServices | arn:aws:ecs:REGION:ACCT:service/myapp-lab/myapp-dev | Can only deploy this one service |
iam:PassRole | ARN 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
| Approach | Mechanism | GitHub side |
|---|---|---|
| Rolling + circuit breaker (this lesson) | ECS deployment controller replaces tasks in batches; automatic rollback on failure | deploy 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 ContinueServiceDeployment | The 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 group | the deploy Action's codedeploy-* inputs |
: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
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.
Core commands and parameters
| Command | Purpose | Notes |
|---|---|---|
aws ecs create-service … --deployment-configuration "…deploymentCircuitBreaker={enable=true,rollback=true}" | Create the service once | Updated by the workflow afterward |
aws ecs describe-services --query 'services[0].deployments' | Check PRIMARY/ACTIVE and rolloutState | Circuit breaker info is in rolloutStateReason |
aws ecs list-service-deployments / describe-service-deployments | Service deployment history (including rollback records) | More structured than events |
aws ecs wait services-stable | Wait for stability | the deploy Action uses the same kind of waiter internally |
aws ecs update-service --task-definition myapp:6 | Manual rollback | Just specify the old revision |
aws ecs describe-tasks --query 'tasks[].stoppedReason' | See why tasks stopped | First 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)
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
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
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)
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.
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
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
Official documentation
- amazon-ecs-deploy-task-definition · amazon-ecs-render-task-definition
- ECS: How the deployment circuit breaker detects failures
- ECS: Blue/green deployments
Video storyboard (about 75 seconds)
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.
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.
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.
Module 5 · Deploy to EKS and Lambda
- 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-kubeconfigto generate a kubeconfig, and usekubectl set imageorhelm upgrade --install --rollback-on-failureto deploy by digest. - Use
aws-actions/aws-lambda-deploy@v1or 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.
What: EKS's two gates
| Layer | Who decides | What CI needs | Error on failure |
|---|---|---|---|
| AWS API | IAM | eks:DescribeCluster (update-kubeconfig uses it to get the endpoint and CA) | AccessDeniedException … eks:DescribeCluster |
| Kubernetes API | EKS 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)
| Policy | Roughly equivalent to | For CI? |
|---|---|---|
AmazonEKSClusterAdminPolicy | cluster-admin | No |
AmazonEKSAdminPolicy | admin (can manage RBAC within the namespace) | Usually not needed |
AmazonEKSEditPolicy | edit (can modify most namespace resources) | Recommended, scoped to the application namespace |
AmazonEKSViewPolicy | view | Read-only check job |
What: Lambda versions and aliases
- $LATEST: a mutable "working copy" that
UpdateFunctionCodechanges. - Version (version):
PublishVersiongenerates 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 setAdditionalVersionWeights, 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@v1 | AWS CLI | |
|---|---|---|
| Update code | package-type: Zip + code-artifacts-dir, or package-type: Image + image-uri | aws lambda update-function-code --zip-file / --image-uri |
| Publish version | publish Default true, outputs version | --publish or aws lambda publish-version |
| Switch alias | The Action does not switch aliases; use the CLI afterward | aws lambda update-alias --routing-config |
| Other | dry-run validates permissions; optionally via s3-bucket upload | SAM/CodeDeploy can automate ones like Canary10Percent5Minutes, etc. |
EKS: from OIDC temporary credentials to kubectl apply
Lambda: versions and aliases
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.
EKS: authorize the CI role and deploy
| Command | Purpose | Notes |
|---|---|---|
aws eks describe-cluster --query cluster.accessConfig | Check the authentication mode | Requires API or API_AND_CONFIG_MAP |
aws eks create-access-entry --principal-arn ROLE_ARN | Create an access entry for the CI role | --type STANDARD (default) |
aws eks associate-access-policy --access-scope type=namespace,namespaces=myapp | Associate access policy | CI gets only the application namespace |
aws eks update-kubeconfig --name eks-lab | Generate kubeconfig | AWS CLI and kubectl are preinstalled on the runner (see the runner image manifest) |
kubectl auth can-i | Verify 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
| Command | Purpose |
|---|---|
aws lambda update-function-code --function-name F --zip-file fileb://f.zip --publish | Update code and publish a version (for container images, use --image-uri …@sha256:…) |
aws lambda wait function-updated-v2 --function-name F | Wait 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).
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", … }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:*\"]}]}"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}}]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":{}}' # rollbackCase 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.
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}}'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
No verified video on "GitHub Actions + Lambda alias weighting" was found; please refer to the documentation and storyboard below.
Official documentation
- EKS: Grant IAM users access to Kubernetes with EKS access entries
- Lambda: Implement Lambda canary deployments using a weighted alias
- aws-actions/aws-lambda-deploy
Video storyboard (about 60 seconds)
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.
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.
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.
Module 6 · Multi-account and environment promotion
- 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 variableAWS_ROLE_ARN. - Use the GitHub environment's required reviewers and deployment branch restrictions to protect prod, and use
allowed-account-idsto 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_reforg-level trust patterns.
What: recommended account and identity layout
| Account | What it holds | GitHub side | Sub trusted by the role |
|---|---|---|---|
| shared-services (tooling account) | ECR (single image source), optional central CI role | build job (environment: build or branch-restricted) | repo:org@OID/myapp@RID:environment:build |
| dev | ECS cluster/service myapp-dev | environment: dev (automatic) | …:environment:dev |
| stage | myapp-stage | environment: stage (main only) | …:environment:stage |
| prod | myapp-prod | environment: 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:prodonly 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-RUNIDmaps directly to one approved run.
How: GitHub environment protection rules (availability verified)
| Rule | Effect | Plan restrictions |
|---|---|---|
| Required reviewers | Up 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 timer | Starts only after N minutes of delay | Same as above |
| Deployment branches and tags | Only allow main or v* tags to deploy to this environment | Available for all public repositories; also available for Pro/Team private repositories |
| Environment variables / secrets | vars.AWS_ROLE_ARN Scoped per environment | On 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 | |
|---|---|---|
| Approach | Create an OIDC provider and environment role in each account; the job calls AssumeRoleWithWebIdentity | Create 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) |
| Pros | Short chain; sub conditions apply directly in the target account; sessions can last up to 12 hours | OIDC trust managed centrally |
| Cons | Each 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 examplemy-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.
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
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.
Core commands and configuration
| Command / configuration | Purpose |
|---|---|
gh api -X PUT repos/OWNER/myapp/environments/prod --input prod-env.json | Set reviewers and deployment branch policy |
gh api -X POST repos/OWNER/myapp/environments/prod/deployment-branch-policies -f name=main -f type=branch | Only 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-policy | Shared-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.
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
myapp-prod, and desired-count set to 1 to save money).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>gh run list --workflow deploy.yml -L1 gh api repos/$GH_OWNER/myapp/actions/runs/RUN_ID/pending_deployments --jq '.[].environment.name'
prod
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.
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'
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:
Official documentation
- GitHub Docs: Deployments and environments
- AWS What's New (2026-02-02): STS supports validating IdP-specific claims
- IAM: Roles terms and concepts (role chaining 1 hour)
Video storyboard (about 60 seconds)
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.
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.
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.
Module 7 · Hands-on cloud deployment troubleshooting
- 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
AssumeRoleWithWebIdentityevents,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 EKSUnauthorized.
Four-layer troubleshooting model
| Layer | Typical errors | Primary evidence | Common root causes |
|---|---|---|---|
| (1) GitHub token | Did you mean to set the `id-token` permission?,Could not load credentials from any providers | the 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 trust | Not authorized to perform sts:AssumeRoleWithWebIdentity,No OpenIDConnect provider found,Incorrect token audience,DurationSeconds exceeds | the sub printed by whoami; get-role 's trust policy; CloudTrail | sub format (old vs. immutable, environment vs. branch), provider not in that account, aud, duration |
| (3) IAM permissions | is not authorized to perform: ecr:… / ecs:… / iam:PassRole | The Action and Resource ARN in the error; simulate-principal-policy | missing action, wrong region or name in Resource, PassRole, SCP or permissions boundary denial |
| (4) Service behavior | CannotPullContainerError,ResourceInitializationError, circuit breaker FAILED,Unauthorized (EKS) | ECS service events,stoppedReason, CloudWatch logs, EKS access entries | image, 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 includeassumedRoleUser, and failed events haveerrorCode/errorMessage; subsequent service calls are recorded asassumed-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 ofallowed/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-servicestheevents,deployments[].rolloutStateReason; fromdescribe-tasks, thestoppedReasonand the containerreason/exitCode. - GitHub debug logs: when re-running, check "Enable debug logging", or set the repository variable or secret
ACTIONS_STEP_DEBUG=true.
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
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
| Scenario | Command |
|---|---|
| View trust policy | aws iam get-role --role-name R --query Role.AssumeRolePolicyDocument |
| View provider | aws iam list-open-id-connect-providers; get-open-id-connect-provider --open-id-connect-provider-arn … |
| Look up STS events in CloudTrail | aws cloudtrail lookup-events --lookup-attributes AttributeKey=EventName,AttributeValue=AssumeRoleWithWebIdentity --max-results 5 |
| Simulate permissions | aws iam simulate-principal-policy --policy-source-arn ROLE_ARN --action-names ecs:UpdateService --resource-arns SVC_ARN |
| ECS events | aws ecs describe-services --cluster C --services S --query 'services[0].events[:10].[createdAt,message]' --output text |
| Reasons for stopped tasks | aws ecs list-tasks --cluster C --service-name S --desired-status STOPPED → describe-tasks --query 'tasks[].[stoppedReason,containers[0].exitCode,containers[0].reason]' |
| Container logs | aws logs tail /ecs/myapp --since 15m |
| EKS identity and permissions | aws eks list-access-entries; kubectl auth can-i --list -n myapp |
| Decode authorization failure messages in CloudTrail | aws 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)
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.
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.
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.
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
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:
Official documentation
- ECS: Stopped task errors
- AWS re:Post: Resolve errors related to OIDC
- GitHub Docs: Enabling debug logging
Video storyboard script (about 60 seconds)
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.
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.
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.
Module 8 · Cost, Cleanup, and Self-Check
- 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.
What: the cost breakdown for this lesson
| Resource | Billing method | Usage in this lesson | Notes |
|---|---|---|---|
| Fargate tasks | Per vCPU-second + GB-second (1-minute minimum) | 2 dev + 1 prod, 0.25 vCPU / 0.5 GB | Billing stops only when the service is stopped |
| Public IPv4 address | Each address is billed hourly (since 2024-02) | One per task with a public IP | This is the hidden cost of the "no ALB" approach |
| ECR | Billed per GB-month of storage; no data transfer fee for pulls to ECS in the same region | A few images of about 100 MB each | Lifecycle policies control growth |
| CloudWatch Logs | Per GB ingested + storage | Very little | This lesson sets a 3-day retention |
| ALB (Express Mode or production) | Per hour + LCU | Not created in this lesson | Express Mode creates an ALB automatically |
| EKS cluster | Cluster per hour (extended-support versions cost more) + nodes | Read-only in this lesson | If you reuse the cluster from the K8s lesson, remember to delete it promptly |
| Lambda | Per request + GB-second, with a free tier | A few dozen invocations | Essentially zero |
| IAM, OIDC providers, STS, ECS clusters | Free | — | But they are security assets that must be cleaned up |
| GitHub Actions | Standard GitHub-hosted runners are free for public repositories; private repositories consume the included minutes quota | Over a dozen runs | See 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-rolethe 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
- AWS: roles (dev/prod), EKS access entries, OIDC provider (lab account only).
- 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). - Local: delete temporary JSON files that contain account information (
trust-*.jsonetc.; they contain no secrets, but there is no need to keep them). - You can keep the budget alerts as long-term protection.
Cleanup dependency graph (delete from top to bottom)
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.
Cleanup commands
| Command | Purpose |
|---|---|
aws ecs delete-service --cluster C --service S --force | Delete the service (no need to scale to 0 first) |
aws ecs wait services-inactive | Wait for the service deletion to complete |
aws ecs deregister-task-definition → delete-task-definitions | Deregister first, then delete the revisions |
aws ecr delete-repository --repository-name myapp --force | Delete the repository along with its images |
aws iam list-role-policies / list-attached-role-policies | Find the policies to delete |
aws iam delete-open-id-connect-provider | Delete the provider (use caution) |
gh api -X DELETE repos/O/R/environments/dev | Delete a GitHub environment |
Lab 8: one-command cleanup (about 5 minutes)
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.
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; done2. Check when a given role was last used.
aws iam get-role --role-name gh-myapp-dev-deploy --query 'Role.RoleLastUsed'
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
Official documentation
Video storyboard script (about 45 seconds)
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.
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.
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.
Command cheat sheet
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 COMPLETEDECS 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
| Error | Layer / fix |
|---|---|
| Did you mean to set the id-token permission? | Token: add id-token: write |
| Not authorized to perform sts:AssumeRoleWithWebIdentity | Trust: compare the sub |
| No OpenIDConnect provider found | Trust: create the provider in that account |
| Incorrect token audience | Trust: aud / audience list |
| not authorized to perform: iam:PassRole | Permissions: PassRole + PassedToService |
| ImageTagAlreadyExists / cannot be overwritten | ECR: check before you build |
| rolloutState FAILED / circuit breaker | Service: stoppedReason |
| EKS Unauthorized / Forbidden | Access entry / access policy scope |
Capstone lab + final quiz
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.
source ~/gh-part4.env.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.myapp-dev (desired 2) and myapp-prod (desired 1), both with circuit breaker rollback enabled..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.
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
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).
AssumeRoleWithWebIdentity and the session name gh-RUNID for the prod deployment.cleanup-gh-part4.sh, and use the tagging API to confirm that nothing remains.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
| Topic | Verified conclusion | Source (accessed 2026-11-15) |
|---|---|---|
| configure-aws-credentials | v6.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-chaining | README · action.yml · git ls-remote |
| GitHub OIDC | issuer 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 API | OIDC reference · OIDC in AWS |
| IAM OIDC provider | AWS 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 role | Create an OIDC identity provider |
| GitHub-specific condition keys | On 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_id | What's New · IAM condition keys |
| Session duration and role chaining | AssumeRole duration is up to 12 hours (limited by the role's MaxSessionDuration); role chaining sessions last at most 1 hour, and anything longer fails immediately | IAM roles terms |
| amazon-ecr-login | Latest v2.1.7 (tag SHA 03f1aad4…), node24; mask-password defaults to true; registry-type defaults to private; output registry | Releases · action.yml |
| ECS render / deploy | render 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 behavior | Rolling 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 Mode | App 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-deploy | Latest tag v1.1.2 (README example uses v1.1.0), node24; package-type Zip/Image, publish defaults to true, dry-run, output version | README · action.yml |
| GitHub environments | Required 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 repositories | Deployments and environments |
| Other Action versions | actions/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 IDs123456/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.