Azure DevOps Hour 4: Going to the Cloud (AWS)

Deliver myapp to AWS securely with Azure Pipelines: OIDC federation (no long-lived keys) → ECR (immutable tags + digest) → ECS on Fargate (circuit-breaker rollback) → EKS / Lambda → multi-account promotion and troubleshooting
AWS Toolkit for Azure DevOps 1.26.0AWS CLI v2ca-central-1Helm 4.3.2 · EKS 1.37Checked against official docs · 2026-11-15
Overall learning objectives
  • Based on team size, operations capability and workload shape, make a justified choice among ECS on Fargate / EKS / Lambda the options, and know that App Runner has not accepted new customers since 2026-04-30, and the replacement for new projects is ECS Express Mode.
  • Use AWS Toolkit for Azure DevOps to create an AWS service connection, explain the trade-offs among the three methods, “access key / access key + role assumption / OIDC federation (from 1.15.0)”, and configure an IAM OIDC provider independently, including the trust policy for the issuer https://vstoken.dev.azure.com/{org GUID}, audience api://AzureADTokenExchange and subject sc://{org}/{project}/{service connection} .
  • Build the image in the pipeline and push it to ECR: immutable tags, record the image digest, and deploy by digest, so “what you test is what you ship.”
  • Use AWS CLI to complete the three ECS deployment steps: register a new task definition revision → update the service → wait for stability; enable the deployment circuit breaker + automatic rollback and rehearse it.
  • Grant the pipeline role in EKS access entries, deploy with kubectl/Helm; use Lambda versions and aliases for weighted releases.
  • Design a separate role and account per environment the promotion flow, placing approvals on Environments and service connections; when facing AccessDenied, AssumeRole failures, ECR login failures, stuck ECS deployments, or EKS Unauthorized errors, quickly locate the cause using the troubleshooting tree.

1-hour time allocation table

#TimeModuleCore contentAnimation / interactionLab
0Before classWarm-up and AWS setupAWS account, CLI, Toolkit extension, variable file, OIDC provider, ECR/ECS base resourcesEnvironment self-check checklistOne-time script to create lab resources
100–05Choosing an AWS deployment architectureECS Fargate / EKS / Lambda / ECS Express Mode; App Runner status; comparison with Azure (ACA/AKS/Functions)Selection wizard (5 questions giving a recommendation and rationale)List existing compute resources in the account
205–14AWS service connections and credentials (incl. OIDC)Access keys vs role assumption vs OIDC; Toolkit credential resolution order; ADO OIDC token API; AssumeRoleWithWebIdentity script approachCore animation: service connection → OIDC token → STS temporary credentials → ECR/ECS API; switch between 6 failure scenariosCreate an OIDC service connection and get it working sts get-caller-identity
314–21Build and push to ECRECRPushImage task vs AWS CLI; ECR authentication token; immutable tags; read the digest and use it as an output variableTag drift vs digest pinning simulatorCI stage: build, push, output the digest
421–30Deploy to ECS on Fargatetask definition revisions, iam:PassRole, update-service, wait services-stable, rolloutState, circuit breaker thresholds and rollbackRolling deployment + circuit-breaker rollback animationAutomatic deployment to the dev environment
530–38Deploy to EKS and Lambdaaccess entries + access policies (namespace scope), get-token, kubectl/Helm 4; Lambda versions, aliases, weighted routingEKS authentication/authorization chain (401 vs 403) + alias weight sliderHelm deployment to EKS (optional); Lambda alias canary
638–45Multi-account and environment promotiona separate account/role/service connection per environment; Environments approvals and checks; checks on service connections; cross-account ECR pullsPromotion flow simulator (approval, rejection, wrong connection use)prod stage + approval
745–54Hands-on cloud deployment troubleshootingAccessDenied, AssumeRole failures, ECR login failures, stuck ECS deployments, EKS Unauthorized; locating with CloudTrailError message classifier + interactive troubleshooting treeInject 3 faults and fix them
854–60Cost, cleanup and self-checkbilling breakdown, the cheapest lab topology, Budgets, cleanup in dependency orderCost estimator (editable unit prices)Cleanup script + verify nothing is left behind
—After classCheat sheet · Capstone labmyapp: CI → ECR → ECS Fargate (dev automatic, prod approval) → circuit-breaker rollback drill → cleanupFinal quiz (12 questions)Capstone lab

Knowledge Coverage Matrix

Target skillsM1M2M3M4M5M6M7M8Key commands / tasksLab
AWS compute service selection✓··✓✓··✓aws ecs/eks/lambda list-*M1
Service connections without long-lived keys (OIDC)·✓···✓✓·AWSShellScript@1,create-open-id-connect-providerM2
least-privilege IAM policies and PassRole·✓✓✓✓✓✓·iam put-role-policy,iam:PassedToServiceM2/M4
ECR push, immutable tags, digest··✓✓✓✓✓·ECRPushImage@1,ecr describe-imagesM3
ECS deployment, waiting for stability, circuit-breaker rollback···✓·✓✓·register-task-definition,update-service,wait services-stableM4 / Capstone
EKS authorization and kubectl/Helm deployment····✓·✓✓eks create-access-entry,helm upgrade --installM5
Lambda version and alias releases✓···✓···update-function-code --publish,update-aliasM5
multi-account promotion and approvals·✓···✓··deployment jobs,environment:M6 / Capstone
cloud deployment troubleshooting·✓✓✓✓·✓·cloudtrail lookup-events,ecs describe-servicesM7
cost control and cleanup✓·✓·✓··✓budgets create-budget,ecs delete-serviceM8

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

TopicWhy not in this courseWhere to learn
full ECS task definition fields, ALB/target groups, native ECS blue/green, hands-on Express Mode, ElastiCachebelongs to “how containers run on AWS”, which the Docker course covers in depthDocker course Lesson 4 (ECS/ECR)
EKS cluster creation, Auto Mode, VPC CNI, Pod Identity, LBCis a Kubernetes platform topicK8s course Lesson 7 (EKS)
Azure-side workload identity federation (ARM service connections), ACR/ACA/AKS deploymentsthis course is its AWS counterpartHour 3 (Azure)
extends templates, protected resources, template securitybelongs to pipeline governanceHour 5
managing all AWS resources with Terraform/CloudFormationthis course uses AWS CLI to create lab resources to reduce prerequisitesTerraform course
AWS CodePipeline/CodeBuild/CodeDeploythis course focuses on “Azure Pipelines as CI/CD, AWS as the runtime platform”CodePipeline User Guide

How to use this course

10 pages per module
Principles · Diagram · Animation · Commands · Lab · Production cases · Troubleshooting · Quiz · Voice · Video. We recommend reading “Principles” and “Animation” first, then doing the “Lab”. The animation in Module 2 is the main thread of the whole course; every later module returns to this call chain.
Learning progress
A quiz score of 70% or more, or clicking “Mark this module complete”, counts toward progress, saved in this browser (if the browser blocks local storage, it is cleared on refresh).
Chinese voice
The “Voice” page reads the script aloud with the browser's built-in Web Speech API (en-US), pronouncing English terms in en-US; without a Chinese voice pack, the script can still be read or passed to a TTS tool.
Version notes The latest AWS Toolkit for Azure DevOps is 1.26.0 (GitHub Release, 2026-10-01); OIDC authentication has been supported since 1.15.0 (2024-08-01), tasks support Node 20 from 1.18.0, and OIDC token retrieval failures are retried automatically from 1.20.0; the current source declares Node10 / Node20_1 / Node24 execution handlers for its tasks. The EKS version, Helm 4 and the K8s course are kept consistent (EKS 1.37, Helm 4.3.2). Use the latest AWS CLI v2; for behavior such as the ECS circuit breaker and ECR immutable tags, the official docs read on 2026-11-15 are authoritative. Seethe sources page.
Cost and risk notice This course creates billable resources (Fargate tasks are billed per vCPU and memory second, ECR storage, CloudWatch Logs; the optional EKS control plane is 0.10 USD/hour). The default lab topology deliberately avoids ALB and NAT gateways to reduce costs. Completethe Module 8 cleanup. Lab roles are granted only the minimum permissions this course needs,do not take the example's AdministratorAccess and use it in any real pipeline.

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

Prepare an AWS account and CLI, install the Toolkit extension, note the org GUID, and use a one-time script to create the OIDC provider, ECR repository, ECS cluster and the dev/prod services
Before class ≈ 20 minca-central-1Requires IAM admin permissions (setup phase only)
Prerequisites
  • CompletedHour 2: an Azure DevOps organization (referred to below as myorg ), project myapp-lab, Azure Repos repository myapp (the Flask + gunicorn app from the Docker course, listening on port 5000,/healthz returning ok), and an agent that can run YAML pipelines.
  • Recommended: completeHour 3 (Azure)— this course's modules map one-to-one to it: ARM workload identity federation ↔ AWS OIDC federation, ACR ↔ ECR, ACA ↔ ECS Fargate, AKS ↔ EKS, Functions ↔ Lambda.
  • An AWS account, and an used only during setup administrator identity (an IAM Identity Center user or admin role) used to create the OIDC provider and IAM roles. The pipeline itself will only use least-privilege roles.
  • A machine with AWS CLI v2, Docker and jq; or use AWS CloudShell directly (AWS CLI is preinstalled, but CloudShell has no Docker daemon, so leave image builds to the pipeline).

Connection to the previous lesson

Lesson 3 (Azure)This course (AWS)Notes
ARM service connection (workload identity federation, Entra app/managed identity)AWS service connection (Toolkit, with Use OIDC checked) + IAM OIDC provider + IAM roleBoth use an OIDC token issued by Azure DevOps; ARM hands it to Entra to exchange for a token, while AWS hands it to STS for temporary credentials.
AzureCLI@2 taskAWSShellScript@1 / AWSCLI@1 tasksThe task is responsible for “getting credentials and injecting environment variables”; scripts use the CLI as usual
az acr login / Docker@2aws ecr get-login-password / ECRPushImage@1ECR authentication tokens are valid for 12 hours
ACA revisions and traffic splittingECS task definition revisions + rolling service updates + circuit breakerThe rollback unit is always “the previous revision”
Environments: myapp-dev / myapp-prodEnvironments: myapp-aws-dev / myapp-aws-prodUse different names to avoid interfering with the approval configuration from Lesson 3

Step 1: Install the AWS Toolkit for Azure DevOps extension

Organization settings → Extensions → Browse marketplace, search for AWS Toolkit for Azure DevOps (publisher Amazon Web Services, marketplace ID AmazonWebServices.aws-vsts-tools), click Get it free Install to organization. Installing the extension requires the organization's “Project Collection Administrator” role or an approved extension request.

How to confirm When creating a new service connection, the type list shows AWS; the YAML editor's task assistant shows tasks such as “AWS Shell Script” and “Amazon ECR Push”.

Step 2: Prepare the variables file (admin machine / CloudShell)

cat > ~/ado-aws.env <<'EOF'
export AWS_REGION=ca-central-1
export AWS_DEFAULT_REGION=ca-central-1
export ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
export ADO_ORG=myorg                  # Azure DevOps organization name (the segment after dev.azure.com/ in the URL)
export ADO_PROJECT=myapp-lab
export ADO_ORG_ID=00000000-0000-0000-0000-000000000000   # obtained in step 3; placeholder for now
export REPO=myapp
export ECR=${ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com
export CLUSTER=myapp-lab
export TAGS='Key=project,Value=ado-lab Key=owner,Value=me'
EOF
source ~/ado-aws.env && echo $ACCOUNT_ID $AWS_REGION
111122223333 ca-central-1

Step 3: Get the Azure DevOps organization GUID (part of the OIDC issuer)

The OIDC token issued by Azure DevOps for the AWS service connection has an issuer (iss), which is https://vstoken.dev.azure.com/{org GUID}. According to the AWS official blog, the most reliable method is: First create a service connection with Use OIDC checked and run a pipeline once, in the task log, the line starting with OIDC Token generated will print the issuer, audience and subject. The first run is expected to fail, since AWS is not yet configured. The Module 2 lab walks you through this step; if you want the GUID earlier, finish steps 1–2 of the Module 2 lab first.

Getting OIDC Token...
OIDC Token generated: issuer: {https://vstoken.dev.azure.com/5f3c2d1e-....} sub: {sc://myorg/myapp-lab/aws-myapp-dev}, aud: {api://AzureADTokenExchange}

Once you have it, run sed -i 's/^export ADO_ORG_ID=.*/export ADO_ORG_ID=5f3c2d1e-..../' ~/ado-aws.env && source ~/ado-aws.env. The log format may change between Toolkit versions, so use the issuer you actually see.

Step 4: Create the base lab resources once

The script below creates: the IAM OIDC provider, ECR repository (immutable tags), CloudWatch log group, ECS task execution role, ECS cluster, and dev/prod Fargate services (using public subnets of the default VPC + public IP,without ALB/NAT). The two pipeline roles are created in Modules 2 and 6, since their trust policies are the focus of this course.

source ~/ado-aws.env
# 1) IAM OIDC provider: URL must exactly match the token iss; audience is fixed to api://AzureADTokenExchange
aws iam create-open-id-connect-provider \
  --url https://vstoken.dev.azure.com/$ADO_ORG_ID \
  --client-id-list api://AzureADTokenExchange \
  --tags Key=project,Value=ado-lab

# 2) ECR repository: immutable tags + basic scanning on push
aws ecr create-repository --repository-name $REPO \
  --image-tag-mutability IMMUTABLE \
  --image-scanning-configuration scanOnPush=true \
  --tags Key=project,Value=ado-lab

# 3) Log group (retained for 7 days, to avoid unlimited log accumulation)
aws logs create-log-group --log-group-name /ecs/myapp
aws logs put-retention-policy --log-group-name /ecs/myapp --retention-in-days 7

# 4) Task execution role: the ECS agent uses it to pull ECR images and write logs
aws iam create-role --role-name myappTaskExecutionRole \
  --assume-role-policy-document '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"ecs-tasks.amazonaws.com"},"Action":"sts:AssumeRole"}]}'
aws iam attach-role-policy --role-name myappTaskExecutionRole \
  --policy-arn arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy

# 5) Cluster (Fargate capacity provider only)
aws ecs create-cluster --cluster-name $CLUSTER --capacity-providers FARGATE \
  --default-capacity-provider-strategy capacityProvider=FARGATE,weight=1 \
  --tags key=project,value=ado-lab
# 6) Networking: default VPC subnets + security group allowing only your IP on port 5000
VPC=$(aws ec2 describe-vpcs --filters Name=isDefault,Values=true --query 'Vpcs[0].VpcId' --output text)
SUBNETS=$(aws ec2 describe-subnets --filters Name=vpc-id,Values=$VPC Name=default-for-az,Values=true \
  --query 'Subnets[].SubnetId' --output text | tr '\t' ',')
SG=$(aws ec2 create-security-group --group-name myapp-lab-sg --description "myapp lab" --vpc-id $VPC --query GroupId --output text)
MYIP=$(curl -s https://checkip.amazonaws.com)
aws ec2 authorize-security-group-ingress --group-id $SG --protocol tcp --port 5000 --cidr ${MYIP}/32
echo "export SUBNETS=$SUBNETS SG=$SG VPC=$VPC" >> ~/ado-aws.env

# 7) Initial task definition (placeholder public Python image; the pipeline replaces it with the ECR image on the first deployment)
cat > /tmp/td-bootstrap.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": "public.ecr.aws/docker/library/python:3.13-slim",
    "command": ["python","-m","http.server","5000"],
    "essential": true,
    "portMappings": [{"containerPort": 5000, "protocol": "tcp"}],
    "logConfiguration": {"logDriver": "awslogs", "options": {
      "awslogs-group": "/ecs/myapp", "awslogs-region": "${AWS_REGION}", "awslogs-stream-prefix": "web"}}
  }]
}
EOF
aws ecs register-task-definition --cli-input-json file:///tmp/td-bootstrap.json --query 'taskDefinition.taskDefinitionArn'

# 8) dev and prod services: circuit breaker + automatic rollback enabled
for ENV in dev prod; do
aws ecs create-service --cluster $CLUSTER --service-name myapp-$ENV \
  --task-definition myapp --desired-count 1 --launch-type FARGATE \
  --network-configuration "awsvpcConfiguration={subnets=[$SUBNETS],securityGroups=[$SG],assignPublicIp=ENABLED}" \
  --deployment-configuration "deploymentCircuitBreaker={enable=true,rollback=true},maximumPercent=200,minimumHealthyPercent=100" \
  --tags key=project,value=ado-lab key=env,value=$ENV --query 'service.serviceArn'
done
aws ecs wait services-stable --cluster $CLUSTER --services myapp-dev myapp-prod && echo STABLE
"arn:aws:ecs:ca-central-1:111122223333:task-definition/myapp:1"
"arn:aws:ecs:ca-central-1:111122223333:service/myapp-lab/myapp-dev"
"arn:aws:ecs:ca-central-1:111122223333:service/myapp-lab/myapp-prod"
STABLE
Single-account simplification So the lab can be completed in one account, the dev and prod services are placed in the same cluster and same account, and are isolated by two different pipeline roles (each able to operate only its own service). Module 6 covers the recommended multi-account layout for production, and what extra work cross-account setups require.
Security note Tasks have public IPs and the security group allows only your IP on port 5000; this avoids ALB costs,for lab use only. In production, tasks should be placed in private subnets, with an ALB exposed externally (see Docker course Lesson 4).

Warm-up: answer from memory (30 seconds)

What does an Azure DevOps service connection actually “store”?

It stores the configuration for “how to obtain credentials for the target system”: this may be the secret itself (an access key, a PAT), or just an identity (a role ARN, an app ID) plus a switch for “exchange via OIDC”. The latter stores no long-lived secret in Azure DevOps — this is the topic of Module 2.

What is the difference between a deployment job and a regular job?

A deployment job is bound to environment, can be gated by approvals and checks on the environment, and records deployment history; by default it does not automatically check out source code, but it does automatically download the pipeline artifacts of the current run. Modules 4 and 6 use this.

What is the relationship among ECS services, task definitions and tasks?

A task definition is the immutable template for “how containers run” (each change creates a new revision myapp:N); the service keeps the desired number of tasks of the specified revision running and replaces them in a rolling fashion; a task is a running instance.

Environment self-check checklist

Module 1 · Choosing an AWS deployment architecture

00:00 – 05:00 · What a pipeline looks like depends on where you deploy: the “deploy action” for ECS Fargate, EKS and Lambda is completely different
5 minECS Fargate · EKS · LambdaApp Runner: not accepting new customers since 2026-04-30★★★★
Learning objectives
  • Describe how the three targets ECS on Fargate, EKS and Lambda differ in the “APIs the pipeline must call”: ecs:UpdateService / Kubernetes API / lambda:UpdateFunctionCode + UpdateAlias.
  • Know the current status of App Runner (existing customers can keep using it, no new customers, no new features), and the replacement officially recommended ECS Express Mode.
  • Be able to quickly give a selection recommendation using 5 questions, and state the mapping to Azure (ACA / AKS / Functions).
Prerequisites: The ECS object model from Docker course Lesson 4; the EKS concepts from K8s course Lesson 7. Importance:★★★★ (a wrong target means redoing the pipeline and permission design later)

What: three mainstream deployment targets

  • Amazon ECS on AWS Fargate: AWS's own container orchestration; Fargate gives each task an isolated compute environment, and you don't manage EC2. The deployment unit is task definition revision; the service handles rolling replacement.
  • Amazon EKS: managed Kubernetes control plane (standard support at 0.10 USD per cluster per hour); workloads are described with Kubernetes manifests / Helm. The deployment unit is Deployment/Helm release, and the pipeline needs Kubernetes API permissions (EKS access entries).
  • AWS Lambda: event-driven functions, billed per request and execution duration, packaged as a zip or a container image. The deployment unit is function version, and traffic is shifted through an alias.
  • ECS Express Mode: for the case where you just want to run one containerized web service: you only need an image, a task execution role and an infrastructure role; a single call creates a Fargate service, a TLS-enabled ALB, auto scaling and logs, with no extra charge of its own (verified and demonstrated in Docker course Lesson 4).
App Runner status (verified) AWS App Runner No longer accepting new customers since 2026-04-30; existing customers can keep using it (including creating new services), AWS continues to invest in security and availability, but no new features are planned, and migration to ECS Express Mode is recommended. Therefore this course no longer designs a pipeline for App Runner; if your account already uses it, the pipeline can keep calling apprunner start-deployment, but for new projects choose ECS (including Express Mode).

Why: how the choice affects the pipeline

Azure Pipelines only handles “get credentials, then call APIs”. Deploying to ECS is three AWS API calls (RegisterTaskDefinition → UpdateService → DescribeServices polling); deploying to EKS is one DescribeCluster call eks:DescribeCluster plus several Kubernetes API calls, with permissions split across IAM and Kubernetes layers; deploying to Lambda is UpdateFunctionCode (publish version) + UpdateAlias. Permission policies, rollback methods, troubleshooting paths all follow the target.

How: comparison table

ECS on FargateEKSLambda
Pipeline callsecs register-task-definition,update-service,wait services-stableeks update-kubeconfig + kubectl/helmlambda update-function-code --publish,update-alias
Permissions the pipeline role needsecs:*TaskDefinition, ecs:UpdateService,iam:PassRole (execution role / task role)eks:DescribeCluster + access entries / access policies (K8s authorization)lambda:UpdateFunctionCode, PublishVersion, UpdateAlias; image packages need ECR read access
Built-in rollbackdeployment circuit breaker + automatic rollback to the previous COMPLETED deploymenthelm --rollback-on-failure / kubectl rollout undopoint the alias back to the old version (within seconds)
Fixed costNo cluster fee; billed per task vCPU/memory secondcontrol plane 0.10 USD/hour + nodes (or Auto Mode management fee)almost zero when there are no requests
Team requirementsBasic container knowledge is enoughRequires Kubernetes operations skillsRequires adapting to the event model (web apps need Lambda Web Adapter, etc.)
Azure equivalentAzure Container AppsAKSAzure Functions

When: how to choose

  • Small team, HTTP service / background worker, don't want to learn Kubernetes → ECS on Fargate (just one web service and you want a zero-config ALB → Express Mode).
  • Existing Kubernetes platform, need the Helm ecosystem / multi-cloud consistency / service mesh → EKS.
  • Event-driven (S3, SQS, EventBridge), low and bursty traffic, single execution ≤ 15 minutes → Lambda.
  • Need GPUs, very long tasks, fine-grained node control → ECS on EC2 / ECS Managed Instances or EKS (beyond the scope of this course).
Common misconceptions① “Fargate is just another name for ECS”—Fargate is a compute engine that both ECS and EKS can use. ② “EKS is more ‘advanced’ than ECS, so it's always better”—for a team of 3–5 people, the operational cost of Kubernetes upgrades, add-ons and RBAC usually far outweighs the benefit. ③ “Lambda can only deploy zip files”—Lambda also supports container images up to 10 GB, but the image must implement the Lambda runtime interface. ④ “App Runner has been shut down”—it has not; it just no longer accepts new customers or gets new features.

Architecture diagram: one Azure Pipelines pipeline, three AWS targets

Azure PipelinesCI: build → push to ECRCD: deployment jobAWS service connection (OIDC) STStemporary credentials ECS on FargateRegisterTaskDefinition → UpdateServiceRollback: circuit breaker EKSDescribeCluster → K8s API (access entries)Rollback: helm / rollout undo LambdaUpdateFunctionCode(publish) → UpdateAliasRollback: point alias back to old version Amazon ECRmyapp@sha256:…All three targets share
Figure 1-1: credential acquisition is the same (Module 2); the difference is which APIs are called once temporary credentials are obtained

Decision flowchart

Event-driven, ≤15 min? Lambda Existing K8s platform/team? EKS Just a single web service? ECS Express Mode ECS on Fargate Yes No Yes No Yes No
Figure 1-2 simplified decision: first rule out Lambda, then check whether the team already has Kubernetes, and finally look at the service shape

Interactive: selection wizard

Answer 5 questions; the wizard gives a recommended target, the key APIs the pipeline needs, and the IAM permissions. You can change any answer, and the result updates in real time.

Core command: inventory existing compute resources in the account

CommandPurposeNotes
aws ecs list-clusters / list-services --clusterList ECS clusters and servicesThe pipeline's --cluster,--service parameters come from here
aws eks list-clustersList EKS clustersEvery cluster is billed every hour
aws lambda list-functionsList functions--query 'Functions[].[FunctionName,PackageType,Runtime]'
aws apprunner list-servicesList App Runner servicesNew customers' calls will be rejected when creating services; use only for inventorying existing resources
aws ecs describe-clusters --include STATISTICSCheck the number of running tasksDetermine whether the cluster is idle
source ~/ado-aws.env
aws ecs list-clusters --query 'clusterArns' --output table
aws ecs list-services --cluster $CLUSTER --query 'serviceArns' --output table
aws eks list-clusters --query 'clusters' --output table
aws lambda list-functions --query 'Functions[].[FunctionName,PackageType,Runtime]' --output table
-------------------------------------------------------------------
|                          ListClusters                           |
+-----------------------------------------------------------------+
|  arn:aws:ecs:ca-central-1:111122223333:cluster/myapp-lab        |
+-----------------------------------------------------------------+
...
|  arn:aws:ecs:ca-central-1:111122223333:service/myapp-lab/myapp-dev   |
|  arn:aws:ecs:ca-central-1:111122223333:service/myapp-lab/myapp-prod  |

How to verify: If both services appear in the list, the pre-class setup succeeded. Common mistakes: Forgetting to set the region, so the CLI defaults to us-east-1 querying, and the result is empty. Production use: Print the target resources at the start of the pipeline, so a failure immediately shows “wrong account/region”.

Lab 1: record a selection decision for myapp (about 3 min)

Use the wizard to answer for myapp: HTTP service, maintained by 2 people, no Kubernetes experience, will need Redis later, steady traffic. Record the wizard's recommendation (should be ECS on Fargate).
Write an ADR (architecture decision record) in the repository
mkdir -p docs/adr
cat > docs/adr/0004-aws-target.md <<'EOF'
# 4. Deployment target for myapp on AWS
- Status: accepted (2026-11)
- Decision: ECS on AWS Fargate, region ca-central-1
- Rationale: the team has no K8s operations capability; HTTP long-lived connection services are not a good fit for Lambda; App Runner has not accepted new customers since 2026-04-30
- Consequences: the pipeline role needs ecs:RegisterTaskDefinition / UpdateService / iam:PassRole; rollback depends on the deployment circuit breaker
- Review trigger: re-evaluate EKS when the number of services > 15 or a service mesh is needed
EOF
git add docs/adr && git commit -m "ADR: AWS deployment target" && git push
Confirm the target resources exist: run the inventory commands from the “Commands” page to confirm myapp-dev,myapp-prod that both services exist.
Acceptance The ADR is pushed to Azure Repos; you can explain in one sentence “why not EKS, why not App Runner”.

Case 1: a new project moving off App Runner

Problem: The team planned to reuse an App Runner template from another account to deploy a new service, but the new account cannot enable App Runner. Approach: Confirmed that new customers can no longer use it after 2026-04-30; switched to ECS Express Mode to create the service and ALB, and changed the pipeline's deployment action to “push the image + update the Express service”. Limitations: Express Mode is a newer feature and its parameters may still change; pin the AWS CLI version in the pipeline and run regression tests when upgrading.

Case 2: the operational burden of choosing EKS by mistake

Problem: A 3-person team built EKS for 4 APIs; a year later the cluster version fell behind and entered extended support, costs rose, and no one was responsible for upgrades. Approach: Moved the stateless APIs to ECS Fargate; the pipeline switched from Helm to task definition deployments; EKS is kept only for components that need Operators. Result: Control plane and node costs dropped, and upgrade work disappeared. Lesson: Write “who owns the 3 Kubernetes upgrades per year” into the selection ADR.

Case 3: the part that suits Lambda

Problem: myapp needs to generate a report every night and write it to S3. Approach: The report job is built as a Lambda (triggered by EventBridge Scheduler), sharing the same Azure Pipelines pipeline and the same ECR account with the web service on ECS, but using different deployment stages and roles. Lesson: The choice need not be “one target per system”; split by workload.

Common errors and fixes

Could not connect to the endpoint URL / empty list: ListClusters returns []

Cause: Wrong region (the CLI default region, or regionName not set on the service connection task), or connected to the wrong account.

aws configure list
aws sts get-caller-identity
echo $AWS_REGION $AWS_DEFAULT_REGION

Fix: Explicitly set the task's regionName: ca-central-1, and in scripts explicitly pass --region or set AWS_REGION.

App Runner: creating a service fails, saying the account is unavailable / not available to new customers

Cause: App Runner has not accepted new customers since 2026-04-30.

Fix: For new projects, use ECS Express Mode or a standard ECS Fargate service; existing services can keep being deployed, but plan a migration (the official guidance is to use Route 53 weighted routing to shift traffic gradually).

Deploying Flask on Lambda returns 502 / Runtime.InvalidEntrypoint

Cause: A regular web container does not implement the Lambda runtime interface (Runtime API).

Fix: Use the AWS-provided base image and handler, or add Lambda Web Adapter; for long-lived connection or WebSocket services, choose ECS directly.

Command-line questions
1. Use one command to list the names and package types of all Lambda functions in ca-central-1.
aws lambda list-functions --region ca-central-1 --query 'Functions[].[FunctionName,PackageType]' --output table
2. Check the number of tasks currently running in the ECS cluster myapp-lab.
aws ecs describe-clusters --clusters myapp-lab --query 'clusters[0].runningTasksCount'
Scenario analysis questions
A 6-person team already runs 20 services on Azure with AKS + Helm and now needs a second site on AWS. ECS or EKS? What changes in the pipeline?

Leaning toward EKS: they already have Helm charts, the team has Kubernetes capability, and keeping the same deployment model across both clouds lets them reuse charts and pipeline templates. Pipeline changes: the service connection changes from ARM to AWS (OIDC),az aks get-credentials switch to aws eks update-kubeconfig and create access entries for the pipeline role in EKS; the Helm commands themselves stay the same. If only 2–3 services need to go to AWS, ECS is also a reasonable choice.

Verified instructional videos

▶
Serverless for container fans via Amazon ECS and AWS Lambda — Bret Fisher
English · Comparing ECS and Lambda from a container developer's perspective (duration and date not verified; App Runner status per this course)
▶
AWS re:Invent 2024 - Unleashing the power of Amazon ECS for platform teams (SVS330) — AWS Events
English · How platform teams run multiple services on ECS
▶
Amazon EKS Auto Mode | Fully Automated Kubernetes Clusters — AWS Developers
English · If you choose EKS, how much node operations work can Auto Mode remove?

Official documentation

Video storyboard script (about 60 seconds)

Shot 1 · 0–15s
Visual: Azure Pipelines icon on the left, three doors on the right: ECS, EKS, Lambda.
Narration: once the pipeline has AWS credentials, which door it knocks on determines which APIs it calls.
Shot 2 · 15–35s
Visual: behind the three doors, buttons appear for UpdateService, kubectl apply and UpdateAlias.
Narration: ECS updates the service, EKS calls Kubernetes, and Lambda publishes a version and then switches the alias.
Shot 3 · 35–60s
Visual: the fourth door, App Runner, gets a “no new customers” sign, and an arrow points to ECS Express Mode.
Narration: App Runner has not accepted new customers since April 30, 2026; for new projects, use ECS Express Mode.
or score ≥ 70% on the quiz

Module 2 · AWS service connections and credentials (incl. OIDC)

05:00 – 14:00 · The pipeline holds no long-lived AWS keys: Azure DevOps issues an OIDC token, and STS exchanges it for temporary credentials valid from 15 minutes to 12 hours
9 minNative OIDC in Toolkit 1.15.0+AssumeRoleWithWebIdentity★★★★★
Learning objectives
  • Compare the three configurations of an AWS service connection: access key,access key + role assumption (AssumeRole),OIDC federation (only the role ARN + Use OIDC checked, via AssumeRoleWithWebIdentity), and explain why OIDC is the preferred choice.
  • Accurately write out the four elements of an OIDC trust relationship: provider URL https://vstoken.dev.azure.com/{org GUID}, audience api://AzureADTokenExchange, subject sc://{org}/{project}/{service connection name}, action sts:AssumeRoleWithWebIdentity.
  • Understand the Toolkit task's credential resolution order and session duration (default 900 seconds; variable aws.rolecredential.maxduration can be set to 900–43200 seconds, but may not exceed the role's MaxSessionDuration).
  • When no Toolkit task is available, use System.OidcRequestUri + aws sts assume-role-with-web-identity a script approach to perform the exchange yourself, and know its prerequisites and limitations.
Prerequisites: Workload identity federation from Lesson 3; IAM roles and trust policies. Importance:★★★★★ (all later modules in this course depend on this credential chain)

What: what is an AWS service connection

An AWS service connection is a service connection type provided by the AWS Toolkit for Azure DevOps extension (connectedService:AWS). Toolkit tasks (AWSShellScript@1, AWSCLI@1, ECRPushImage@1, LambdaDeployFunction@1, etc.) reference it via the input awsCredentials: <connection name> . Azure DevOps itself has no built-in service connection type for “AWS workload identity federation”— the OIDC capability comes from the Toolkit: it calls the Azure DevOps OIDC token REST API (Oidctoken - Create) to request a token for the connection, then hands it to AWS STS.

Comparison of the three credential configurations

ConfigurationWhat to fill in the service connectionWhat the task calls internallyAdvantagesRisks
① Access keyAccess Key ID + Secret Access KeySigns requests directly with an IAM user keySimplestLong-lived key: once leaked, usable for a long time; needs rotation; IAM user permissions are often too broad
② Access key + role assumptionKey + Role to Assume (optional External ID, session name)sts:AssumeRole → temporary credentials (default 15 minutes)The task uses temporary credentials; works across accounts, and can switch roles per environmentStill stores one long-lived key (used only for AssumeRole)
③ OIDC federation (recommended)Fill in only Role to Assume, check Use OIDC, no keysRequests an OIDC token from Azure DevOps → sts:AssumeRoleWithWebIdentityIn Azure DevOps no AWS secret is stored; the trust policy can be scoped to a specific service connectionA wrong trust policy = denied; renaming the org/project/connection changes the subject

Toolkit official README: “We strongly suggest to use the OIDC Federation to avoid having to maintain static credentials.” If Use OIDC is checked but a key is also filled in, the task first follows the key + role assumption path (in the source, pure OIDC is used only when there is no key and a role ARN is present).

Why: why OIDC is safer

  • No long-lived secret to leak: the token is issued by Azure DevOps for a specific job and a specific service connection, with a very short lifetime; the credentials STS returns expire after 15 minutes by default.
  • Identity can be tightly constrained: the trust policy uses sub = sc://myorg/myapp-lab/aws-myapp-prod to restrict it so that “only this service connection can assume the prod role”. Tokens obtained by other projects or other connections have a different subject and are rejected by STS.
  • Clear auditing: in CloudTrail AssumeRoleWithWebIdentity events record the subject, role and session name, so you can trace which service connection initiated the call.

How: the 6 steps of the OIDC exchange

  1. The task reads the service connection parameters: assumeRoleArn,useOIDC,roleSessionName (default aws-vsts-tools).
  2. The task uses the job's System.AccessToken to call the Azure DevOps OIDC token API (…/_apis/distributedtask/hubs/{hub}/plans/{planId}/jobs/{jobId}/oidctoken?serviceConnectionId=…), retrying automatically on failure (from 1.20.0).
  3. Azure DevOps returns a JWT: iss=https://vstoken.dev.azure.com/{org GUID},aud=api://AzureADTokenExchange,sub=sc://{org}/{project}/{service connection}.
  4. The task calls STS AssumeRoleWithWebIdentity (RoleArn, RoleSessionName, WebIdentityToken, DurationSeconds).
  5. STS checks: an IAM OIDC provider with a matching URL exists in the account → gets the public key from the issuer's /.well-known/openid-configuration and JWKS to verify the signature → the audience is in the provider's client ID list → the role trust policy conditions (:aud,:sub) are satisfied → DurationSeconds ≤ role MaxSessionDuration.
  6. STS returns temporary credentials (ASIA… access key, session token, expiration time), and the task passes them as AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY/AWS_SESSION_TOKEN/AWS_REGION environment variables to the script (AWSShellScript) or uses them directly for SDK calls (ECRPushImage, etc.).

Toolkit task credential source order (when no service connection is specified)

Task variables AWS.AccessKeyID/AWS.SecretAccessKey/AWS.SessionToken → standard environment variables in the agent process AWS_ACCESS_KEY_ID etc. → instance metadata when the agent runs on EC2 (instance profile role). When a self-hosted agent runs on EC2 / ECS, the latter is another “no keys” approach, but it binds permissions to the machine rather than to the service connection, so every pipeline running on that agent can use them; isolation is weaker than with OIDC.

Session duration

The Toolkit requests 900 seconds (15 minutes) by default. For long deployments (for example, waiting up to 10 minutes for ECS to stabilize, plus the build), you can set the pipeline variable aws.rolecredential.maxduration (900–43200). The requested duration must not exceed the role's MaxSessionDuration (1 hour by default when the role is created), otherwise STS reports ValidationError. Note: credentials are obtained at the start of each task, so “15 minutes per task” is usually enough; what really needs lengthening is a long script within a single task.

Script approach: call the OIDC API yourself + AssumeRoleWithWebIdentity

When to use: you need credentials where Toolkit tasks are not supported (for example, custom tools in a container job), or you want the AWS SDK to refresh credentials automatically (AWS_WEB_IDENTITY_TOKEN_FILE + AWS_ROLE_ARN). Basis for feasibility: ① Microsoft publicly documented, in the sprint 240 release notes, System.OidcRequestUri the variable and the usage of “requesting a new idToken from your own script” (the example is an AzureRM connection); ② the Toolkit source for AWS connections calls the same Oidctoken API, passing in the AWS service connection's ID.

Caveat Microsoft's script example only demonstrates AzureRM service connections. When calling directly from a script with an AWS-type service connection,the pipeline must already be authorized to use the service connection (add this pipeline under the service connection's “Pipeline permissions”), otherwise the request is rejected; the token's subject always uses the service connection's sc://…, so the trust policy does not need to change. This course treats it as a fallback; in production, prefer Toolkit tasks. Test in your own organization before rolling it out.

When: how to choose

  • New pipelines: always use OIDC (Toolkit ≥ 1.15.0).
  • Existing pipelines still using access keys: first switch to “key + role assumption”, then move to OIDC, and finally deactivate and delete the old access keys in IAM.
  • Self-hosted agents on AWS: you can use an instance role, but it is still recommended to have one OIDC service connection per environment, to avoid “anyone can use the agent's permissions”.

Comparison with similar technology

Azure DevOps → AWS (this course)Azure DevOps → Azure (Lesson 3)GitHub Actions → AWS
Issuerhttps://vstoken.dev.azure.com/{org GUID}New ARM connections use the Entra issuer (see Lesson 3)https://token.actions.githubusercontent.com
Audienceapi://AzureADTokenExchangeapi://AzureADTokenExchangests.amazonaws.com
subjectsc://org/project/service connectionsc://org/project/service connection (or new format)repo:owner/repo:ref:… / environment:…
Exchange partyAWS STS AssumeRoleWithWebIdentityEntra ID (federated credential)AWS STS AssumeRoleWithWebIdentity
Common misconceptions① “Checking Use OIDC means nothing needs configuring in AWS”—you must first create the IAM OIDC provider and the role that trusts it. ② “The subject contains the project ID”—the format given in the Toolkit docs and the AWS blog is the connection name: sc://{OrganizationName}/{ProjectName}/{ServiceConnectionName}, so renaming breaks trust. ③ “The audience can be anything”—the audience of tokens issued by Azure DevOps is fixed to api://AzureADTokenExchange (AWS blog: “This is a fixed value for Azure DevOps.”). ④ “An OIDC token is an AWS credential”—it is only proof of identity; it must be exchanged through STS before you can call AWS APIs.

Sequence diagram: one OIDC credential exchange

Toolkit task Azure DevOps OIDC API AWS STS IAM (provider + role) ① POST …/oidctoken?serviceConnectionId (Bearer System.AccessToken) ② JWT: iss / aud / sub ③ AssumeRoleWithWebIdentity(RoleArn, WebIdentityToken, DurationSeconds) ④ Find the OIDC provider (URL = iss) ⑤ Fetch /.well-known/openid-configuration + JWKS to verify the signature ⑥ Trust policy: aud and sub conditions; duration ≤ MaxSession ⑦ Credentials: ASIA… / SessionToken / Expiration ⑧ Inject AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY /AWS_SESSION_TOKEN / AWS_REGION → aws ecr / aws ecs …
Figure 2-1: Azure DevOps only issues identity tokens; the actual AWS credentials are issued by STS after verifying the trust relationship

Trust policy item-by-item mapping

OIDC token (JWT payload, example) "iss": "https://vstoken.dev.azure.com/5f3c…" "aud": "api://AzureADTokenExchange" "sub": "sc://myorg/myapp-lab/aws-myapp-dev" "exp": expires shortly after issuance Role trust policy Principal.Federated: …:oidc-provider/vstoken.dev.azure.com/5f3c… vstoken.dev.azure.com/5f3c…:aud = api://AzureADTokenExchange vstoken.dev.azure.com/5f3c…:sub = sc://myorg/myapp-lab/aws-myapp-dev Action: sts:AssumeRoleWithWebIdentity
Figure 2-2: iss determines “which provider”; aud and sub must exactly match the condition keys (StringEquals)

Core animation: the credential acquisition and call chain from Azure Pipelines to AWS

Choose a scenario, then click “Play” or “Next step”. The normal scenario goes through ① request OIDC token → ② STS exchange → ③ call ECR/ECS; failure scenarios stop at the point where the real error occurs and show the original text you would see in the task log, along with the fix.

Pipeline taskawsCredentials: aws-myapp-dev ADO OIDC token APISystem.AccessToken AWS STSAssumeRoleWithWebIdentity IAMOIDC provider + trust policy Temporary credentialsASIA… · 900s Amazon ECRGetAuthorizationToken → docker push Amazon ECSRegisterTaskDefinition · PassRole · UpdateService

Core commands and tasks

Command / taskPurposeKey parameters
aws iam create-open-id-connect-providerCreate IAM OIDC provider--url https://vstoken.dev.azure.com/<GUID>,--client-id-list api://AzureADTokenExchange; the thumbprint can be omitted (IAM attempts to obtain it automatically and prefers verification via the trusted CA library)
aws iam create-role --assume-role-policy-documentCreate pipeline role and trust policy--max-session-duration (default 3600)
aws iam put-role-policyWrite an inline permissions policy for the roleTighten per environment and per resource ARN
AWSShellScript@1Run a Bash script with the service connection's credentialsawsCredentials,regionName,scriptType: inline|filePath (inline policy up to 5000 characters)
AWSCLI@1Run an AWS CLI commandawsCommand,awsSubCommand,awsArguments
variable aws.rolecredential.maxdurationAdjust temporary credential duration900–43200 seconds, ≤ role MaxSessionDuration
aws sts get-caller-identityConfirm who you areOn OIDC success, the Arn looks like assumed-role/role name/session name
aws sts assume-role-with-web-identityManual exchange in the script approachNo existing AWS credentials needed (this API does not require signing)

Minimal working OIDC verification pipeline

trigger: none
pool:
  vmImage: ubuntu-latest
variables:
  aws.rolecredential.maxduration: "900"
steps:
- task: AWSShellScript@1
  displayName: Who am I (OIDC)
  inputs:
    awsCredentials: aws-myapp-dev        # service connection name
    regionName: ca-central-1
    scriptType: inline
    inlineScript: |
      aws sts get-caller-identity
      env | grep -E '^AWS_(REGION|ACCESS_KEY_ID)=' | sed 's/=\(ASIA....\).*/=\1…/'
Getting OIDC Token...
OIDC Token generated: issuer: {https://vstoken.dev.azure.com/5f3c2d1e-…} sub: {sc://myorg/myapp-lab/aws-myapp-dev}, aud: {api://AzureADTokenExchange}
Assuming role via OIDC Token...
...role assumed via OIDC Token: arn:aws:sts::111122223333:assumed-role/ado-myapp-dev-deploy/aws-vsts-tools
{
    "UserId": "AROAEXAMPLEID:aws-vsts-tools",
    "Account": "111122223333",
    "Arn": "arn:aws:sts::111122223333:assumed-role/ado-myapp-dev-deploy/aws-vsts-tools"
}
AWS_REGION=ca-central-1
AWS_ACCESS_KEY_ID=ASIA…

How to verify: The Arn contains assumed-role/ado-myapp-dev-deploy, and the access key starts with ASIA (temporary credentials; long-lived keys start with AKIA ). Common mistakes: Printing the whole credential to the log — Azure Pipelines only automatically masks “known secret variables”, and temporary credentials injected by the Toolkit are not necessarily masked, so never echo credentials.

Script approach (without Toolkit tasks)

- bash: |
    set -euo pipefail
    # 1) Request an OIDC token for this service connection from Azure DevOps
    OIDC_TOKEN=$(curl -sS -X POST \
      -H "Content-Type: application/json" -H "Content-Length: 0" \
      -H "Authorization: Bearer ${SYSTEM_ACCESSTOKEN}" \
      "${SYSTEM_OIDCREQUESTURI}?api-version=7.1&serviceConnectionId=${AWS_SC_ID}" | jq -r '.oidcToken')
    test -n "$OIDC_TOKEN" -a "$OIDC_TOKEN" != "null"
    # 2a) Hand to the SDK: write it to a file; the CLI/SDK automatically calls AssumeRoleWithWebIdentity and refreshes before expiry
    echo "$OIDC_TOKEN" > "$(Agent.TempDirectory)/aws-web-identity-token"
    export AWS_WEB_IDENTITY_TOKEN_FILE="$(Agent.TempDirectory)/aws-web-identity-token"
    export AWS_ROLE_ARN="arn:aws:iam::111122223333:role/ado-myapp-dev-deploy"
    export AWS_ROLE_SESSION_NAME="ado-$(Build.BuildId)"
    aws sts get-caller-identity
    # 2b) Or exchange manually (get one-time temporary credentials)
    # aws sts assume-role-with-web-identity --role-arn "$AWS_ROLE_ARN" \
    #   --role-session-name "ado-$(Build.BuildId)" --web-identity-token "$OIDC_TOKEN" --duration-seconds 900
  displayName: OIDC → STS (script)
  env:
    SYSTEM_ACCESSTOKEN: $(System.AccessToken)
    AWS_SC_ID: $(awsServiceConnectionId)   # service connection GUID
    AWS_REGION: ca-central-1

Note: ① in YAML, a script that gets System.AccessToken must go through env: an explicit mapping; ② the OIDC token inside the token file also expires, and the SDK needs an “unexpired token” to refresh credentials, so a long-running script should request a new token before expiry and overwrite the file; ③ the service connection GUID can be obtained from az devops service-endpoint list --query "[?name=='aws-myapp-dev'].id" -o tsv .

Lab 2: create the OIDC service connection and dev pipeline role (about 8 min)

Create the AWS service connection (without setting up the AWS side yet): Project settings → Service connections → New service connection → AWS. Fill in: connection name aws-myapp-dev; Role to Assume arn:aws:iam::111122223333:role/ado-myapp-dev-deploy (replace with your account ID); check Use OIDC; leave Access Key ID / Secret empty; Role Session Name can be left empty (default aws-vsts-tools). Do not check “Grant access permission to all pipelines”.
Run the verification pipeline and read the org GUID: take the minimal OIDC verification pipeline from the “Commands” page azure-pipelines-oidc-test.yml , commit it to the repository and create the pipeline; on the first run, click to permit use of the service connection when prompted. The task will fail (the AWS side has no provider/role yet), but in the log OIDC Token generated shows the issuer. Write the GUID into ~/ado-aws.env the ADO_ORG_ID, if pre-class step 4 skipped the OIDC provider, create it now:
source ~/ado-aws.env
aws iam create-open-id-connect-provider --url https://vstoken.dev.azure.com/$ADO_ORG_ID \
  --client-id-list api://AzureADTokenExchange --tags Key=project,Value=ado-lab
aws iam list-open-id-connect-providers
{
    "OpenIDConnectProviderList": [
        { "Arn": "arn:aws:iam::111122223333:oidc-provider/vstoken.dev.azure.com/5f3c2d1e-…" }
    ]
}
Create the dev pipeline role (the trust policy accepts only the aws-myapp-dev connection)
source ~/ado-aws.env
P=vstoken.dev.azure.com/$ADO_ORG_ID
cat > /tmp/trust-dev.json <<EOF
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": { "Federated": "arn:aws:iam::${ACCOUNT_ID}:oidc-provider/${P}" },
    "Action": "sts:AssumeRoleWithWebIdentity",
    "Condition": { "StringEquals": {
      "${P}:aud": "api://AzureADTokenExchange",
      "${P}:sub": "sc://${ADO_ORG}/${ADO_PROJECT}/aws-myapp-dev"
    } }
  }]
}
EOF
aws iam create-role --role-name ado-myapp-dev-deploy \
  --assume-role-policy-document file:///tmp/trust-dev.json \
  --max-session-duration 3600 --tags Key=project,Value=ado-lab \
  --query 'Role.Arn' --output text
arn:aws:iam::111122223333:role/ado-myapp-dev-deploy
Write the least-privilege policy (ECR push to the myapp repository, deploy only the myapp-dev service, pass the execution role to ECS only)
cat > /tmp/perm-dev.json <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    { "Sid": "EcrAuth", "Effect": "Allow", "Action": "ecr:GetAuthorizationToken", "Resource": "*" },
    { "Sid": "EcrPushMyapp", "Effect": "Allow",
      "Action": ["ecr:BatchCheckLayerAvailability","ecr:InitiateLayerUpload","ecr:UploadLayerPart",
                 "ecr:CompleteLayerUpload","ecr:PutImage","ecr:BatchGetImage","ecr:DescribeImages"],
      "Resource": "arn:aws:ecr:${AWS_REGION}:${ACCOUNT_ID}:repository/${REPO}" },
    { "Sid": "EcsTaskDef", "Effect": "Allow",
      "Action": ["ecs:RegisterTaskDefinition","ecs:DescribeTaskDefinition","ecs:ListTasks","ecs:DescribeTasks"],
      "Resource": "*" },
    { "Sid": "EcsServiceDev", "Effect": "Allow", "Action": ["ecs:UpdateService","ecs:DescribeServices"],
      "Resource": "arn:aws:ecs:${AWS_REGION}:${ACCOUNT_ID}:service/${CLUSTER}/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 ado-myapp-dev-deploy --policy-name deploy-dev \
  --policy-document file:///tmp/perm-dev.json

ecr:GetAuthorizationToken does not support resource-level restrictions, so you can only use "*"; RegisterTaskDefinition also needs "*". The real isolation point is UpdateService 's service ARN and iam:PassRole 's role ARN.

Re-run the verification pipeline: IAM changes usually take effect within seconds. The expected log shows role assumed via OIDC Token and assumed-role/ado-myapp-dev-deploy/aws-vsts-tools.
Negative test: prove the trust policy is working: create a new connection aws-myapp-test, fill in the dev role ARN and check Use OIDC, then in the pipeline change the awsCredentials to point to it and run once.
Getting OIDC Token...
OIDC Token generated: issuer: {https://vstoken.dev.azure.com/5f3c…} sub: {sc://myorg/myapp-lab/aws-myapp-test}, aud: {api://AzureADTokenExchange}
Assuming role via OIDC Token...
Failed to assume role with OIDC: AccessDenied: Not authorized to perform sts:AssumeRoleWithWebIdentity

Different subject → trust policy condition not met. How the error appears varies by Toolkit version: newer code throws “Could not assume role … (token subject '…') … Check that the role's trust policy allows sts:AssumeRoleWithWebIdentity …” directly; older versions may keep going and only fail at a later AWS call with an error like “security token included in the request is invalid”. If you see the latter, scroll up in the log first to find the OIDC lines. Delete the aws-myapp-test connection when finished.

Acceptance① aws-myapp-dev The connection holds no access keys; ② the verification pipeline succeeds and shows assumed-role; ③ using a different connection name to assume the same role is rejected.

Case 1: a leaked IAM user key

Problem: An old AWS service connection stored an IAM user's access key, and that user had attached PowerUserAccess; a former employee had exported that key. Approach: Migrated in two steps, “key + role assumption → OIDC”: first create an OIDC role and new connection for each environment, switch pipelines one by one; use the IAM credential report to confirm the old key access_key_1_last_used_date shows it is no longer being used, then deactivate and delete it. Lesson: During migration, use CloudTrail to filter by userIdentity.accessKeyId to find callers still using the old key.

Case 2: renaming a project broke all deployments

Problem: An administrator renamed the Azure DevOps project from myapp-lab to myapp, and the next day every AWS deployment reported Not authorized to perform sts:AssumeRoleWithWebIdentity. Root cause: The subject includes the project name, changing from sc://myorg/myapp-lab/… to sc://myorg/myapp/…. Fix: Update the trust policy of all roles. Prevention: Add “renaming an org/project/service connection” to the change checklist; manage trust policies as IaC, and publish them together with any rename.

Case 3: credentials expire during a long CloudFormation deployment

Problem: One AWSShellScript task ran a database migration and a CloudFormation deployment in sequence, taking 25 minutes; the second half reported ExpiredToken. Approach: Set aws.rolecredential.maxduration: "3600", and confirm the role's MaxSessionDuration ≥ 3600; a better approach is to split the long job into multiple tasks (each task obtains credentials when it starts).

Common errors and fixes

System.AccessToken is undefined. Ensure that you have enabled OAuth token access for your pipeline/agent job

Cause: The Toolkit needs the job's OAuth token to request an OIDC token. In classic release/build pipelines, “Allow scripts to access the OAuth token” is unchecked; or org/project policies restrict the job token.

Fix: Classic pipelines: agent job → check Allow scripts to access the OAuth token. In YAML pipelines, Toolkit tasks work directly (the AWS official blog example needs no extra mapping); a hand-written script must env: SYSTEM_ACCESSTOKEN: $(System.AccessToken).

InvalidIdentityToken: No OpenIDConnect provider found in your account for https://vstoken.dev.azure.com/5f3c…

Cause: The IAM account has no OIDC provider whose URL exactly matches (wrong GUID copied, extra trailing slash, or created in another account).

aws iam list-open-id-connect-providers
aws iam get-open-id-connect-provider --open-id-connect-provider-arn <ARN> --query '{url:Url,aud:ClientIDList}'

Fix: Recreate the provider using the issuer printed in the task log; the OIDC provider must be in the same account as the role.

AccessDenied: Not authorized to perform sts:AssumeRoleWithWebIdentity

Cause: Trust policy condition not met: subject mismatch (org/project/connection renamed, different letter case, or the project ID was written instead), the condition key prefix was written as https://…, the audience was wrong, or the Principal points to a different provider.

aws iam get-role --role-name ado-myapp-dev-deploy --query 'Role.AssumeRolePolicyDocument'

Fix: Match the subject from the task log exactly; the condition key format is vstoken.dev.azure.com/<GUID>:sub (without https://).

ValidationError: The requested DurationSeconds exceeds the MaxSessionDuration set for this role.

Cause:aws.rolecredential.maxduration The requested duration is greater than the role's MaxSessionDuration (default 3600).

aws iam update-role --role-name ado-myapp-dev-deploy --max-session-duration 7200

Fix: Choose one: lower the variable, or raise the role's maximum session duration (up to 43200).

Credentials could not be loaded / Unable to locate credentials (calling aws directly in a script)

Cause: Used a regular bash/script step instead of AWSShellScript@1, so the Toolkit had no chance to inject credentials; or environment variables were not passed in a container job.

Fix: Switch to AWSShellScript@1, or use the script approach from the “Commands” page.

Command-line questions
1. Write the trust policy condition that allows only the service connection aws-myapp-prod to assume the role (represent the org GUID as $G).
"Condition": { "StringEquals": {
  "vstoken.dev.azure.com/$G:aud": "api://AzureADTokenExchange",
  "vstoken.dev.azure.com/$G:sub": "sc://myorg/myapp-lab/aws-myapp-prod"
} }
2. Find the most recent AssumeRoleWithWebIdentity event in CloudTrail.
aws cloudtrail lookup-events --region ca-central-1 \
  --lookup-attributes AttributeKey=EventName,AttributeValue=AssumeRoleWithWebIdentity \
  --max-results 5 --query 'Events[].[EventTime,Username]' --output table
Scenario analysis questions
The security team requires that “pipelines in the dev project must never deploy to prod”. Is Azure DevOps service connection permission alone enough? What extra safeguard can you add on the AWS side?

Not enough: project administrators can change a service connection's pipeline permissions. The hard guarantee on the AWS side is: the prod role's trust policy subject only lists sc://myorg/myapp-prod-project/aws-myapp-prod, tokens from the dev project have a different subject, so STS always rejects them. In addition, prod runs in a separate account, and the prod role authorizes only prod resources. You can also use SCPs in AWS Organizations to restrict the permission boundary of the dev account.

Verified instructional videos

No video verified via oEmbed that specifically explains “Azure DevOps federating to AWS via OIDC” was found. Official articles and a storyboard script are provided below.

Official documentation and articles

Video storyboard script (about 90 seconds)

Shot 1 · 0–20s
Visual: a key labeled AKIA sits in an Azure DevOps safe, with a red warning.
Narration: put a long-lived access key into a service connection, and once it leaks, it stays valid for a long time.
Shot 2 · 20–45s
Visual: the pipeline task raises its hand, and Azure DevOps hands it an ID card labeled iss, aud, sub.
Narration: after checking Use OIDC, the task requests an identity token that belongs only to this service connection from Azure DevOps.
Shot 3 · 45–70s
Visual: the STS window checks the ID card: is the issuer registered, does the audience match, is the subject in the trust policy.
Narration: STS checks the provider and role trust policy in IAM item by item, and only issues temporary credentials if all pass.
Shot 4 · 70–90s
Visual: a temporary key labeled ASIA, with a 15-minute hourglass, opens the ECR and ECS doors.
Narration: temporary credentials expire after fifteen minutes by default; the pipeline uses them to push images and update services, with no long-lived keys throughout.
or score ≥ 70% on the quiz

Module 3 · Build and push to ECR

14:00 – 21:00 · Tags are for humans, digests are for machines: CI produces an “immutable tag + digest”, and all later environments deploy by the same digest
7 minECRPushImage@1 · aws ecrIMMUTABLE★★★★★
Learning objectives
  • Push in two ways: with the Toolkit's ECRPushImage@1 task, or in a AWSShellScript@1 step, using aws ecr get-login-password | docker login + docker push; know the trade-offs of each.
  • Understand ECR authentication tokens: GetAuthorizationToken The returned token is valid for 12 hours and has the same permissions as the IAM principal that obtained it; the username is fixed as AWS.
  • Design pipeline tags: $(Build.BuildId)-<short SHA>; understand why an IMMUTABLE repository makes latest the second push fail.
  • After pushing, read the image digest, and write it as an output variable for later stages, and understand the relationship between ECS's “image digest resolution (version consistency)” and “deploy by digest”.
Prerequisites: The ECR section of Docker course Lesson 4 (scanning, lifecycle, and pull through cache are already covered there). Importance:★★★★★

What: what pushing to ECR requires

ECR is an OCI image repository. Before pushing, the Docker client needs a registry credential: call ecr:GetAuthorizationToken to get a base64-encoded AWS:<password>, valid for 12 hours, with the same permissions as the IAM principal that obtained it. Docker then uploads layers (InitiateLayerUpload / UploadLayerPart / CompleteLayerUpload), and finally PutImage writes the manifest and points the tag to it. The SHA-256 of the manifest content is the digest (sha256:…).

Two push methods

ECRPushImage@1 (Toolkit)AWSShellScript@1 + docker/aws cli
Logintask fetches the token and logs in internallyaws ecr get-login-password | docker login --username AWS --password-stdin
InputsimageSource (imagename / imageid),sourceImageName,sourceImageTag (default latest),repositoryName,pushTag (default latest),autoCreateRepository,outputVariableany docker/buildx parameters (multi-platform, cache, SBOM, provenance)
OutputoutputVariable is account.dkr.ecr.region.amazonaws.com/repository:tag (not the digest)Available aws ecr describe-images or buildx --metadata-file get the digest
Suitable forsimple scenarios, classic pipelineswhen you need buildx, caching, digest output (used in this course)
Pitfall: the ECRPushImage defaults forsourceImageTag and pushTag are both latest. When the repository is IMMUTABLE, the second run's push latest will fail (ImageTagAlreadyExistsException). Always explicitly set pushTag: $(imageTag).

Why: why use “immutable tag + deploy by digest”

  • Traceable: the tag 1873-a1b2c3d maps directly to the build number and commit.
  • What you test is what you ship: dev validates digest A; if prod deploys by “tag” and the tag is overwritten in between (MUTABLE repository), prod gets B. Deploying by digest fundamentally avoids this.
  • Reliable rollback: the previous task definition revision records the previous digest, so rollback doesn't depend on whether the “tag is still where it was”.

How: ECS image digest resolution (version consistency)

Even when the task definition uses a tag, ECS by default resolves the tag to a digest at deployment time: the first task the service starts determines the digest, and afterwards all of that service's tasks and later service updates use this digest (the container definition parameter versionConsistency can control it; Fargate Linux platform version 1.3.0+ supports it). A forced new deployment re-resolves. This prevents “mixed versions within the same service”, but cannot prevent “the tag already pointing to a different image at prod deployment time”. So this course writes directly into the task definition repository@sha256:…, so ECS does not need to resolve it again.

When: tag strategy recommendations

TagPurposeUsed for deployment?
$(Build.BuildId)-$(short SHA)Unique per build; never overwritten in an IMMUTABLE repositoryFor human reading and lookup; deployment uses its corresponding digest
1.4.0 (semantic version)Added as an extra tag by the pipeline at release timeSame as above
latestConvenient for local developmentDo not use for deployment; do not push it to IMMUTABLE repositories
Common misconceptions① “Once IMMUTABLE, images can't be deleted”—images can be deleted (lifecycle policies also delete them); you just can't repoint an existing tag to a different image. ② “The digest is the image ID”—docker images 's IMAGE ID is the hash of the config, while the registry digest is the hash of the manifest; the two differ, and deployment must use the registry digest (RepoDigests). ③ “A multi-platform image has only one digest”—the manifest list (index) has its own digest, and each platform's manifest has its own digest too; deploy using the index digest.

Data flow in the CI stage

checkoutBuild.SourceVersion docker buildtag 1873-a1b2c3d ecr get-login-passwordToken 12h docker pushlayers → PutImage ECR myappIMMUTABLE describe-imagesimageDigest = sha256:9f2c… ##vso[task.setvariableIMAGE_DIGEST; isOutput=true] DeployDev / DeployProd: stageDependencies.Build.Push.outputs['img.IMAGE_DIGEST'] Also save image.json as a pipeline artifact (for auditing and manual rollback)
Figure 3-1: CI builds only once; the digest is passed downstream as an output variable and an artifact

Tag vs digest

Tag (readable pointer)myapp:1873-a1b2c3dcan be repointed when MUTABLEfixed when IMMUTABLE digest (content-addressed)myapp@sha256:9f2c…if content changes, digest changesalways points to the same image ECS task definition"image": "…/myapp@sha256:9f2c…"each revision pins one digestrollback = return to the old revision
Figure 3-2: deployments reference the digest; tags are left for humans

Interactive simulator: tag drift vs deploying by digest

Switch the repository mode and the deployment reference method, click the action buttons in turn, and observe whether the image dev validated matches the image prod actually runs.

Repository:Deployment reference:
ECR: myapp
dev (verified)
prod (actually running)

Core commands and tasks

Commands / tasksPurposeNotes
aws ecr get-login-passwordGet registry password (12 hours)Used with docker login --username AWS --password-stdin {account}.dkr.ecr.{region}.amazonaws.com
aws ecr describe-imagesLook up the digest, push time, and scan status for a tag--image-ids imageTag=T --query 'imageDetails[0].imageDigest'
aws ecr batch-get-imageGet the manifestCan be used to add a tag to an existing image (put-image)
aws ecr wait image-scan-completeWait for the scan to complete on pushthen use describe-image-scan-findings as a gate before the
ECRPushImage@1Toolkit push taskBe sure to pushTag
##vso[task.setvariable variable=X;isOutput=true]set the output variableThe step needs name:, and across stages use stageDependencies.stage.job.outputs['step name.X']

Method A: ECRPushImage@1

- task: Docker@2
  displayName: Build
  inputs:
    command: build
    repository: myapp
    tags: $(Build.BuildId)
- task: ECRPushImage@1
  displayName: Push to ECR
  inputs:
    awsCredentials: aws-myapp-dev
    regionName: ca-central-1
    imageSource: imagename
    sourceImageName: myapp
    sourceImageTag: $(Build.BuildId)
    repositoryName: myapp
    pushTag: $(Build.BuildId)       # don't keep the default latest
    outputVariable: pushedImage     # value looks like 111122223333.dkr.ecr.ca-central-1.amazonaws.com/myapp:1873

Method B: AWSShellScript@1 (used in this lesson; gives you the digest)

#!/usr/bin/env bash
# Called by AWSShellScript@1: credentials and AWS_REGION are already injected into the environment
set -euo pipefail
REPO="${REPO:-myapp}"
# Tag = build number-short commit SHA (Azure Pipelines expressions have no substring function, so build it in the script)
IMAGE_TAG="${IMAGE_TAG:-${BUILD_BUILDID}-${BUILD_SOURCEVERSION:0:7}}"
ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
ECR="${ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com"

aws ecr get-login-password | docker login --username AWS --password-stdin "$ECR"
# Idempotent: when you “re-run” the same build, BuildId stays the same and an IMMUTABLE repository rejects duplicate pushes, so check first, then push
if aws ecr describe-images --repository-name "$REPO" --image-ids imageTag="$IMAGE_TAG" >/dev/null 2>&1; then
  echo "tag $IMAGE_TAG already in ECR, reuse it"
else
  docker build --pull -t "$ECR/$REPO:$IMAGE_TAG" \
    --label org.opencontainers.image.revision="${BUILD_SOURCEVERSION:-unknown}" .
  docker push "$ECR/$REPO:$IMAGE_TAG"
fi

DIGEST=$(aws ecr describe-images --repository-name "$REPO" \
  --image-ids imageTag="$IMAGE_TAG" --query 'imageDetails[0].imageDigest' --output text)
echo "digest: $DIGEST"
echo "##vso[task.setvariable variable=IMAGE_TAG;isOutput=true]$IMAGE_TAG"
echo "##vso[task.setvariable variable=IMAGE_DIGEST;isOutput=true]$DIGEST"
echo "##vso[task.setvariable variable=IMAGE_URI;isOutput=true]$ECR/$REPO@$DIGEST"
printf '{"repository":"%s","tag":"%s","digest":"%s"}\n' "$REPO" "$IMAGE_TAG" "$DIGEST" > "$BUILD_ARTIFACTSTAGINGDIRECTORY/image.json"
docker logout "$ECR"   # on a self-hosted agent, don't leave the registry credentials in ~/.docker/config.json
Login Succeeded
...
1873-a1b2c3d: digest: sha256:9f2c6c1d0e…41ab size: 1786
digest: sha256:9f2c6c1d0e…41ab
Removing login credentials for 111122223333.dkr.ecr.ca-central-1.amazonaws.com

How to verify:docker push The digest printed on the last line matches describe-images . Common mistakes: In a bash step (non-AWS task) that calls this script → no credentials. Production use:image.json Publish it as an artifact, so during an incident you can quickly answer “which commit is production running?”

Lab 3: CI stage — build, push, output digest (about 6 min)

Add the push script to the repository: in the myapp repository, create deploy/push.sh (see the “Commands” tab, Method B),chmod +x deploy/push.sh then commit.
Create the Build stage of the pipeline file
trigger:
  branches: { include: [ main ] }
pool:
  vmImage: ubuntu-latest
variables:
  awsRegion: ca-central-1
stages:
- stage: Build
  jobs:
  - job: Push
    steps:
    - checkout: self
    - task: AWSShellScript@1
      name: img                           # output variable prefix
      displayName: Build & push to ECR
      inputs:
        awsCredentials: aws-myapp-dev
        regionName: $(awsRegion)
        scriptType: filePath
        filePath: deploy/push.sh
        disableAutoCwd: true
        workingDirectory: $(Build.SourcesDirectory)
      env:
        REPO: myapp                       # the tag is generated by the script as BuildId-short SHA
    - publish: $(Build.ArtifactStagingDirectory)/image.json
      artifact: image

Note: Azure Pipelines expressions have no substring function, so the tag is built push.sh in the script with Bash's ${BUILD_SOURCEVERSION:0:7} to build it, and expose it as output variables img.IMAGE_TAG ; export them together. AWSShellScript defaults the working directory to the script's folder, so here we use disableAutoCwd + workingDirectory to make docker build . run from the repository root.

Run and verify
source ~/ado-aws.env
aws ecr describe-images --repository-name $REPO \
  --query 'sort_by(imageDetails,&imagePushedAt)[-3:].[imageTags[0],imageDigest,imageScanStatus.status]' --output table
------------------------------------------------------------------
|                         DescribeImages                         |
+--------------+---------------------------------+---------------+
|  1873-a1b2c3d|  sha256:9f2c6c1d0e…41ab         |  COMPLETE     |
+--------------+---------------------------------+---------------+
Verify the immutable tag: in the pipeline UI, click “Re-run” on the same run; the log should show already in ECR, reuse it (the script's idempotent handling). Then manually test overwriting the same tag:
aws ecr get-login-password | docker login --username AWS --password-stdin $ECR
docker pull $ECR/$REPO:1873-a1b2c3d
docker tag $ECR/$REPO:1873-a1b2c3d $ECR/$REPO:test-immutable && docker push $ECR/$REPO:test-immutable
echo "# change" >> README.md; docker build -t $ECR/$REPO:test-immutable . && docker push $ECR/$REPO:test-immutable
tag invalid: The image tag 'test-immutable' already exists in the 'myapp' repository and cannot be overwritten because the repository is immutable.

Cleanup: aws ecr batch-delete-image --repository-name $REPO --image-ids imageTag=test-immutable; git checkout README.md.

Acceptance The Build stage succeeds; ECR shows BuildId-SHA tag; pipeline artifact image digest in it matches ECR.

Case 1: “same tag, two images”

Problem: MUTABLE repository, and the pipeline always pushes :release. Dev passed verification on Friday; on Monday, before the prod deployment, someone pushed a tag with the same name from a branch, and prod went live with untested code. Fix: Change the repository to IMMUTABLE; change the tag to BuildId-SHA; the CD stage only accepts the digest output variable from CI. Result: prod can never deploy an image that dev has not verified.

Case 2: leftover ECR credentials on a self-hosted agent

Problem: A shared self-hosted agent ~/.docker/config.json still had ECR login credentials (valid for 12 hours), and a pipeline from another project used them to pull the image. Fix: After pushing, run docker logout; give each job its own DOCKER_CONFIG directory (for example $(Agent.TempDirectory)/docker); or switch to a Microsoft-hosted or ephemeral agent.

Case 3: scan gate

Problem: Images with CRITICAL vulnerabilities must be blocked from reaching prod. Fix: In CI, aws ecr wait image-scan-complete then read findingSeverityCounts.CRITICAL, and if greater than 0, then exit 1; enhanced scanning (Inspector) is billed according to its pricing, so you can turn it on only for the main branch. Limitations: Basic scanning only covers OS packages; Python dependencies need enhanced scanning or an extra dependency scan in CI.

Common errors and fixes

no basic auth credentials

Cause: The push ran without docker login, or the registry hostname you logged in to does not match the push target (different account ID / region).

docker info 2>/dev/null | grep -i registry; cat ~/.docker/config.json | jq '.auths | keys'

Fix: Re-login to {account}.dkr.ecr.{region}.amazonaws.com ; make sure the image tag prefix matches the login host exactly.

denied: Your authorization token has expired. Reauthenticate and try again.

Cause: The ECR token is older than 12 hours (common on long-running self-hosted agents that reuse an old login).

Fix: Re-run the login step in every job get-login-password | docker login.

An error occurred (AccessDeniedException) when calling the GetAuthorizationToken operation: User: arn:aws:sts::…:assumed-role/ado-myapp-dev-deploy/aws-vsts-tools is not authorized to perform: ecr:GetAuthorizationToken on resource: *

Cause: The role is missing ecr:GetAuthorizationToken, or the permission is limited to a repository ARN (it only supports "*").

Fix: Put it in its own statement: "Action":"ecr:GetAuthorizationToken","Resource":"*".

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

Cause: Pushing the same tag twice to an IMMUTABLE repository (common when ECRPushImage defaults to latest, or when “re-running” the same build — BuildId doesn't change, so the tag doesn't either).

Fix: Include BuildId in the tag; on re-run, first check whether the tag already exists and reuse its digest directly: aws ecr describe-images --image-ids imageTag=$T if it succeeds, skip the build.

name unknown: The repository with name 'myapp' does not exist in the registry with id '111122223333'

Cause: The repository was not created, the region is wrong, or you pushed to another account's registry hostname.

Fix: Create the repository ahead of time with IaC (avoid doing it in the pipeline, which would need autoCreateRepository, giving the role overly broad ecr:CreateRepository permissions).

Command-line exercises
1. Look up the digest for tag 1873-a1b2c3d and build an image reference that ECS can use.
D=$(aws ecr describe-images --repository-name myapp --image-ids imageTag=1873-a1b2c3d --query 'imageDetails[0].imageDigest' --output text)
echo "$ECR/myapp@$D"
2. Without rebuilding, add a 1.4.0 tag to an existing image.
M=$(aws ecr batch-get-image --repository-name myapp --image-ids imageTag=1873-a1b2c3d --query 'images[0].imageManifest' --output text)
aws ecr put-image --repository-name myapp --image-tag 1.4.0 --image-manifest "$M"
Scenario analysis
The team says: “ECS resolves the tag to a digest, so writing the tag in the task definition is enough.” Do you agree?

Partly agree. ECS's version consistency guarantees that within one service all tasks (including later scaling) run the same digest, but resolution happens at deploy time: if a MUTABLE tag is repointed after dev verification, the prod deployment resolves to a new digest. Forcing a new deployment also re-resolves it. Writing the digest into the task definition guarantees both cross-environment consistency and precise rollback.

Verified teaching videos

▶
Amazon Elastic Container Registry (Amazon ECR) Explained | Amazon Web Services — Amazon Web Services
English · ECR basics (duration and date not verified)
▶
AWS re:Invent 2023 - Dive deep into Amazon ECR (CON405) — AWS Events
English · ECR storage, replication and security in depth

Official documentation

Video storyboard script (about 60 seconds)

Shot 1 · 0–20s
Visual: tag 1.0 is like a sticky note on image box A; it is then peeled off and stuck on box B.
Narration: a mutable tag is just a sticky note, which can be stuck onto a different image at any time.
Shot 2 · 20–40s
Visual: box A has a sha256 fingerprint engraved on it; no matter how the sticky note changes, the fingerprint stays the same.
Narration: a digest is the fingerprint of the image content; it stays the same as long as the content does.
Shot 3 · 40–60s
Visual: the pipeline passes a card with the digest from the Build stage; dev and prod both use the card to pick up the same box.
Narration: CI builds once and passes the digest to every environment, so what you test is what you ship.
or score ≥ 70% on the “Quiz”

Module 4 · Deploy to ECS on Fargate

21:00 – 30:00 · Three deployment steps: register a new task definition revision → update the service → wait for stability; on failure, the circuit breaker rolls back automatically, but the pipeline must be able to tell “stable on the new version” from “stable on the rolled-back old version”
9 minregister-task-definition · update-servicedeploymentCircuitBreaker★★★★★
Learning objectives
  • Keep the task definition as code in the repository (template + placeholders); render the digest in the pipeline and register a new revision.
  • Understand iam:PassRole: when you register a task definition that references the execution role / task role and use it to update a service, the pipeline role must be allowed to “pass” those roles to ECS.
  • Be able to use aws ecs wait services-stable (polls every 15 seconds, exits with 255 after 40 attempts, about 10 minutes) and verify the PRIMARY deployment's taskDefinition and rolloutState.
  • Explain the circuit breaker's two-phase detection, its threshold (BOUNDED_PERCENT defaults to 50%, bounded between 3 and 200 tasks), and its rollback target (the most recent COMPLETED deployment), and complete one rollback rehearsal.
Prerequisites: Service connections from Module 2, digest output from Module 3; task definition fields from Lesson 4 of the Docker course. Importance:★★★★★

What: what an ECS deployment is made of

  • Task definition revision (myapp-dev:7): immutable. Changing the image = registering a new revision.
  • Service deployment (ecs-svc/…): update-service --task-definition Creates a new PRIMARY deployment, and the old one becomes ACTIVE until all of its old tasks are replaced.
  • Rolling parameters: minimumHealthyPercent (rounded up) and maximumPercent (rounded down). In this lesson, desired=1, min=100, max=200: start one new task first, and stop the old task only after the new one is healthy. Zero downtime.
  • Circuit breaker: deploymentCircuitBreaker={enable=true,rollback=true}, applies only to the ECS (rolling update) deployment controller.

Why: why the pipeline shouldn't only check “update-service succeeded”

update-service It only submits the deployment and returns immediately; new tasks may fail to pull the image, fail health checks, or keep restarting. The pipeline must wait for and determine the result. A subtler issue: after the circuit breaker rolls back, the service also becomes “stable,”wait services-stable so the wait returns success. If the pipeline shows green, the team will think the new version went live.

How: the five steps of the deployment script

  1. Render: in the repository's deploy/taskdef.json template, replace the __IMAGE__,__FAMILY__,__VERSION__ etc. with this run's values (for the image, use repository@sha256:…).
  2. Register: aws ecs register-task-definition --cli-input-json file://td.json → new revision ARN. This step checks iam:PassRole (execution role, task role).
  3. Update: aws ecs update-service --cluster C --service S --task-definition new ARN.
  4. Wait: aws ecs wait services-stable (success condition: the service has only one deployment and runningCount = desiredCount).
  5. Check: read the PRIMARY deployment and require taskDefinition == new ARN and rolloutState == COMPLETED; otherwise print the recent service events and the stopped tasks' stoppedReason, and fail the stage with a non-zero exit code.

How the circuit breaker decides a failure (verified)

  • Phase 1: watches whether new tasks can reach RUNNING; Phase 2: health checks after reaching RUNNING (ELB, Cloud Map, container healthCheck). If failed tasks in either phase accumulate to the threshold, the deployment is marked as failed.
  • Threshold: thresholdConfiguration Defaults to BOUNDED_PERCENT 50%, meaning 50% of the desired count, but no fewer than 3 and no more than 200; when desired=1 the threshold is 3. COUNT / UNBOUNDED_PERCENT can also be used. resetOnHealthyTask Controls whether the counter is reset to zero once tasks are healthy.
  • Rollback: rollback=true on failure, it rolls back to the most recent COMPLETED deployment (its task definition revision). Rollback details appear in the service events; the rolloutState set to FAILED is the failed deployment.
  • You can also add CloudWatch alarm (alarms configuration) to decide failure based on business metrics; if either condition is met, it fails.

What iam:PassRole is

Roles in a task definition executionRoleArn/taskRoleArn are permissions handed to ECS to use. To prevent privilege escalation (a low-privilege user putting a high-privilege role into a task definition), AWS requires the caller to hold iam:PassRole. Best practice is to allow passing only specific roles, and add a condition iam:PassedToService = ecs-tasks.amazonaws.com.

When: does Toolkit have an ECS deployment task?

The AWS Toolkit for Azure DevOps currently does not have a dedicated “ECS deployment” task (the task list includes AWSCLI, AWSShellScript, ECRPushImage/PullImage, CloudFormation, CodeDeploy, Lambda, Beanstalk, Secrets Manager, SSM, etc.), so ECS deployments use AWSShellScript@1 + AWS CLI. If the team already manages the service with CloudFormation/CDK, you can also use CloudFormationCreateOrUpdateStack@1 to pass the new digest in as a parameter.

MethodProsCons
CLI script (this lesson)Transparent, easy to debug, precise permissionsYou must write the wait and check logic yourself
CloudFormation parameter updateConsistent with IaC, stack rollbackSlow stack updates; you need to understand how the ECS circuit breaker and stack rollback interact
CodeDeploy blue/greenTraffic shifting, hooksRequires ALB and CodeDeploy resources; ECS already has native blue/green (Lesson 4 of the Docker course)
Common misconceptions① “wait services-stable success = the new version is live”——after a rollback it also becomes stable. ② “--force-new-deployment can release a new image”——only when the task definition references a mutable tag does it “happen” to pull the new image, which is exactly what should be avoided. ③ “The circuit breaker monitors application error rates”——it only watches task startup and health checks; business metrics need CloudWatch alarms to roll back. ④ “minimumHealthyPercent=100 guarantees zero downtime”——you also need correct health checks and graceful shutdown (SIGTERM handling,stopTimeout).

Deployment pipeline → ECS control plane

① Render taskdef.json__IMAGE__ → @sha256:… ② RegisterTaskDefinitionCheck iam:PassRole → myapp-dev:8 ③ UpdateServiceNew PRIMARY deployment ④ wait services-stable15s × 40 attempts (up to about 10 min) ECS service scheduler (min 100% / max 200%) Old task :7 RUNNING New task :8 PROVISIONING Circuit breaker countFailures 0 / threshold 3 ⑤ Check PRIMARYtaskDefinition==:8 and COMPLETED Failures ≥ threshold → rolloutState=FAILED → roll back to the most recent COMPLETED (:7)The service then “stabilizes” on :7 —— wait succeeds, but step ⑤ must fail the pipeline
Figure 4-1: step ⑤ is the key to preventing “the pipeline turning green after a rollback”

Circuit breaker threshold quick calculation

desiredCount50% × desiredThreshold (bounded to 3–200)
10.53
423
1055
1000500200

Animation: rolling deployment + circuit breaker rollback

Service desired=2, min 100% / max 200%. Choose to deploy a “good image” or a “bad image (health check fails)”, and watch the old and new tasks, the circuit breaker count, the PRIMARY deployment state, and the step ⑤ check result.

Deployments
Task

Core commands

CommandPurposeKey parameters / notes
aws ecs register-task-definitionRegister a new revision--cli-input-json file://td.json; outputs taskDefinition.taskDefinitionArn
aws ecs update-serviceSwitch the service to the new revision--task-definition,--deployment-configuration (circuit breaker / alarms)
aws ecs wait services-stableWait for stabilityChecks every 15 seconds; exits with code 255 after 40 failed checks
aws ecs describe-servicesDeployment status and eventsdeployments[?status=='PRIMARY'],events[:10]
aws ecs list-tasks --desired-status STOPPED + describe-tasksWhy tasks stoppedstoppedReason,containers[].reason,exitCode
aws ecs describe-task-definitionView a given revisionFind the previous revision for a manual rollback

Task definition template (repository deploy/taskdef.json)

{
  "family": "__FAMILY__",
  "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": "__IMAGE__",
    "essential": true,
    "portMappings": [{ "containerPort": 5000, "protocol": "tcp" }],
    "environment": [ { "name": "APP_VERSION", "value": "__VERSION__" } ],
    "healthCheck": {
      "command": ["CMD-SHELL", "python -c \"import urllib.request; urllib.request.urlopen('http://127.0.0.1:5000__HEALTH_PATH__', timeout=3)\" || exit 1"],
      "interval": 10, "timeout": 5, "retries": 3, "startPeriod": 15
    },
    "stopTimeout": 30,
    "logConfiguration": { "logDriver": "awslogs", "options": {
      "awslogs-group": "/ecs/myapp", "awslogs-region": "__REGION__", "awslogs-stream-prefix": "__FAMILY__" } }
  }]
}

The myapp image is based on python:slim and has no curl, so the container health check uses the Python standard library to send requests. __HEALTH_PATH__ Normally set to /healthz; during the rollback rehearsal, deliberately change it to a nonexistent path.

Deployment script (repository deploy/ecs-deploy.sh)

#!/usr/bin/env bash
# Called by AWSShellScript@1; requires environment variables CLUSTER SERVICE FAMILY IMAGE_URI APP_VERSION
set -euo pipefail
: "${CLUSTER:?}" "${SERVICE:?}" "${FAMILY:?}" "${IMAGE_URI:?}"
HEALTH_PATH="${HEALTH_PATH:-/healthz}"
ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
case "$IMAGE_URI" in *@sha256:*) ;; *) echo "IMAGE_URI must be a digest reference"; exit 2;; esac

# ① Render
sed -e "s#__IMAGE__#${IMAGE_URI}#" -e "s#__FAMILY__#${FAMILY}#g" -e "s#__VERSION__#${APP_VERSION:-unknown}#" \
    -e "s#__ACCOUNT_ID__#${ACCOUNT_ID}#" -e "s#__REGION__#${AWS_REGION}#" -e "s#__HEALTH_PATH__#${HEALTH_PATH}#" \
    deploy/taskdef.json > td.json
# ② Register
NEW_TD=$(aws ecs register-task-definition --cli-input-json file://td.json \
  --query 'taskDefinition.taskDefinitionArn' --output text)
echo "registered: $NEW_TD"
# ③ Update service
aws ecs update-service --cluster "$CLUSTER" --service "$SERVICE" --task-definition "$NEW_TD" \
  --query 'service.deployments[0].[id,rolloutState]' --output text
# ④ Wait (don't exit immediately on failure; collect info first)
set +e; aws ecs wait services-stable --cluster "$CLUSTER" --services "$SERVICE"; WAIT_RC=$?; set -e
# ⑤ Check PRIMARY deployment
read -r PRIMARY_TD STATE REASON < <(aws ecs describe-services --cluster "$CLUSTER" --services "$SERVICE" \
  --query "services[0].deployments[?status=='PRIMARY']|[0].[taskDefinition,rolloutState,rolloutStateReason]" --output text)
echo "wait rc=$WAIT_RC primary=$PRIMARY_TD state=$STATE"
if [[ "$PRIMARY_TD" == "$NEW_TD" && "$STATE" == "COMPLETED" ]]; then
  echo "##vso[task.setvariable variable=DEPLOYED_TD;isOutput=true]$NEW_TD"
  echo "deployment succeeded"; exit 0
fi
echo "##vso[task.logissue type=error]ECS deployment did not complete on $NEW_TD (primary=$PRIMARY_TD, state=$STATE, reason=$REASON)"
aws ecs describe-services --cluster "$CLUSTER" --services "$SERVICE" \
  --query 'services[0].events[:8].[createdAt,message]' --output text
for t in $(aws ecs list-tasks --cluster "$CLUSTER" --service-name "$SERVICE" --desired-status STOPPED --query 'taskArns[:3]' --output text); do
  aws ecs describe-tasks --cluster "$CLUSTER" --tasks "$t" \
    --query 'tasks[0].[taskDefinitionArn,stoppedReason,containers[0].reason,containers[0].healthStatus]' --output text
done
exit 1
registered: arn:aws:ecs:ca-central-1:111122223333:task-definition/myapp-dev:2
ecs-svc/4729120998764512345	IN_PROGRESS
wait rc=0 primary=arn:aws:ecs:ca-central-1:111122223333:task-definition/myapp-dev:2 state=COMPLETED
deployment succeeded

How to verify: Open in a browser http://{task-public-IP}:5000/ Shows [1873-a1b2c3d] Hello from … (for how to get the public IP, see step 4 in the “Lab” tab). Common mistakes:describe-services In the --query backticks for literal values are interpreted by some shells, so this lesson uses single-quoted strings throughout 'PRIMARY'.

Lab 4: automatic deployment to dev (about 8 min)

Commit the task definition template and deployment script: add the “Commands” tab's deploy/taskdef.json and deploy/ecs-deploy.sh to the repository (chmod +x).
Create the environment in Azure DevOps: Pipelines → Environments → New environment, name myapp-aws-dev, and select None for resource. No approval for dev.
Add the DeployDev stage to the pipeline
- stage: DeployDev
  dependsOn: Build
  jobs:
  - deployment: Ecs
    environment: myapp-aws-dev
    variables:
      imageUri: $[ stageDependencies.Build.Push.outputs['img.IMAGE_URI'] ]
      imageTag: $[ stageDependencies.Build.Push.outputs['img.IMAGE_TAG'] ]
      aws.rolecredential.maxduration: "1800"     # wait for stability up to about 10 minutes; leave a margin
    strategy:
      runOnce:
        deploy:
          steps:
          - checkout: self                         # deploy jobs do not check out by default
          - task: AWSShellScript@1
            name: ecs
            displayName: Deploy myapp-dev
            inputs:
              awsCredentials: aws-myapp-dev
              regionName: $(awsRegion)
              scriptType: filePath
              filePath: deploy/ecs-deploy.sh
              disableAutoCwd: true
              workingDirectory: $(Build.SourcesDirectory)
            env:
              CLUSTER: myapp-lab
              SERVICE: myapp-dev
              FAMILY: myapp-dev
              IMAGE_URI: $(imageUri)
              APP_VERSION: $(imageTag)

Key points: ① to read output variables across stages, you must set them at the job level variables and reference them with stageDependencies.stage.job.outputs['step name.variable']; ② aws.rolecredential.maxduration set to 1800; the role's MaxSessionDuration is 3600, which satisfies “≤”.

Push to main and watch the run, and after a successful deployment, get the task's public IP and visit:
source ~/ado-aws.env
T=$(aws ecs list-tasks --cluster $CLUSTER --service-name myapp-dev --query 'taskArns[0]' --output text)
ENI=$(aws ecs describe-tasks --cluster $CLUSTER --tasks $T \
  --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/; curl -s http://$IP:5000/healthz
[1873-a1b2c3d] Hello from ip-172-31-7-41.ca-central-1.compute.internal, hits=N/A (redis not connected)
ok

This lesson does not deploy Redis, so hits showing N/A is expected (the app is designed to degrade when a dependency is unavailable).

Confirm that ECS recorded the digest
aws ecs describe-tasks --cluster $CLUSTER --tasks $T --query 'tasks[0].containers[0].[image,imageDigest]' --output text
111122223333.dkr.ecr.ca-central-1.amazonaws.com/myapp@sha256:9f2c…41ab	sha256:9f2c…41ab
Acceptance The DeployDev stage is green, and the log contains deployment succeeded; a deployment record appears under Environments → myapp-aws-dev; the task's imageDigest matches the digest output by the Build stage. The rollback rehearsal goes in theCapstone lab.

Case 1: rolled back, yet the pipeline is green

Problem: The team's deployment step only has update-service + wait services-stable. A configuration error made the new tasks fail health checks, the circuit breaker rolled back, the service stabilized on the old revision, the pipeline was green, and the release ticket was closed. Only three days later did they discover the new feature had never gone live. Fix: Add the step ⑤ PRIMARY check, and use ##vso[task.logissue type=error] to write the failure reason into the run summary.

Case 2: privilege escalation via an overly broad PassRole

Problem: The pipeline role has iam:PassRole on *. In a task definition, someone changed the taskRoleArn to the account's admin role, and the task gained admin permissions. Fix: Allow PassRole only for myappTaskExecutionRole and myappTaskRole, and add a iam:PassedToService condition; keep the task definition template in a protected branch; changes require code review.

Case 3: the wait times out but the deployment is still in progress

Problem: Large image + slow-starting Java service, desired=20,wait services-stable hit a 10-minute timeout (exit code 255), but the deployment eventually succeeded. Fix: In the script, replace the built-in waiter with a loop (for example, up to 30 minutes, querying every 30 seconds rolloutState), and also raise aws.rolecredential.maxduration and the role's MaxSessionDuration to 3600; or enable an “early success condition”.

Common errors and fixes

AccessDeniedException: User: arn:aws:sts::111122223333:assumed-role/ado-myapp-dev-deploy/aws-vsts-tools is not authorized to perform: iam:PassRole on resource: arn:aws:iam::111122223333:role/myappTaskExecutionRole

Cause: Registering the task definition / updating the service requires passing the execution role to ECS.

Fix: Add iam:PassRole (resource is the role ARN, condition iam:PassedToService=ecs-tasks.amazonaws.com).

ClientException: Container.image repository should not be null or empty / Invalid 'containerDefinitions[0].image'

Cause: The output variable was not passed along,IMAGE_URI is empty, or still shows the $(imageUri) literal string.

echo "IMAGE_URI=[$IMAGE_URI]"

Fix: Check the Build stage step's name: img,isOutput=true, and the reference path stageDependencies.Build.Push.outputs['img.IMAGE_URI'] (stage and job names must match in case).

Waiter ServicesStable failed: Max attempts exceeded

Cause: The service did not stabilize within 10 minutes: tasks kept failing (check the stop reason), or the deployment itself is slow.

aws ecs describe-services --cluster myapp-lab --services myapp-dev --query 'services[0].events[:8].[createdAt,message]' --output text

Fix: Decide based on the events; for slow deployments, use a custom poll to extend the wait.

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

Cause: The circuit breaker triggered (the actual service event text is authoritative). Common root causes: image pull failure (execution role / network), container exits right after starting, failing health checks.

aws ecs list-tasks --cluster myapp-lab --service-name myapp-dev --desired-status STOPPED
aws ecs describe-tasks --cluster myapp-lab --tasks <ARN> --query 'tasks[0].[stoppedReason,containers[0].reason,containers[0].exitCode]'

Fix: Follow the Module 7 troubleshooting tree; after fixing, re-run the pipeline (this registers a new revision).

InvalidParameterException: The container web does not exist in the task definition / Fargate requires task definition to have execution role ARN to support ECR images

Cause: A template field was broken, or is missing executionRoleArn (Fargate needs it to pull images from ECR and to write awslogs).

Fix: Validate the rendered result locally with jq . td.json ; keep executionRoleArn.

Command-line exercises
1. Use one command to output the task definition and rolloutState of the service's PRIMARY deployment.
aws ecs describe-services --cluster myapp-lab --services myapp-dev \
  --query "services[0].deployments[?status=='PRIMARY']|[0].[taskDefinition,rolloutState]" --output text
2. Manually roll back to the previous revision myapp-dev:6.
aws ecs update-service --cluster myapp-lab --service myapp-dev --task-definition myapp-dev:6
aws ecs wait services-stable --cluster myapp-lab --services myapp-dev
Scenario analysis
The new version starts normally and passes health checks, but the 5xx error rate rose from 0.1% to 8%. The circuit breaker did not roll back. Why? How should the pipeline change?

The circuit breaker only looks at task startup and health checks; business error rates are outside its scope. The service should be configured with a CloudWatch alarm for rollback (deploymentConfiguration.alarms, with an alarm metric such as the ALB 5xx ratio), or add post-deployment verification in the pipeline (smoke test + metric query), and on failure roll back manually or automatically to the previous revision.

Verified teaching videos

▶
Circuit Breakers for Amazon ECS — Containers from the Couch
English · Circuit breaker demo (duration and date not verified; thresholds follow the official docs verified in this lesson)
▶
Deploying a Modern Application Stack to AWS Fargate with Amazon ECS - AWS Online Tech Talks — AWS Developers
English · Overall deployment flow on Fargate
▶
How to Setup AWS ECS Fargate with a Load Balancer | Step by Step — Be A Better Dev
English · Console walkthrough supplement (this lesson's lab does not use an ALB, to save costs)

Official documentation

Video storyboard script (about 75 seconds)

Shot 1 · 0–20s
Visual: the pipeline lights up three buttons in turn: register revision, update service, wait for stability.
Narration: an ECS deployment has only three steps, but after the third one you still need to ask: stable on which version?
Shot 2 · 20–50s
Visual: new tasks turn red one after another, counters 1, 2, 3; the circuit breaker trips, and the service switches back to the old revision.
Narration: when new task failures reach the threshold, the circuit breaker rolls the service back to the most recent successful deployment.
Shot 3 · 50–75s
Visual: the waiter shows a green check mark; next to it, a verdict box compares the PRIMARY revision number, and the result is red.
Narration: after a rollback the service is also stable, so the pipeline must compare the revision number of the primary deployment in order to report failure honestly.
or score ≥ 70% on the “Quiz”

Module 5 · Deploy to EKS and Lambda

30:00 – 38:00 · EKS permissions have two layers (whether IAM lets you get cluster info + what access entries let you do in Kubernetes); Lambda publishing is “publish an immutable version + move an alias”
8 minEKS access entries · Helm 4Lambda versions / aliasesEKS lab optional (US$0.10/hour)
Learning objectives
  • Explain kubectl The authentication chain for accessing EKS: aws eks get-token generate a presigned STS GetCallerIdentity token → EKS verifies identity → access entry mapping → access policy / RBAC authorization; distinguish 401 Unauthorized (does not know you) and 403 Forbidden (knows you but does not allow the action).
  • Create an access entry for the pipeline role and associate it with namespace-scoped access policy (for example, AmazonEKSEditPolicy limited to myapp namespace).
  • In AWSShellScript, use aws eks update-kubeconfig + helm upgrade --install --rollback-on-failure --wait (Helm 4) to deploy by digest.
  • Use update-function-code --publish to publish a Lambda version, and use the alias live weighted routing for a canary; rollback = point the alias back to the old version.
Prerequisites: Lesson 7 of the K8s course (EKS, access entries, Pod Identity); Helm basics. Importance:★★★★

What: the two layers of permissions in EKS

LayerWho decidesWhat the pipeline role needsFailure symptom
AWS API layerIAMeks:DescribeCluster (update-kubeconfig read endpoint and CA)AccessDeniedException … eks:DescribeCluster
Kubernetes authenticationEKS (IAM identity → access entry)The IAM role ARN access entry (authentication mode API or API_AND_CONFIG_MAP)error: You must be logged in to the server (Unauthorized)
Kubernetes authorizationEKS access policy + Kubernetes RBACAssociate an access policy (cluster or namespace scope), or an RBAC binding to the access entry's groupError from server (Forbidden): … cannot create resource "deployments" …

How: the authentication chain

  1. AWSShellScript injects temporary credentials (Module 2).
  2. aws eks update-kubeconfig --name lab Write a kubeconfig whose user section is an exec plugin: every kubectl call runs aws eks get-token --cluster-name lab.
  3. get-token Use the current credentials locally to generate a presigned STS GetCallerIdentity URL (with the cluster name header), encoded as k8s-aws-v1.… a Bearer token (short-lived, about 15 minutes).
  4. The API server hands the token to the EKS authentication component, which calls STS to get the caller's identity arn:aws:sts::…:assumed-role/ado-myapp-dev-deploy/session-name, and normalizes it to the IAM role ARN.
  5. Look up the role ARN's access entry → get the Kubernetes username and groups; none → 401.
  6. Authorization: first check the associated EKS access policy (for example, namespace myapp Edit), then RBAC; if neither allows it → 403.
Note The access entry's principalArn must be IAM role ARN (arn:aws:iam::…:role/ado-myapp-dev-deploy), not the STS assumed-role session ARN. Once access entries are enabled (API_AND_CONFIG_MAP or API), you cannot turn them off again; EKS Auto Mode clusters require access entries (verified in Lesson 7 of the K8s course).

Why not use the Kubernetes service connection in Azure DevOps

A Kubernetes service connection (kubeconfig / service account token) requires storing a long-lived Kubernetes credential in Azure DevOps, or relying on the exec plugin being available on the agent. For EKS, “AWS OIDC service connection + aws eks get-token” uses only short-lived credentials end to end, and authorization is centrally managed by access entries, which better fits this lesson's security goal. The trade-off is that you cannot directly use KubernetesManifest@1 tasks and the Environment's Kubernetes resource view, etc.

What: Lambda versions and aliases

  • $LATEST: a mutable “working copy”,update-function-code which you can modify.
  • Version (1, 2, 3…): an immutable snapshot of code and configuration taken at publish time; --publish makes the update and the publish a single atomic operation.
  • Alias (live): a named pointer to a version; callers (API Gateway, EventBridge) bind to the alias ARN. Aliases can be configured with weighted routing: one primary version + at most one additional version (AdditionalVersionWeights), and an alias with routing configuration cannot point to $LATEST.
  • Rollback: update-alias --function-version old-version, takes effect within seconds. CodeDeploy can automate linear/canary shifting (this lesson uses the CLI to demonstrate the principle).

The Toolkit's Lambda task

LambdaDeployFunction@1 supports deploymentMode: codeonly | codeandconfiguration, zip (local or S3),publish (default true),outputVariable (function ARN). It does not manage aliases, and its runtime dropdown is also stuck on older versions (such as python3.8), so this lesson uses the AWS CLI to complete “publish + alias switch”.

When: comparison

ECS (Module 4)EKSLambda
Release unitTask definition revisionDeployment / Helm release revisionFunction version
Traffic shiftingRolling (or native blue/green)Rolling (or Argo Rollouts, etc.)Alias weighting
RollbackCircuit breaker / old revision--rollback-on-failure / helm rollbackPoint the alias back to the old version
Extra pipeline permissionsiam:PassRoleAccess entry + access policylambda:UpdateAlias (and PassRole, if changing the execution role)
Common misconceptions① “Granting eks:* in IAM means you can use kubectl”——IAM permissions are not Kubernetes permissions; you also need an access entry. ② “An access entry with the session ARN”——it must be the role ARN. ③ “A Lambda alias can split 50/50 across three versions”——only one primary version plus one additional version. ④ “Helm 4 still uses --atomic”——Helm 4 renamed it to --rollback-on-failure, the old flags still work but produce a warning.

EKS: from the pipeline to Kubernetes authorization

AWSShellScriptTemporary credentials (OIDC) aws eks get-tokenPresigned GetCallerIdentity EKS authentication→ role ARN Access entryNone → 401 Access policy / RBACNot allowed → 403 Access entry example principalArn: …:role/ado-myapp-dev-deploy policy: AmazonEKSEditPolicy accessScope: namespace = [myapp] After passing helm upgrade --install myapp ./chart -n myapp --set image.repository=…/myapp --set image.digest=sha256:… --rollback-on-failure --wait --timeout 5m
Figure 5-1 IAM identity → access entry → access policy: all three gates must pass before deployment is allowed

Lambda: versions and aliases

$LATESTMutable Version 6 Version 7 Version 8 (new) --publish Alias live7: 90% · 8: 10% CallersEventBridge → …:myapp-report:live
Figure 5-2 Callers only recognize the alias; publishing and rolling back both move the alias

Animation A: kubectl request authentication and authorization (401 vs 403)

Animation B: Lambda alias weighted routing

Weight for new version 8: 10%
7
8

EKS authorization commands (run by cluster admin)

CommandPurposeNotes
aws eks describe-cluster --query cluster.accessConfigCheck authentication modeMust be API or API_AND_CONFIG_MAP
aws eks create-access-entryCreate an access entry for the IAM role--principal-arn (role ARN),--type STANDARD
aws eks associate-access-policyassociate access policy--policy-arn arn:aws:eks::aws:cluster-access-policy/AmazonEKSEditPolicy --access-scope type=namespace,namespaces=myapp
aws eks list-associated-access-policiesVerify authorizationTroubleshoot 403
kubectl auth can-i --list -n myappView permissions for the current identityPrint in the pipeline for easier troubleshooting
source ~/ado-aws.env
EKS=lab   # name of the EKS cluster created in Lesson 7 of the K8s course (skip the EKS section if there is no cluster)
ROLE_ARN=arn:aws:iam::$ACCOUNT_ID:role/ado-myapp-dev-deploy
aws eks describe-cluster --name $EKS --query 'cluster.accessConfig.authenticationMode'
aws eks create-access-entry --cluster-name $EKS --principal-arn $ROLE_ARN --type STANDARD
aws eks associate-access-policy --cluster-name $EKS --principal-arn $ROLE_ARN \
  --policy-arn arn:aws:eks::aws:cluster-access-policy/AmazonEKSEditPolicy \
  --access-scope type=namespace,namespaces=myapp
# the pipeline role also needs to read the cluster endpoint
aws iam put-role-policy --role-name ado-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\"}]}"
kubectl create namespace myapp
"API_AND_CONFIG_MAP"
{ "accessEntry": { "principalArn": "arn:aws:iam::111122223333:role/ado-myapp-dev-deploy", "type": "STANDARD", "username": "arn:aws:sts::111122223333:assumed-role/ado-myapp-dev-deploy/{{SessionName}}", ... } }
{ "associatedAccessPolicy": { "policyArn": "arn:aws:eks::aws:cluster-access-policy/AmazonEKSEditPolicy", "accessScope": { "type": "namespace", "namespaces": [ "myapp" ] } } }
namespace/myapp created

EKS deployment step in the pipeline (Helm 4)

- task: AWSShellScript@1
  displayName: Deploy to EKS (helm)
  inputs:
    awsCredentials: aws-myapp-dev
    regionName: ca-central-1
    scriptType: inline
    inlineScript: |
      set -euo pipefail
      curl -fsSL -o get_helm.sh https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-4
      bash get_helm.sh --version v4.3.2 >/dev/null && helm version --short
      aws eks update-kubeconfig --name lab --alias lab
      kubectl auth can-i create deployments -n myapp
      REPO_URI="${IMAGE_URI%@*}"; DIGEST="${IMAGE_URI#*@}"
      helm upgrade --install myapp ./chart -n myapp \
        --set image.repository="$REPO_URI" --set image.digest="$DIGEST" \
        --rollback-on-failure --wait --timeout 5m
      kubectl -n myapp get deploy myapp -o jsonpath='{.spec.template.spec.containers[0].image}{"\n"}'
  env:
    IMAGE_URI: $(imageUri)

Write the image in the chart as {{ .Values.image.repository }}@{{ .Values.image.digest }}. The Helm version preinstalled on the hosted agent is listed in the image manifest, so here we use the official get-helm-4 script to pin the version; you can also skip Helm and directly kubectl -n myapp set image deploy/myapp web="$IMAGE_URI" && kubectl -n myapp rollout status deploy/myapp --timeout=5m.

Lambda publish commands

CommandPurpose
aws lambda update-function-code --zip-file fileb://fn.zip --publishUpdate $LATEST and publish a new version (returns Version); for an image package, use --image-uri repository@sha256:…
aws lambda wait published-version-active --qualifier VWait for the new version to be available
aws lambda update-alias --name live --function-version 7 --routing-config '{"AdditionalVersionWeights":{"8":0.1}}'Canary: 10% to version 8
aws lambda update-alias --name live --function-version 8 --routing-config '{"AdditionalVersionWeights":{}}'Move everything to 8 and clear additional weights
aws lambda get-alias --name liveCheck the current target and weights

Lab 5A: Lambda alias canary (about 5 min, almost zero cost)

Create the function (one-time admin task)
source ~/ado-aws.env
aws iam create-role --role-name myappReportLambdaRole \
  --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 myappReportLambdaRole \
  --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
mkdir -p ~/fn && cd ~/fn
printf 'import os\ndef handler(event, context):\n    return {"version": os.environ.get("AWS_LAMBDA_FUNCTION_VERSION")}\n' > app.py
zip -q fn.zip app.py; sleep 10   # wait for the new role to become available in IAM
aws lambda create-function --function-name myapp-report --runtime python3.13 --handler app.handler \
  --role arn:aws:iam::$ACCOUNT_ID:role/myappReportLambdaRole --zip-file fileb://fn.zip --publish \
  --query Version --output text
aws lambda create-alias --function-name myapp-report --name live --function-version 1
Grant Lambda publish permissions to the dev pipeline role
aws iam put-role-policy --role-name ado-myapp-dev-deploy --policy-name lambda-release --policy-document "{
 \"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",
 \"Action\":[\"lambda:UpdateFunctionCode\",\"lambda:PublishVersion\",\"lambda:GetFunction\",\"lambda:GetFunctionConfiguration\",\"lambda:GetAlias\",\"lambda:UpdateAlias\"],
 \"Resource\":[\"arn:aws:lambda:$AWS_REGION:$ACCOUNT_ID:function:myapp-report\",\"arn:aws:lambda:$AWS_REGION:$ACCOUNT_ID:function:myapp-report:*\"]}]}"
Pipeline step: publish a new version and do a 10% canary
- task: AWSShellScript@1
  displayName: Lambda canary 10%
  inputs:
    awsCredentials: aws-myapp-dev
    regionName: ca-central-1
    scriptType: inline
    inlineScript: |
      set -euo pipefail
      cd lambda && zip -q ../fn.zip app.py && cd ..
      OLD=$(aws lambda get-alias --function-name myapp-report --name live --query FunctionVersion --output text)
      NEW=$(aws lambda update-function-code --function-name myapp-report --zip-file fileb://fn.zip --publish --query Version --output text)
      aws lambda wait published-version-active --function-name myapp-report --qualifier "$NEW"
      aws lambda update-alias --function-name myapp-report --name live --function-version "$OLD" \
        --routing-config "{\"AdditionalVersionWeights\":{\"$NEW\":0.1}}"
      echo "##vso[task.setvariable variable=LAMBDA_NEW;isOutput=true]$NEW"
      echo "live: $OLD 90% / $NEW 10%"
Verify the traffic split, then either fully shift or roll back
for i in $(seq 1 20); do aws lambda invoke --function-name myapp-report:live /dev/stdout --query 'ExecutedVersion' --output text 2>/dev/null; done | sort | uniq -c
aws lambda get-alias --function-name myapp-report --name live
     18 {"version": "1"}1
      2 {"version": "2"}2
{ "Name": "live", "FunctionVersion": "1", "RoutingConfig": { "AdditionalVersionWeights": { "2": 0.1 } } ... }

Full shift: aws lambda update-alias --function-name myapp-report --name live --function-version 2 --routing-config '{"AdditionalVersionWeights":{}}'; rollback: set --function-version back to 1 and clear the weights.

Lab 5B (optional): Helm deployment to EKS

Only do this if you still keep the EKS cluster from Lesson 7 of the K8s course (control plane US$0.10/hour + node costs). Follow the “Commands” tab to run the access entry authorization, then add the Helm step to the pipeline. Acceptance: kubectl -n myapp get deploy myapp -o jsonpath='{..image}' shows the digest reference. When done, delete the access entry: aws eks delete-access-entry --cluster-name lab --principal-arn $ROLE_ARN.

Case 1: pipeline returns 401 after migrating to access entries

Problem: The platform team changed the cluster authentication mode from CONFIG_MAP to API, and deleted the aws-auth ConfigMap, so all Azure Pipelines deployments reported Unauthorized. Root cause: The pipeline role only had a mapping in aws-auth, with no matching access entry. Fix: First, in API_AND_CONFIG_MAP mode, create and verify an access entry for each pipeline role, then switch to API mode.

Case 2: pipeline has cluster admin permissions

Problem: To save effort, the pipeline role was associated with AmazonEKSClusterAdminPolicy (cluster scope). A tampered Helm chart created a ClusterRoleBinding. Fix: One pipeline role per application, associated only with namespace-scoped AmazonEKSEditPolicy; CRDs and cluster-level resources are deployed separately by a platform pipeline; charts come from a protected branch or a signed OCI artifact.

Case 3: automatic rollback of a Lambda canary

Problem: The new version of the reporting function has a higher error rate under 10% of traffic. Fix: The pipeline waits 10 minutes in the 10% stage, querying CloudWatch metrics Errors (dimensions Resource=myapp-report:live,ExecutedVersion=new version), and if it exceeds the threshold, point the alias back to the old version and fail the stage; a more complete approach is to use CodeDeploy's Lambda deployment configuration (such as a 10% canary for 5 minutes) + alarm-based rollback.

Common errors and fixes

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

Cause: EKS does not recognize this identity: no access entry; the access entry's principalArn is set to the session ARN or another role; or the kubeconfig is not using the pipeline credentials (for example, a stale kubeconfig / AWS_PROFILE left on the agent).

aws sts get-caller-identity
aws eks list-access-entries --cluster-name lab
aws eks describe-access-entry --cluster-name lab --principal-arn arn:aws:iam::111122223333:role/ado-myapp-dev-deploy

Fix: Create an access entry for the IAM role ARN; in the pipeline, explicitly aws eks update-kubeconfig, and do not rely on old files on the agent.

Error from server (Forbidden): deployments.apps is forbidden: User "arn:aws:sts::…:assumed-role/ado-myapp-dev-deploy/aws-vsts-tools" cannot create resource "deployments" in API group "apps" in the namespace "myapp"

Cause: Authentication succeeded but authorization is insufficient: the access policy's scope does not include the namespace, or only the View policy was associated.

aws eks list-associated-access-policies --cluster-name lab --principal-arn arn:aws:iam::111122223333:role/ado-myapp-dev-deploy

Fix: Associate AmazonEKSEditPolicy to myapp namespace, or bind the access entry's Kubernetes group through RBAC.

An error occurred (AccessDeniedException) when calling the DescribeCluster operation

Cause:update-kubeconfig Requires eks:DescribeCluster.

Fix: Add that permission to the pipeline role (resource is the cluster ARN).

Error: UPGRADE FAILED: context deadline exceeded (the release is then rolled back)

Cause:--wait Timeout: image pull failure (node role lacks ECR read permission, cross-account repository policy), probe failures, insufficient resources.

kubectl -n myapp get pods; kubectl -n myapp describe pod -l app.kubernetes.io/name=myapp | tail -20
helm -n myapp history myapp

Fix: Follow the K8s course troubleshooting tree for Pod issues; for cross-account ECR see Module 6.

InvalidParameterValueException: … alias with routing configuration cannot point to $LATEST / can't specify more than one additional version

Cause: A weighted alias must point to a published version, and can have only one additional version.

Fix: First, --publish to get the version number; when doing a full shift, clear AdditionalVersionWeights.

Command-line exercises
1. Grant the role ado-myapp-prod-deploy edit permission on the myapp namespace in the prod cluster.
R=arn:aws:iam::444455556666:role/ado-myapp-prod-deploy
aws eks create-access-entry --cluster-name prod --principal-arn $R
aws eks associate-access-policy --cluster-name prod --principal-arn $R \
  --policy-arn arn:aws:eks::aws:cluster-access-policy/AmazonEKSEditPolicy --access-scope type=namespace,namespaces=myapp
2. Immediately roll back the live alias to version 6.
aws lambda update-alias --function-name myapp-report --name live --function-version 6 --routing-config '{"AdditionalVersionWeights":{}}'
Scenario analysis
The same pipeline role can deploy to the dev cluster but gets 401 on the prod cluster. The IAM policies are identical. What could be the cause?

Access entries are per cluster configured separately: the prod cluster has no access entry for this role, or prod is in another account and the pipeline is using the dev account's role (across accounts, the access entry must reference the assumed role ARN in the prod account). It could also be that the prod cluster is still in CONFIG_MAP mode with no mapping in aws-auth.

Verified teaching videos

▶
AWS EKS - Create Kubernetes cluster on Amazon EKS | the easy way — TechWorld with Nana
English · EKS cluster and kubectl access (recorded earlier; access entries follow this lesson)
▶
EKS Pod Identity vs IRSA | Securely Connect Kubernetes Pods to AWS Services — Containers from the Couch
English · Distinguishing “pipeline accesses cluster” (this module) from “Pod accesses AWS” (Lesson 7 of the K8s course)
▶
Serverless for container fans via Amazon ECS and AWS Lambda — Bret Fisher
English · How Lambda relates to containers

No oEmbed-verified video on Lambda alias weighted routing was found; please refer to the documentation and storyboard below.

Official documentation

Video storyboard script (about 75 seconds)

Shot 1 · 0–25s
Visual: kubectl hands over a k8s-aws-v1 token; the EKS gatekeeper checks the list (access entries); if you are not on the list, a 401 lights up.
Narration: EKS first confirms who you are; if this IAM role is not on the list, you are unauthenticated.
Shot 2 · 25–45s
Visual: after you enter, the access policy only opens the myapp room; trying to enter kube-system lights up a 403.
Narration: after authentication you still need authorization; an access policy can be limited to a single namespace.
Shot 3 · 45–75s
Visual: the alias live is like a mixing-board fader; it pushes 10% from version 7 to version 8, and when something goes wrong it is pulled back to 0.
Narration: Lambda publishes immutable versions, uses alias weights for canaries, and rolling back only requires pointing the alias back to the old version.
or score ≥ 70% on the “Quiz”

Module 6 · Multi-account and environment promotion

38:00 – 45:00 · Per environment: a separate AWS account (or at least a separate role) + a separate service connection + separate approvals; the same digest is promoted from dev to prod
7 minEnvironments approvals and checksService connection checks★★★★★
Learning objectives
  • Design the layout of “tools account (ECR) + dev account + prod account”, and know that the OIDC provider must be with the role in the same account, so every account needs its own provider.
  • Achieve one service connection, one role, and one subject per environment: the dev connection technically cannot assume the prod role.
  • Put approvals on Environment (myapp-aws-prod), and on the prod service connection, add branch control and other checks to prevent anyone from bypassing the Environment and using the connection directly.
  • Solve cross-account ECR image pulls (repository policy + execution role), and master the YAML detail that stageDependencies can only reference directly dependent stages.
Prerequisites: Environments and deployment jobs from Lesson 2; Lesson 6 goes deeper into approvals and checks. Importance:★★★★★

What: recommended account and identity layout

AccountResourcesAzure DevOps service connectionRole and trust subject
tools (777788889999)ECR repository myapp (IMMUTABLE)aws-myapp-buildado-myapp-build ← sc://myorg/myapp-lab/aws-myapp-build; push only
dev (111122223333)ECS cluster/service myapp-devaws-myapp-devado-myapp-dev-deploy ← …/aws-myapp-dev
prod (444455556666)ECS cluster/service myapp-prodaws-myapp-prod (restricted + checks)ado-myapp-prod-deploy ← …/aws-myapp-prod

To save time, this lab simulates it in one account: same account, two services, two roles, two service connections. The isolation principle is identical; only the account-level “blast radius” boundary is missing.

Why: why so many layers

  • Account Is AWS's strongest isolation boundary: quotas, IAM, billing, and SCPs are all partitioned by account. Any misconfiguration in dev cannot touch prod.
  • One subject per environment: even if someone changes the dev connection's role ARN to the prod role, STS will reject it because the subject does not match.
  • Approvals are on the Environment: “who, when, and which digest was approved for prod” stays in the deployment history.
  • Checks are also on the service connection: the Environment's approvals only gate deployment jobs that use that Environment; if someone writes a plain job that directly references aws-myapp-prod, only approvals/checks on the service connection can stop it.

How: control points on the Azure DevOps side

ControlWhere it goesPurpose
ApprovalsEnvironment myapp-aws-prod (can also be added to the prod service connection)Specify approvers/groups; can set timeouts and forbid self-approval by the initiator
Branch controlprod service connection / EnvironmentAllow only refs/heads/main (and protected branches) to use it
Business hoursEnvironmentDeploy only during business hours
Exclusive lockEnvironmentOnly one run can deploy to prod at a time
Required templateprod service connectionOnly pipelines that extend the approved template can use it (Lesson 5)
Pipeline permissionsService connection → Security → Pipeline permissionsDo not tick “Grant access permission to all pipelines”; authorize pipelines one by one

How: promoting the same digest

The prod stage does not rebuild, but reads the Build stage's IMAGE_URI (repository@sha256:…). Watch the YAML detail: stageDependencies can only reference stages directly listed in this stage's dependsOn. If DeployProd only writes dependsOn: DeployDev, it cannot read Build's output, so write dependsOn: [Build, DeployDev].

Cross-account ECR pulls

  1. ECR in the tools account repository policy allow the prod account (or the prod execution role ARN) to perform ecr:BatchGetImage,ecr:GetDownloadUrlForLayer,ecr:BatchCheckLayerAvailability.
  2. The prod account's task execution role itself also needs these permissions, plus ecr:GetAuthorizationToken (the managed policy AmazonECSTaskExecutionRolePolicy already includes it; the resource is *).
  3. The task definition's image uses the tools account's repository URI + digest. You can also use ECR cross-account replication to copy the image to the prod account; before deploying, use describe-images to verify that the digests match.

When: minimum viable approach

  • Starting point: one account + one role/connection per environment + prod Environment approval (this lesson's lab).
  • Before going live: split out the prod account; add branch control and approvals to the prod connection; set up an organization-wide CloudTrail trail.
  • At scale: AWS Organizations + SCPs; roles and trust policies generated centrally by IaC; extends templates force all pipelines through the same promotion process.
Common misconceptions① “One role + different environment variables = multiple environments”——the same role can operate every environment, so approvals are meaningless. ② “Environment approvals are enough”——a plain job that references the service connection directly can bypass the Environment, so checks must also be added on the service connection. ③ “Each environment builds its own image”——this produces different digests, so prod runs something dev never tested. ④ “It's enough to create the OIDC provider in the tools account”——the OIDC provider in the trust policy must be in the same account as the role.

Multi-account promotion overview

Azure Pipelines: azure-pipelines-aws.yml Build (aws-myapp-build) DeployDev (env: myapp-aws-dev) Approvals + branch checks DeployProd (env: myapp-aws-prod) tools accountOIDC provider + ado-myapp-buildECR myapp (IMMUTABLE)Repository policy: allow dev/prod to pullmyapp@sha256:9f2c… dev accountOIDC provider + ado-myapp-dev-deploysub = …/aws-myapp-devECS myapp-dev prod accountOIDC provider + ado-myapp-prod-deploysub = …/aws-myapp-prodECS myapp-prod (same digest)
Figure 6-1 Each account has its own OIDC provider and roles; the image is built once and pulled across accounts by digest

Two gates: Environment and service connection

deployment job + environment plain job directly references the connection Environment checks (approvals…) Service connection checks (branch control, approvals, required template) The second path bypasses the Environment; only checks on the service connection can stop it
Figure 6-2 The prod service connection must carry its own checks

Animation: promotion flow and “wrong identity” simulation

Choose a scenario and play it. Watch which service connection each stage uses, which role it assumes, and which gate stops it.

Core commands and YAML

Command / syntaxPurpose
environment: myapp-aws-prodA deployment job binds to an Environment, triggering its approvals and checks
dependsOn: [Build, DeployDev]Lets DeployProd read the output variable from Build
condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))Only the main branch enters the prod stage
aws ecr set-repository-policyAllow other accounts to pull
az devops service-endpoint listList service connections (for auditing; requires the azure-devops extension)
az pipelines run --branchTrigger a run manually

DeployProd stage

- stage: DeployProd
  dependsOn: [Build, DeployDev]            # both must be listed in order to read Build's outputs
  condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
  jobs:
  - deployment: Ecs
    environment: myapp-aws-prod            # approvals are configured on this Environment
    variables:
      imageUri: $[ stageDependencies.Build.Push.outputs['img.IMAGE_URI'] ]
      imageTag: $[ stageDependencies.Build.Push.outputs['img.IMAGE_TAG'] ]
      aws.rolecredential.maxduration: "1800"
    strategy:
      runOnce:
        deploy:
          steps:
          - checkout: self
          - task: AWSShellScript@1
            displayName: Deploy myapp-prod
            inputs:
              awsCredentials: aws-myapp-prod     # separate connection → separate role → separate subject
              regionName: $(awsRegion)
              scriptType: filePath
              filePath: deploy/ecs-deploy.sh
              disableAutoCwd: true
              workingDirectory: $(Build.SourcesDirectory)
            env:
              CLUSTER: myapp-lab
              SERVICE: myapp-prod
              FAMILY: myapp-prod
              IMAGE_URI: $(imageUri)
              APP_VERSION: $(imageTag)

Cross-account ECR repository policy (run in the tools account)

aws ecr set-repository-policy --repository-name myapp --policy-text '{
  "Version": "2012-10-17",
  "Statement": [{
    "Sid": "AllowPullFromDevAndProd",
    "Effect": "Allow",
    "Principal": { "AWS": [ "arn:aws:iam::111122223333:root", "arn:aws:iam::444455556666:root" ] },
    "Action": [ "ecr:BatchGetImage", "ecr:GetDownloadUrlForLayer", "ecr:BatchCheckLayerAvailability" ]
  }]
}'

Using the account root ARN as the principal means “delegate to that account's IAM”; the other account must still grant the permissions through identity policies (the execution role's managed policy already includes them). A stricter approach is to write the specific execution role ARN, or use aws:PrincipalOrgID a condition to restrict it to the organization.

Lab 6: prod role, prod connection and approvals (about 7 min)

Create the prod role (trusts only aws-myapp-prod, can only deploy myapp-prod, cannot push images)
source ~/ado-aws.env
P=vstoken.dev.azure.com/$ADO_ORG_ID
sed "s#/aws-myapp-dev\"#/aws-myapp-prod\"#" /tmp/trust-dev.json > /tmp/trust-prod.json
grep sub /tmp/trust-prod.json
aws iam create-role --role-name ado-myapp-prod-deploy --assume-role-policy-document file:///tmp/trust-prod.json \
  --max-session-duration 3600 --tags Key=project,Value=ado-lab Key=env,Value=prod --query Role.Arn --output text
cat > /tmp/perm-prod.json <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    { "Sid": "EcrRead", "Effect": "Allow", "Action": ["ecr:DescribeImages"],
      "Resource": "arn:aws:ecr:${AWS_REGION}:${ACCOUNT_ID}:repository/${REPO}" },
    { "Sid": "EcsTaskDef", "Effect": "Allow",
      "Action": ["ecs:RegisterTaskDefinition","ecs:DescribeTaskDefinition","ecs:ListTasks","ecs:DescribeTasks"], "Resource": "*" },
    { "Sid": "EcsServiceProd", "Effect": "Allow", "Action": ["ecs:UpdateService","ecs:DescribeServices"],
      "Resource": "arn:aws:ecs:${AWS_REGION}:${ACCOUNT_ID}:service/${CLUSTER}/myapp-prod" },
    { "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 ado-myapp-prod-deploy --policy-name deploy-prod --policy-document file:///tmp/perm-prod.json
      "vstoken.dev.azure.com/5f3c…:sub": "sc://myorg/myapp-lab/aws-myapp-prod"
arn:aws:iam::111122223333:role/ado-myapp-prod-deploy
Create the prod service connection and add checks: create a new AWS connection aws-myapp-prod (role ado-myapp-prod-deploy, tick Use OIDC, no secrets). In the connection's “⋮ → Approvals and checks”, add Branch control (allowed branch refs/heads/main, tick “Verify branch protection”), and in “Security → Pipeline permissions” add only this pipeline.
Create the prod Environment and add approvals: Environments → New → myapp-aws-prod → “⋮ → Approvals and checks” → Approvals; the approver is yourself (in a real team, choose someone else and tick “Don't allow the requester to approve”), timeout 1 hour; then add Exclusive lock.
Append the DeployProd stage and push (YAML from the “Commands” tab). When the run reaches DeployProd, its status is “Waiting”; the approvals panel shows the run awaiting approval; deployment starts after approval.
Verify dev and prod run the same digest
for S in myapp-dev myapp-prod; do
  T=$(aws ecs list-tasks --cluster $CLUSTER --service-name $S --query 'taskArns[0]' --output text)
  echo "$S $(aws ecs describe-tasks --cluster $CLUSTER --tasks $T --query 'tasks[0].containers[0].imageDigest' --output text)"
done
myapp-dev sha256:9f2c…41ab
myapp-prod sha256:9f2c…41ab
Negative test: the dev role cannot touch prod: temporarily change DeployProd's awsCredentials to aws-myapp-dev and run it once (another branch is fine; do not merge). Expected: AccessDeniedException … not authorized to perform: ecs:UpdateService on resource: …service/myapp-lab/myapp-prod. After reverting, delete the test branch.
Acceptance dev deploys automatically, prod waits for approval before deploying; the digest matches in both environments; the dev connection cannot update the prod service; the Environment's deployment history shows the approver and run number.

Case 1: the “emergency fix” pipeline that bypassed the Environment

Problem: An engineer created a new pipeline that used a plain job to reference aws-myapp-prod to do a “hotfix”, bypassing the prod Environment's approvals. Fix: On the prod service connection, turn off “Grant access permission to all pipelines”, add approvals and branch control, and set a Required template so only pipelines that extend the company's deployment template can use it. Result: Any new pipeline that uses the prod connection for the first time needs admin authorization and approval.

Case 2: stageDependencies returned no value, and prod deployed an empty image

Problem: DeployProd only wrote dependsOn: DeployDev, the imageUri variable was empty, and the rendered task definition failed to register. Fix: Change it to dependsOn: [Build, DeployDev]; the deployment script validates at the start that IMAGE_URI must contain @sha256: (this lesson's script already includes this).

Case 3: cross-account pull denied

Problem: prod task stop reason: CannotPullContainerError: … 403 Forbidden. Root cause: The tools account ECR repository policy only allowed the dev account. Fix: Add the prod account (or aws:PrincipalOrgID condition) to the repository policy; update it automatically in IaC for each new environment.

Common errors and fixes

The pipeline is not valid. … / variable imageUri is empty ($[ stageDependencies… ] evaluates to an empty string)

Cause: The referenced stage is not in dependsOn , or stage/job/step names are spelled inconsistently; deployment job outputs are referenced differently from regular jobs (include the lifecycle hook and resource name, such as outputs['Ecs.Deploy.ecs.DEPLOYED_TD'], see the official docs).

Fix:dependsOn: [Build, DeployDev]; in the job, first echo "[$(imageUri)]" to confirm.

The run stays stuck on “Waiting for approval” / “Check: Branch control failed”

Cause: No one handled the approval (it fails after timeout); or the run came from a non-main branch, or the branch was unprotected while “Verify branch protection” was ticked.

Fix: On the run page, check the specific results in the “Checks” panel; run from main; configure a branch policy for main.

Pipeline does not have permissions to use the referenced service connection(s) aws-myapp-prod

Cause: The prod connection is not authorized for this pipeline (this is the intended protection).

Fix: The connection administrator clicks “Permit” on the run page, or adds the pipeline in the connection's Security settings.

CannotPullContainerError: … 403 Forbidden / denied: User … is not authorized to perform: ecr:BatchGetImage

Cause: Cross-account pull: the repository policy does not authorize the target account, or the execution role lacks permissions, or it lacks kms:Decrypt on a KMS-encrypted repository.

aws ecr get-repository-policy --repository-name myapp --query policyText --output text | jq .

Fix: Add the target account/role to the repository policy; check the execution role.

Command-line exercises
1. Write the job variable expression DeployProd uses to read the IMAGE_URI output of the img step in the Push job of the Build stage.
variables:
  imageUri: $[ stageDependencies.Build.Push.outputs['img.IMAGE_URI'] ]
2. Use the CLI to compare the current task definition revisions of the dev and prod services.
aws ecs describe-services --cluster myapp-lab --services myapp-dev myapp-prod --query 'services[].[serviceName,taskDefinition]' --output table
Scenario analysis
The company requires “prod deployments must be approved by a non-submitter, may only run on weekdays from 9–17, and only one deployment may run at a time.” How do you configure this in Azure DevOps? Is configuring only the Environment enough?

On the myapp-aws-prod Environment, configure: Approvals (approver group; tick “Don't allow requesters to approve”), Business hours (Monday–Friday 9–17), and Exclusive lock. Also on the aws-myapp-prod service connection, configure Branch control and (optionally) the same approvals or a Required template, since a plain job that references the connection directly can bypass the Environment. On the AWS side, the prod role's subject only trusts aws-myapp-prod.

Verified instructional videos

▶
Azure DevOps Environments EXPLAINED — CoderDave
English · Basics of Environments, approvals and checks (duration and date not verified)
▶
Azure DevOps Environments: Checks and Gates DEEP DIVE — CoderDave
English · Checks (branch control, business hours, exclusive locks, etc.)
▶
Don't deploy now! How to DELAY a deployment — CoderDave
English · Delayed deployments and time windows

No verified video on “AWS multi-account + Azure DevOps promotion” was found.

Official documentation

Video storyboard script (about 60 seconds)

Shot 1 · 0–20s
Visual: three buildings: tools, dev, prod; each building has its own doorman (OIDC provider).
Narration: every account needs its own OIDC provider and role; the doorman only accepts passes issued to it.
Shot 2 · 20–40s
Visual: the dev pass (sub ending in aws-myapp-dev) is rejected by the prod doorman.
Narration: the subject is pinned to the service connection, so a dev connection can never get into prod.
Shot 3 · 40–60s
Visual: the same digest package travels from dev to prod, stamped by an approver along the way.
Narration: the image is built only once; after approval, the same digest is promoted to production.
or score ≥ 70% on the quiz

Module 7 · Cloud deployment troubleshooting in practice

45:00 – 54:00 · First work out which layer the error is in: Azure DevOps → STS → IAM authorization → ECR → ECS/EKS runtime; each layer has its own typical error signature and diagnostic commands
9 minCloudTrail · simulate-principal-policyInteractive troubleshooting tree★★★★★
Learning objectives
  • Read the structure of AWS denial messages: User: <principal> is not authorized to perform: <action> on resource: <resource> because …, and use what follows “because” to tell apart “no allow” from “explicit deny (SCP / permissions boundary / session policy / resource policy)”.
  • Use CloudTrail (lookup-events) and the IAM policy simulator (simulate-principal-policy) to locate permission problems without changing code.
  • Work through five common failure types using the troubleshooting tree: AccessDenied, AssumeRole failures, ECR login failures, stuck ECS deployments, EKS Unauthorized.
Prerequisites: Modules 2–6. Importance:★★★★★ (in cloud deployment, the most time-consuming part is often troubleshooting, not writing the pipeline)

What: the five-layer model

LayerTypical error signatureFirst diagnostic command
① Azure DevOpsSystem.AccessToken is undefined,not have permissions to use the referenced service connection, checks not passingRun page “Checks” panel; service connection Security
② STS (get credentials)AssumeRoleWithWebIdentity / AssumeRole operation's AccessDenied,InvalidIdentityToken,ValidationErrorissuer/sub on the OIDC line in the task log; aws iam get-role
③ IAM authorization (API call)AccessDeniedException … is not authorized to perform: ecs:UpdateService …aws sts get-caller-identity; simulate-principal-policy; CloudTrail
④ ECRno basic auth credentials,authorization token has expired,name unknown,tag invalid … immutableaws ecr describe-repositories; sign in again
⑤ Runtime (ECS/EKS)CannotPullContainerError,ResourceInitializationError, health check failures, circuit breaker rollback; Unauthorized/Forbiddendescribe-services events, stop reasons of tasks stoppedReason; kubectl auth can-i

Why: why work layer by layer first

A “deployment failed” can show the same symptom at different layers: a layer ② problem means changing the IAM trust policy, layer ③ means changing permission policies, and layer ⑤ may be networking or the application. Changing the wrong layer wastes time and often leads to permissions being widened “just to make it run” up to *.

How: reading AccessDenied

An error occurred (AccessDeniedException) when calling the UpdateService operation:
User: arn:aws:sts::111122223333:assumed-role/ado-myapp-dev-deploy/aws-vsts-tools
is not authorized to perform: ecs:UpdateService
on resource: arn:aws:ecs:ca-central-1:111122223333:service/myapp-lab/myapp-prod
because no identity-based policy allows the ecs:UpdateService action
  • Principal: assumed-role/role name/session name → confirm it is the role you expect (check whether the wrong service connection was selected).
  • Action + resource: the exact API and ARN. In the example above, the dev role tries to update the prod service; this is a correct denial, so fix the pipeline instead of granting permissions.
  • because …: no identity-based policy allows (missing allow) and with an explicit deny in a service control policy / permissions boundary / resource-based policy (explicit deny) call for completely different fixes.
  • Some services such as EC2 return Encoded authorization failure message, use aws sts decode-authorization-message --encoded-message … to decode (requires sts:DecodeAuthorizationMessage permission).

How: use CloudTrail to find the calls

Fill in each AWS service connection with a meaningful Role Session Name (e.g. ado-myapp-dev), in CloudTrail userIdentity.arn it appears, making it easy to tell which pipeline made the call. lookup-events You can query management events (last 90 days) and filter by event name or username; for AssumeRoleWithWebIdentity failed calls, the event records the error code and request parameters (token contents are not fully logged).

When: four patterns of stuck ECS deployments

PatternService event / stop reason (example)Common root cause
Task cannot pull imageCannotPullContainerError: …digest/tag does not exist; cross-account repository policy; execution role lacks permissions
Task cannot reach ECRResourceInitializationError: unable to pull secrets or registry auth: … There is a connection issue between the task and Amazon ECR. Check your task network configuration.Public subnet, yet assignPublicIp=DISABLED; private subnet has no NAT or VPC endpoints for ECR/S3/Logs; security group blocks outbound
Container exits right after startEssential container in task exited (exitCode 1/137)wrong command or environment variable, port conflict, OOM
Health check failuresTask failed container health checks / ELB health check failureswrong path or port, startup slower than startPeriod, dependencies not ready
Common misconceptions① “If you get AccessDenied, just add Action: * a wildcard and try”—this hides the real problem (wrong connection, explicit deny) and creates a security risk. ② “Permissions should take effect immediately after a change”—IAM is eventually consistent, usually within seconds but occasionally longer; temporary credentials STS has already issued do not gain anything beyond the new permissions, but new tasks fetch credentials again. ③ “A stuck ECS deployment is an AWS problem”—most of the time it is one of three things: image, network or health check, and the answer is in stoppedReason the layered diagram below.

Troubleshooting layer diagram

① Azure DevOps: service connection authorization, OAuth token, Environment/connection checks ② STS: OIDC provider, audience, subject, session duration → temporary credentials ③ IAM authorization: identity policies, PassRole, SCP/permissions boundaries, resource policies ④ ECR: login token (12h), repository exists, immutable tags, cross-account ⑤ Runtime: ECS tasks (image pull, networking, health checks) / EKS (401/403)The lower the failure sits, the more you need AWS-side events rather than pipeline logs
Figure 7-1: eliminate layers top to bottom; if an upper layer fails, the layer below logs nothing

Use CloudTrail to locate a failed call

Task log: AccessDeniedNote the action and time lookup-eventsEventName=UpdateService errorCode / userIdentitywhich role, which session simulate-principal-policy to verify the fix
Figure 7-2: gather evidence first, then change the policy, and finally verify with the simulator

Interactive: raw error classifier

Paste an error from the pipeline log below (or click an example). The classifier works out which layer it belongs to and gives the most likely root cause and the next diagnostic command. The rules are based on the real error signatures compiled in this lesson.

Troubleshooting command box

CommandQuestion it answers
aws sts get-caller-identityWho am I right now (which role, which session, which account)?
aws iam get-role --role-name R --query Role.AssumeRolePolicyDocumentWho is allowed to assume the role in the trust policy?
aws iam list-role-policies / get-role-policy / list-attached-role-policiesWhat permissions does the role have?
aws iam simulate-principal-policy --policy-source-arn ROLE --action-names A --resource-arns RIs this action on this resource allowed for this role? (evaluates identity policies only, not the full effect of SCPs)
aws cloudtrail lookup-events --lookup-attributes AttributeKey=EventName,AttributeValue=XWhat exactly happened in this call (errorCode, errorMessage)?
aws sts decode-authorization-message --encoded-message MWhich policy does an encoded denial message refer to?
aws ecs describe-services … --query 'services[0].events[:10]'What did the service scheduler report?
aws ecs describe-tasks … --query 'tasks[0].[stoppedReason,containers[0].reason]'Why did the task stop?
aws logs tail /ecs/myapp --since 15mWhat did the container itself output?
kubectl auth can-i --list -n myappWhat can the current identity do in EKS?
# 1) Simulate: can the dev role update the prod service?
aws iam simulate-principal-policy \
  --policy-source-arn arn:aws:iam::111122223333:role/ado-myapp-dev-deploy \
  --action-names ecs:UpdateService iam:PassRole \
  --resource-arns arn:aws:ecs:ca-central-1:111122223333:service/myapp-lab/myapp-prod \
  --query 'EvaluationResults[].[EvalActionName,EvalDecision]' --output table

# 2) CloudTrail: AccessDenied in the last hour (filter by event name, then filter errorCode locally)
aws cloudtrail lookup-events --start-time $(date -u -d '-1 hour' +%FT%TZ) \
  --lookup-attributes AttributeKey=EventName,AttributeValue=UpdateService \
  --query 'Events[].CloudTrailEvent' --output text | jq -r 'select(.errorCode!=null) | [.eventTime,.userIdentity.arn,.errorCode,.errorMessage] | @tsv'
-----------------------------------------
|        SimulatePrincipalPolicy        |
+--------------------+------------------+
|  ecs:UpdateService |  implicitDeny    |
|  iam:PassRole      |  implicitDeny    |
+--------------------+------------------+
2026-11-15T15:42:10Z	arn:aws:sts::111122223333:assumed-role/ado-myapp-dev-deploy/aws-vsts-tools	AccessDenied	User: … is not authorized to perform: ecs:UpdateService on resource: …/myapp-prod …

Note: CloudTrail events are usually queryable within a few minutes of the call; lookup-events there is a rate limit (2 requests per account per region per second); for bulk analysis, use CloudTrail Lake or write trails to S3 and query them with Athena. IAM is a global service and its events are recorded in us-east-1; calls to regional STS endpoints are recorded in their own region.

Lab 7: inject 3 faults and fix them (about 8 minutes)

For each fault: inject → run the pipeline (or “Re-run” the DeployDev stage) → read the error → locate it with the troubleshooting tree → fix → run again.

Fault A: wrong subject in the trust policy (STS layer)
source ~/ado-aws.env
sed 's#/aws-myapp-dev"#/aws-myapp-DEV"#' /tmp/trust-dev.json > /tmp/trust-bad.json
aws iam update-assume-role-policy --role-name ado-myapp-dev-deploy --policy-document file:///tmp/trust-bad.json

Expected error: Not authorized to perform sts:AssumeRoleWithWebIdentity, the sub on the OIDC line in the log is …/aws-myapp-dev. Fix:aws iam update-assume-role-policy --role-name ado-myapp-dev-deploy --policy-document file:///tmp/trust-dev.json (StringEquals is case-sensitive).

Fault B: missing iam:PassRole (IAM authorization layer)
jq 'del(.Statement[] | select(.Sid=="PassExecRole"))' /tmp/perm-dev.json > /tmp/perm-bad.json
aws iam put-role-policy --role-name ado-myapp-dev-deploy --policy-name deploy-dev --policy-document file:///tmp/perm-bad.json

Expected error: … is not authorized to perform: iam:PassRole on resource: …role/myappTaskExecutionRole (appears in RegisterTaskDefinition or UpdateService). Use simulate-principal-policy to confirm implicitDeny. Fix: Re-create put-role-policy and write back /tmp/perm-dev.json.

Fault C: tasks have no public IP (runtime layer: cannot reach ECR)
aws ecs update-service --cluster $CLUSTER --service myapp-dev \
  --network-configuration "awsvpcConfiguration={subnets=[$SUBNETS],securityGroups=[$SG],assignPublicIp=DISABLED}" \
  --force-new-deployment --query 'service.deployments[0].rolloutState'
sleep 120
aws ecs list-tasks --cluster $CLUSTER --service-name myapp-dev --desired-status STOPPED --query 'taskArns[0]' --output text \
 | xargs -I{} aws ecs describe-tasks --cluster $CLUSTER --tasks {} --query 'tasks[0].stoppedReason' --output text
"IN_PROGRESS"
ResourceInitializationError: unable to pull secrets or registry auth: … There is a connection issue between the task and Amazon ECR. Check your task network configuration. …

The subnets in the default VPC are public subnets (routing to an internet gateway); tasks without a public IP cannot reach ECR. After 3 cumulative failures, the circuit breaker declares the deployment failed and rolls back to the previous service revision. ECS records each deployment's configuration as a “service revision”, and network configuration is part of it, so after rollback the network configuration may be restored as well. Use aws ecs describe-services --query 'services[0].networkConfiguration' to check the actual result rather than assume. Fix: Change back assignPublicIp=ENABLED and --force-new-deployment; in production, use private subnets plus NAT or VPC endpoints for ECR/S3/CloudWatch Logs.

Review: using the troubleshooting tree on the “Troubleshooting” page, write down which layer each fault is in and which command you used to find it.
Caveat For Fault C, the raw service events after the circuit breaker rolls back, and whether rollback restores the network configuration, should be taken from your describe-services output; whatever the result, always confirm the myapp-dev service's assignPublicIp status is ENABLED and runningCount=1.

Case 1: explicit deny from an SCP

Problem: Deployment to the newly opened prod account fails with … with an explicit deny in a service control policy, and repeatedly adding permissions to the role does not help. Root cause: The organization's SCP denied ca-central-1 calls in regions other than the allowed one, while the pipeline's regionName was mistakenly set to us-east-1. Lesson: When you see “explicit deny”, stop changing the identity policy and go find the SCP/permissions boundary administrator.

Case 2: credentials expire during a long task

Problem: In the deployment script, wait services-stable the verification step after fails with ExpiredToken. Root cause: The Toolkit default credential lifetime is 900 seconds; build + deploy + wait within a single task exceeds 15 minutes. Fix: Split the task or set aws.rolecredential.maxduration.

Case 3: ECS deployment stuck in a private subnet

Problem: After moving the service to private subnets, all tasks ResourceInitializationError get stuck. Root cause: No NAT, and no VPC endpoints. Fix: Create interface endpoints com.amazonaws.ca-central-1.ecr.api,ecr.dkr,logs (plus Secrets Manager if used) and an S3 gateway endpoint (ECR image layers are stored in S3).

Interactive troubleshooting tree

Start from the symptom and answer the questions step by step until you reach the diagnosis and fix command.

Quick reference for common errors

An error occurred (ExpiredToken) when calling the … operation: The security token included in the request is expired

Cause: Temporary credentials expired (default 900 seconds). Fix: Split the task, set aws.rolecredential.maxduration (≤ role MaxSessionDuration).

The security token included in the request is invalid

Cause: Credentials are incomplete or come from the wrong source (for example, after an OIDC failure the task falls back to empty keys; leftover AWS_* environment variables on the agent). Fix: Scroll up the log to find OIDC-related lines; check agent environment variables and ~/.aws.

… with an explicit deny in a service control policy

Cause: Explicit deny from the organization SCP. Fix: Confirm whether the region or action is forbidden by organization policy; contact the SCP administrator and stop changing the identity policy.

Command-line exercises
1. Check whether the prod role is allowed to perform ecs:UpdateService on the myapp-prod service.
aws iam simulate-principal-policy --policy-source-arn arn:aws:iam::111122223333:role/ado-myapp-prod-deploy \
  --action-names ecs:UpdateService --resource-arns arn:aws:ecs:ca-central-1:111122223333:service/myapp-lab/myapp-prod \
  --query 'EvaluationResults[0].EvalDecision'
2. Check the stop reasons of the 3 most recently stopped tasks in myapp-dev.
for t in $(aws ecs list-tasks --cluster myapp-lab --service-name myapp-dev --desired-status STOPPED --query 'taskArns[:3]' --output text); do
  aws ecs describe-tasks --cluster myapp-lab --tasks $t --query 'tasks[0].[stoppedAt,stoppedReason]' --output text; done
Scenario analysis
The pipeline worked yesterday, but today all AWS tasks report “Not authorized to perform sts:AssumeRoleWithWebIdentity”, and there are no IAM change records. List your troubleshooting order.

① Check the OIDC line in the task log for the issuer and sub, and compare them word for word with the trust policy; the most common cause is a renamed organization, project or service connection (visible in the Azure DevOps audit log); ② check whether the organization GUID in the issuer matches the OIDC provider URL (for example, the pipeline was moved to another organization); ③ confirm the OIDC provider still exists and its audience includes api://AzureADTokenExchange; ④ in CloudTrail, look up the AssumeRoleWithWebIdentity errorMessage of the failed event; ⑤ check whether the Toolkit extension was upgraded and whether the service connection was edited (Use OIDC was unchecked).

Verified instructional videos

▶
Circuit Breakers for Amazon ECS — Containers from the Couch
English · Watching the circuit breaker handle a failed deployment
▶
Remotely access your containers on ECS using ECS Exec! — Containers from the Couch
English · Troubleshooting inside a running Fargate container (requires extra task role permissions; see Docker course Lesson 4)

No verified video on IAM AccessDenied troubleshooting or CloudTrail queries was found.

Official documentation

Video storyboard script (about 60 seconds)

Shot 1 · 0–20s
Visual: a five-step staircase from Azure DevOps to runtime; a red error ball is stuck on the second step.
Narration: to troubleshoot, first locate the layer: failing to get credentials is the STS layer; getting credentials but being rejected is the IAM layer.
Shot 2 · 20–40s
Visual: zoom in on the AccessDenied message, highlighting the principal, action, resource and because.
Narration: the denial message tells you who, what action, on which resource, and whether it is a missing allow or an explicit deny.
Shot 3 · 40–60s
Visual: an ECS task card flips over; the back reads stoppedReason.
Narration: when an ECS deployment is stuck, the answer is almost always in the reason the task stopped: image, network or health check.
or score ≥ 70% on the quiz

Module 8 · Cost, cleanup and self-check

54:00 – 60:00 · Know where the money goes, use Budgets as a safety net, delete in dependency order, and verify with tags that nothing is left behind
6 minAWS Budgets · tagsCleanup order matters★★★★
Learning objectives
  • List the billable items in this lesson's architecture: Fargate (vCPU/memory per second), public IPv4 addresses, ECR storage and transfer, CloudWatch Logs, (optional) EKS control plane, Lambda; and the ALB and NAT gateway that we deliberately avoid.
  • Know Azure Pipelines' Microsoft-hosted free tier: the organization must first be linked to an Azure subscription (set up billing) to enable it; private projects get 1 parallel job, up to 1 hour per run, 1800 minutes per month; runs waiting for approval do not occupy a parallel job.
  • Clean up AWS and Azure DevOps resources in dependency order, and use the resource tagging API to verify nothing is left behind.
Prerequisites: The list of resources created in the first 7 modules. Importance:★★★★

What: billable items in this lesson

ResourceBilling modelUsage in this lessonCost-saving tips
Fargate tasksPer vCPU and memory × seconds running (Linux minimum 1 minute)2 services × 1 task × 0.25 vCPU / 0.5 GB; briefly doubles during deploymentWhen not in use, set the desired count to 0 desired-count 0 or delete the service; consider ARM64 (Graviton) and Fargate Spot (non-production)
Public IPv4 addressEach public IPv4 is billed by the hour (including public IPs automatically assigned to tasks)1 per taskIn production, use private subnets + ALB; delete after the lab is done
ECRStorage is billed per GB-month; cross-region and internet transfer billed separatelyBuild one image each time (about 100–200 MB compressed)Lifecycle policy keeps only the most recent N; pulls within the same region incur no transfer fees.
CloudWatch LogsIngestion billed per GB, storage per GB-monthVery littleSet a retention period (7 days in this lesson)
EKS (optional)Control plane $0.10/hour (standard support) + node / Auto Mode management feesOnly if doing Lab 5BDelete the cluster when done, or at least delete the access entries
LambdaRequests + GB-seconds (free tier available)Dozens of invocationsNearly zero
ALB / NAT gatewayPer hour + usageNot used in this lessonThese two items are the usual big-ticket costs in lab bills
Azure PipelinesMicrosoft-hosted free tier (once enabled) or paid parallel jobs; 1 free self-hostedAbout 5–15 minutes per runWaiting for approval does not use a parallel job; see the Azure DevOps pricing page for exact rates

Why: why Budgets + tags

The most common accident in cloud labs is not a technical error but “forgetting to delete”. AWS Budgets Send an email when actual or forecast costs exceed a threshold; apply one consistent tag (project=ado-lab) lets you list all leftover resources with one command. Note: IAM roles and OIDC providers incur no charges, but they count as security leftovers—a role that still trusts your Azure DevOps organization is a future attack surface.

How: cleanup order (reverse of dependencies)

  1. Azure DevOps: first disable or delete the pipelines (so that no deployment is triggered during cleanup).
  2. ECS services: delete-service --force (this stops tasks), then wait services-inactive.
  3. Task definitions: deregister all revisions, then delete-task-definitions; delete the cluster.
  4. ECR repositories (--force including images), log groups, Lambda functions and aliases.
  5. EKS access entries (if any).
  6. IAM: delete inline policies / detach managed policies → delete roles; finally delete the OIDC provider.
  7. Security groups (can be deleted only after the dependent ENIs are released).
  8. Azure DevOps: delete service connections and Environments; optionally uninstall the extension.
Common misconceptions① “Setting desired count to 0 means no charges”—tasks stop, but ECR storage, logs and (if any) ALB/NAT still incur charges. ② “Deleting the cluster removes the services”—a cluster with active services cannot be deleted; delete the services first. ③ “IAM resources are free, so keep them”—a role that trusts an external OIDC provider is a security leftover. ④ “The estimate is the bill”—the calculator only estimates; actual figures are in Cost Explorer, and bills lag behind.

Resource dependencies and cleanup order

① Pipelines (disable) ② ECS services ③ Task definitions / cluster ④ ECR / logs / Lambda ⑤ EKS access entries ⑥ IAM roles → OIDC provider ⑦ Security groups ⑧ Service connections / Environments / extension Verify: resourcegroupstaggingapi get-resources --tag-filters Key=project,Values=ado-lab should be empty (IAM resources need to be checked separately)
Figure 8-1: stop anything that creates new resources first (the pipeline), then delete from the upper layers downward

Interactive: cost estimator (unit prices are editable)

The default unit prices are approximations of us-east-1 public prices, used only to demonstrate the calculation formula (the EKS control plane at $0.10/hour is a verified value). Look up the ca-central-1 prices on the AWS pricing page, replace them, and then review the results.

Usage
Running tasks
vCPU per task · memory (GB)
Hours running per day · days
ECR storage (GB) · logs (GB)
Unit prices (USD, editable)
Fargate per vCPU·hour · per GB·hour
Public IPv4 per address·hour
ECR per GB·month · log ingestion per GB
ALB per hour · NAT per hour · EKS per hour

Cost and cleanup commands

CommandPurpose
aws budgets create-budgetCreate a monthly cost budget with email alerts
aws ce get-cost-and-usage --filter '{"Tags":{"Key":"project","Values":["ado-lab"]}}'Check actual costs by tag (activate the project tag in “Cost allocation tags” first; there is a delay)
aws ecs delete-service --force + wait services-inactiveDelete the service and stop its tasks
aws ecs deregister-task-definition / delete-task-definitionsDeregister and delete task definition revisions
aws ecr delete-repository --forceDelete the repository and its images
aws resourcegroupstaggingapi get-resources --tag-filters Key=project,Values=ado-labList resources that still carry the tag

Budget alert (recommended before class)

source ~/ado-aws.env
aws budgets create-budget --account-id $ACCOUNT_ID \
  --budget '{"BudgetName":"ado-lab-monthly","BudgetLimit":{"Amount":"10","Unit":"USD"},"TimeUnit":"MONTHLY","BudgetType":"COST"}' \
  --notifications-with-subscribers '[{"Notification":{"NotificationType":"ACTUAL","ComparisonOperator":"GREATER_THAN","Threshold":80,"ThresholdType":"PERCENTAGE"},"Subscribers":[{"SubscriptionType":"EMAIL","Address":"you@example.com"}]}]'

Complete cleanup script

#!/usr/bin/env bash
set -uo pipefail          # no -e: some resources may not exist to begin with
source ~/ado-aws.env
# ② ECS services
for S in myapp-dev myapp-prod; do
  aws ecs delete-service --cluster $CLUSTER --service $S --force --query 'service.status' --output text
done
aws ecs wait services-inactive --cluster $CLUSTER --services myapp-dev myapp-prod
# ③ Task definitions and cluster
for F in myapp myapp-dev myapp-prod; do
  for TD in $(aws ecs list-task-definitions --family-prefix $F --status ACTIVE --query 'taskDefinitionArns[]' --output text); do
    aws ecs deregister-task-definition --task-definition $TD --query 'taskDefinition.revision' --output text >/dev/null
  done
  INACTIVE=$(aws ecs list-task-definitions --family-prefix $F --status INACTIVE --query 'taskDefinitionArns[]' --output text)
  [ -n "$INACTIVE" ] && aws ecs delete-task-definitions --task-definitions $INACTIVE --query 'failures' --output text
done
aws ecs delete-cluster --cluster $CLUSTER --query 'cluster.status' --output text
# ④ ECR / logs / Lambda
aws ecr delete-repository --repository-name $REPO --force --query 'repository.repositoryName' --output text
aws logs delete-log-group --log-group-name /ecs/myapp
aws lambda delete-function --function-name myapp-report
# ⑤ EKS access entries (if you did Lab 5B)
aws eks delete-access-entry --cluster-name lab --principal-arn arn:aws:iam::$ACCOUNT_ID:role/ado-myapp-dev-deploy 2>/dev/null
# ⑥ IAM
for R in ado-myapp-dev-deploy ado-myapp-prod-deploy; do
  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
  aws iam delete-role --role-name $R
done
aws iam detach-role-policy --role-name myappTaskExecutionRole --policy-arn arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy
aws iam delete-role --role-name myappTaskExecutionRole
aws iam detach-role-policy --role-name myappReportLambdaRole --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
aws iam delete-role --role-name myappReportLambdaRole
aws iam delete-open-id-connect-provider --open-id-connect-provider-arn arn:aws:iam::$ACCOUNT_ID:oidc-provider/vstoken.dev.azure.com/$ADO_ORG_ID
# ⑦ Security groups (ENI release for tasks may take a few minutes)
sleep 60; aws ec2 delete-security-group --group-id $SG
# Verify
aws resourcegroupstaggingapi get-resources --tag-filters Key=project,Values=ado-lab --query 'ResourceTagMappingList[].ResourceARN'
aws iam list-roles --query "Roles[?starts_with(RoleName,'ado-myapp') || starts_with(RoleName,'myapp')].RoleName"
aws iam list-open-id-connect-providers
[]
[]
{
    "OpenIDConnectProviderList": []
}

Resource tagging API results can lag by a few minutes and may briefly list just-deleted resources; treat each service's own list/describe output as authoritative. Budgets can be kept as a long-term reminder (the AWS Budgets pricing page governs budget billing rules).

Lab 8: cleanup and verification (about 5 minutes)

Azure DevOps: disable the pipeline: Pipelines → this pipeline → ⋮ → Settings → Processing of new run requests: Disabled (or simply delete the pipeline).
AWS: run the cleanup script: copy the cleanup-ado-aws.sh script from the “Commands” page, save it and run it bash cleanup-ado-aws.sh, checking the output one command at a time.
Azure DevOps: delete service connections and Environments: Project settings → Service connections → delete aws-myapp-dev,aws-myapp-prod; Pipelines → Environments → delete myapp-aws-dev,myapp-aws-prod. You can also use the CLI:
az devops configure --defaults organization=https://dev.azure.com/myorg project=myapp-lab
for n in aws-myapp-dev aws-myapp-prod; do
  id=$(az devops service-endpoint list --query "[?name=='$n'].id" -o tsv)
  [ -n "$id" ] && az devops service-endpoint delete --id $id --yes
done
Verify nothing is left: the verification commands should all return empty output; the next day, confirm in Cost Explorer that ado-lab related costs have stopped growing.

Self-check checklist for this lesson

Case 1: weekend bill

Problem: After training, learners only set the ECS service desired count to 0 and forgot to delete the NAT gateway and ALB; a month later each person incurred tens of dollars in charges. Approach: Lab templates do not create NAT/ALB by default; Budgets alert when actual costs exceed 80%; the training account is cleaned up weekly by script, by tag.

Case 2: “orphaned” trust relationship

Problem: A year after the project was decommissioned, a security audit found that AWS still had 6 trust vstoken.dev.azure.com/… roles, one with full S3 permissions; the matching Azure DevOps project had been reused by another team under the same name. Risk: Same project name + same service connection name = the same subject. Approach: The decommissioning process includes “deleting the role and OIDC provider”; the trust policy is managed by IaC and periodically compared with the service connections that actually exist in Azure DevOps.

Case 3: ECR storage grows quietly

Problem: Each commit builds a 400 MB image; after two years the repositories reach several TB. Approach: Lifecycle policy: images without a release tag are kept for 30 days, and the most recent 50 release-tagged images are kept; digests currently in use in prod are protected by an extra tag applied by the release pipeline.

Common errors during cleanup

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

Cause: The cluster still has services (including DRAINING ones). Fix: First delete-service --force and wait services-inactive.

DeleteConflict: Cannot delete entity, must delete policies first.

Cause: The role still has inline policies or attached managed policies. Fix:list-role-policies + delete-role-policy; list-attached-role-policies + detach-role-policy.

DependencyViolation: resource sg-… has a dependent object

Cause: Task ENIs have not yet been released. Fix: wait a few minutes before deleting; aws ec2 describe-network-interfaces --filters Name=group-id,Values=$SG check which resource is holding them.

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

Cause: Did not add --force. Fix:aws ecr delete-repository --repository-name myapp --force.

ClientException: The specified task definition is not in INACTIVE status (delete-task-definitions failed)

Cause: Only deregistered (INACTIVE) revisions can be deleted. Fix: First deregister-task-definition.

Command-line exercises
1. List the ARNs of all resources in the account that carry the tag project=ado-lab.
aws resourcegroupstaggingapi get-resources --tag-filters Key=project,Values=ado-lab --query 'ResourceTagMappingList[].ResourceARN' --output text
2. Without deleting the service, stop myapp-dev from incurring compute charges.
aws ecs update-service --cluster myapp-lab --service myapp-dev --desired-count 0
Scenario analysis
The team wants to keep the lab environment for use next week, but does not want to pay for idle time. Which resources can be kept and which should be stopped?

Can keep (almost no charges): ECR repositories (small storage charge), task definitions, the cluster (no charge), IAM roles and OIDC providers (no charge, but confirm the trust scope), log groups (set a retention period). Should stop: set the ECS service desired count to 0 (stops Fargate and public IPv4 charges); delete the EKS cluster, or at least confirm a reason to keep it ($0.10/hour); delete any ALB/NAT. Disable pipeline triggers in Azure DevOps so that automatic deployments during idle time do not set the desired count back (the deployment script does not change desired, but a new deployment starts tasks).

Verified instructional videos

▶
Cost optimization on AWS Fargate — Containers from the Couch
English · Fargate cost optimization ideas (duration and date not verified)
▶
AWS re:Invent 2023 - Boosting efficiency: How to realize 70% cost reduction with AWS Fargate -CON318 — AWS Events
English · Graviton, Spot and capacity planning

Official documentation

Video storyboard script (about 45 seconds)

Shot 1 · 0–15s
Visual: a billing meter ticks: Fargate, public IP, ECR, logs; grey ALB and NAT are crossed out.
Narration: this lesson's lab topology deliberately avoids ALB and NAT to keep costs to a minimum.
Shot 2 · 15–35s
Visual: dominoes fall in sequence: pipeline, service, task definition, repository, role, OIDC provider.
Narration: cleanup must follow dependencies in reverse order, stopping the pipeline that creates resources first.
Shot 3 · 35–45s
Visual: the tag query returns empty; a green check mark.
Narration: finally, confirm with a tag query that nothing is left, and delete the trust relationships too.
or score ≥ 70% on the quiz

Command cheat sheet

Azure Pipelines → the most-used tasks, commands and policy snippets for AWS deployments
Printable

1. Service connections and credentials

PurposeCommand / configuration
OIDC provideraws iam create-open-id-connect-provider --url https://vstoken.dev.azure.com/<org GUID> --client-id-list api://AzureADTokenExchange
Trust policy conditionvstoken.dev.azure.com/<GUID>:aud = api://AzureADTokenExchange; …:sub = sc://<org>/<project>/<service connection>; action sts:AssumeRoleWithWebIdentity
Service connectionType AWS; Role to Assume = role ARN; check Use OIDC; leave keys blank; Role Session Name recommended as ado-<app>-<env>
Credential durationvariable aws.rolecredential.maxduration: 900–43200, ≤ role MaxSessionDuration (default 3600)
Who is callingaws sts get-caller-identity (OIDC success: assumed-role/role name/session name, the key starts with ASIA)
Script approachPOST ${SYSTEM_OIDCREQUESTURI}?api-version=7.1&serviceConnectionId=<GUID> (Bearer $(System.AccessToken)) → .oidcToken → AWS_WEB_IDENTITY_TOKEN_FILE + AWS_ROLE_ARN

2. ECR

aws ecr get-login-password | docker login --username AWS --password-stdin $ACCOUNT.dkr.ecr.$REGION.amazonaws.com
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=$TAG --query 'imageDetails[0].imageDigest' --output text
echo "##vso[task.setvariable variable=IMAGE_URI;isOutput=true]$ECR/myapp@$DIGEST"

3. ECS deployment

NEW_TD=$(aws ecs register-task-definition --cli-input-json file://td.json --query 'taskDefinition.taskDefinitionArn' --output text)
aws ecs update-service --cluster C --service S --task-definition "$NEW_TD"
aws ecs wait services-stable --cluster C --services S          # 15s × 40 times
aws ecs describe-services --cluster C --services S \
  --query "services[0].deployments[?status=='PRIMARY']|[0].[taskDefinition,rolloutState]" --output text
aws ecs describe-services --cluster C --services S --query 'services[0].events[:8].[createdAt,message]' --output text
aws ecs update-service --cluster C --service S \
  --deployment-configuration "deploymentCircuitBreaker={enable=true,rollback=true},maximumPercent=200,minimumHealthyPercent=100"

4. EKS and Lambda

aws eks create-access-entry --cluster-name lab --principal-arn arn:aws:iam::ACCT:role/ado-myapp-dev-deploy
aws eks associate-access-policy --cluster-name lab --principal-arn arn:aws:iam::ACCT:role/ado-myapp-dev-deploy \
  --policy-arn arn:aws:eks::aws:cluster-access-policy/AmazonEKSEditPolicy --access-scope type=namespace,namespaces=myapp
aws eks update-kubeconfig --name lab && kubectl auth can-i --list -n myapp
helm upgrade --install myapp ./chart -n myapp --set image.repository=$REPO_URI --set image.digest=$DIGEST --rollback-on-failure --wait --timeout 5m
NEW=$(aws lambda update-function-code --function-name F --zip-file fileb://fn.zip --publish --query Version --output text)
aws lambda wait published-version-active --function-name F --qualifier $NEW
aws lambda update-alias --function-name F --name live --function-version $OLD --routing-config "{\"AdditionalVersionWeights\":{\"$NEW\":0.1}}"

5. YAML snippets

PurposeHow to write it
Toolkit script tasktask: AWSShellScript@1 + awsCredentials,regionName,scriptType: filePath,disableAutoCwd: true,workingDirectory
Cross-stage output variablestep name: img + isOutput=true; downstream job $[ stageDependencies.Build.Push.outputs['img.IMAGE_URI'] ]; downstream stage dependsOn must include Build
deployment jobdeployment: X + environment: myapp-aws-prod + strategy.runOnce.deploy.steps; remember - checkout: self
deploy to prod only on maincondition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
ECR push taskECRPushImage@1: always set pushTag (default latest)

6. Least-privilege snippet (pipeline role)

CapabilityActionsResource
ECR loginecr:GetAuthorizationToken*
Pushecr:BatchCheckLayerAvailability,InitiateLayerUpload,UploadLayerPart,CompleteLayerUpload,PutImagerepository ARN
ECS deploymentecs:RegisterTaskDefinition,DescribeTaskDefinition (*); ecs:UpdateService,DescribeServicesservice ARN
Pass roleiam:PassRole + condition iam:PassedToService=ecs-tasks.amazonaws.comexecution role / task role ARN
EKSeks:DescribeCluster + access entries + namespace-scoped access policycluster ARN
Lambdalambda:UpdateFunctionCode,PublishVersion,GetAlias,UpdateAliasfunction ARN and function ARN:*

7. One-line troubleshooting

Error keywordCheck first
System.AccessToken is undefinedClassic pipelines: tick Allow scripts to access the OAuth token; scripts need env mapping
No OpenIDConnect provider foundWhether the provider URL and issuer match exactly, and whether it is the same account
Not authorized to perform sts:AssumeRoleWithWebIdentityTrust policy sub/aud (renamed? case?)
DurationSeconds exceeds the MaxSessionDurationmaxduration variable vs role setting
not authorized to perform: iam:PassRolePassRole resource and condition
no basic auth credentials / token has expiredRe-login to ECR; hostname matches
ResourceInitializationError … connection issue … ECRassignPublicIp / NAT / VPC endpoints
deployment failed: tasks failed to startstoppedReason of stopped tasks
Unauthorized (kubectl)Access entry (role ARN)
Forbidden (kubectl)Access policy scope / RBAC

Capstone lab + final quiz

myapp: CI → ECR → ECS Fargate (dev automatic, prod approval) → circuit breaker rollback drill → cleanup
After class ≈ 45 minutesWill incur a small amount of AWS charges
Scenario The myapp team needs to put the service live on AWS (ca-central-1). The security team requires: no long-term AWS keys stored in Azure DevOps; dev and prod use different identities, and the dev identity is technically unable to change prod; prod deployment must be approved and allowed only from the main branch; the deployed image must be exactly the one verified in dev; when a deployment fails, the service recovers automatically and the pipeline honestly shows the failure. Complete and demonstrate one failed rollback, then clean up all resources.
Cost, permissions and risk
  • Cost: 2 Fargate tasks (0.25 vCPU / 0.5 GB) × lab duration + 1 public IPv4 per task + a little ECR storage and logs; estimated using approximate us-east-1 unit prices, one hour of the lab is on the order of $0.1 (ca-central-1 follows the pricing page; you can replace the unit prices with the Module 8 estimator). No ALB/NAT/EKS is created.
  • Permissions: the preparation phase needs an administrator identity that can create IAM roles, OIDC providers and ECS/ECR/log resources; the pipeline uses only ado-myapp-dev-deploy and ado-myapp-prod-deploy two least-privilege roles. In Azure DevOps, you need project administrator rights (to create service connections and Environments) and organization-level rights to install extensions.
  • Risk: the tasks get public IPs, so allow only your own IP; after the lab, be sure to run the cleanup in step 7, including deleting the IAM roles and OIDC provider that trust your organization.
Pre-flight checks (Modules 0, 2, 6)
source ~/ado-aws.env
aws iam list-open-id-connect-providers --query 'OpenIDConnectProviderList[].Arn' --output text
aws iam get-role --role-name ado-myapp-dev-deploy --query 'Role.AssumeRolePolicyDocument.Statement[0].Condition'
aws iam get-role --role-name ado-myapp-prod-deploy --query 'Role.AssumeRolePolicyDocument.Statement[0].Condition'
aws ecs describe-services --cluster $CLUSTER --services myapp-dev myapp-prod \
  --query 'services[].[serviceName,runningCount,deploymentConfiguration.deploymentCircuitBreaker]' --output table

If anything is missing, go back to the lab of the corresponding module and complete it. In Azure DevOps there should be service connections aws-myapp-dev,aws-myapp-prod (all OIDC, no keys), Environments myapp-aws-dev,myapp-aws-prod (the latter has approvals).

Complete pipeline (Modules 3, 4, 6): use the complete file below to replace azure-pipelines-aws.yml.
trigger:
  branches: { include: [ main ] }
parameters:
- name: breakHealthcheck
  displayName: Rollback drill: make this deployment's health check fail
  type: boolean
  default: false
pool:
  vmImage: ubuntu-latest
variables:
  awsRegion: ca-central-1

stages:
- stage: Build
  jobs:
  - job: Push
    steps:
    - checkout: self
    - task: AWSShellScript@1
      name: img
      displayName: Build & push to ECR
      inputs:
        awsCredentials: aws-myapp-dev
        regionName: $(awsRegion)
        scriptType: filePath
        filePath: deploy/push.sh
        disableAutoCwd: true
        workingDirectory: $(Build.SourcesDirectory)
      env:
        REPO: myapp
    - publish: $(Build.ArtifactStagingDirectory)/image.json
      artifact: image

- stage: DeployDev
  dependsOn: Build
  jobs:
  - deployment: Ecs
    environment: myapp-aws-dev
    variables:
      imageUri: $[ stageDependencies.Build.Push.outputs['img.IMAGE_URI'] ]
      imageTag: $[ stageDependencies.Build.Push.outputs['img.IMAGE_TAG'] ]
      aws.rolecredential.maxduration: "1800"
    strategy:
      runOnce:
        deploy:
          steps:
          - checkout: self
          - task: AWSShellScript@1
            name: ecs
            displayName: Deploy myapp-dev
            inputs:
              awsCredentials: aws-myapp-dev
              regionName: $(awsRegion)
              scriptType: filePath
              filePath: deploy/ecs-deploy.sh
              disableAutoCwd: true
              workingDirectory: $(Build.SourcesDirectory)
            env:
              CLUSTER: myapp-lab
              SERVICE: myapp-dev
              FAMILY: myapp-dev
              IMAGE_URI: $(imageUri)
              APP_VERSION: $(imageTag)
              HEALTH_PATH: ${{ iif(parameters.breakHealthcheck, '/does-not-exist', '/healthz') }}

- stage: DeployProd
  dependsOn: [Build, DeployDev]
  condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
  jobs:
  - deployment: Ecs
    environment: myapp-aws-prod
    variables:
      imageUri: $[ stageDependencies.Build.Push.outputs['img.IMAGE_URI'] ]
      imageTag: $[ stageDependencies.Build.Push.outputs['img.IMAGE_TAG'] ]
      aws.rolecredential.maxduration: "1800"
    strategy:
      runOnce:
        deploy:
          steps:
          - checkout: self
          - task: AWSShellScript@1
            displayName: Deploy myapp-prod
            inputs:
              awsCredentials: aws-myapp-prod
              regionName: $(awsRegion)
              scriptType: filePath
              filePath: deploy/ecs-deploy.sh
              disableAutoCwd: true
              workingDirectory: $(Build.SourcesDirectory)
            env:
              CLUSTER: myapp-lab
              SERVICE: myapp-prod
              FAMILY: myapp-prod
              IMAGE_URI: $(imageUri)
              APP_VERSION: $(imageTag)

${{ iif(…) }} is a compile-time template expression that chooses the health check path based on the run parameter; in a normal run it is always /healthz.

Normal release (Modules 3, 4, 6): edit app.py 's welcome message and push to main. Build → DeployDev runs automatically; DeployProd waits for approval → approve → complete. Verify:
aws ecs describe-services --cluster $CLUSTER --services myapp-dev myapp-prod \
  --query "services[].[serviceName, deployments[?status=='PRIMARY']|[0].taskDefinition, deployments[?status=='PRIMARY']|[0].rolloutState]" --output table
for S in myapp-dev myapp-prod; do T=$(aws ecs list-tasks --cluster $CLUSTER --service-name $S --query 'taskArns[0]' --output text)
  aws ecs describe-tasks --cluster $CLUSTER --tasks $T --query 'tasks[0].containers[0].imageDigest' --output text; done

the two digests are identical and equal the pipeline artifact image.json 's value. Note the current dev task definition revision (for example myapp-dev:3), which you will need in the next step.

Circuit breaker rollback drill (Modules 4, 7): on the pipeline page, click Run pipeline, tick the “Rollback drill” parameter and run it. Observe:
  • DeployDev registers a new revision myapp-dev:4, new tasks fail their health checks and are replaced; after 3 cumulative failures the circuit breaker declares failure and rolls back.
  • wait services-stable Final result: success (service stable at :3), but step ⑤ of the script finds PRIMARY ≠ :4, prints service events and stop reasons, and fails with exit code 1.
  • DeployProd is skipped because the previous stage failed—prod is not affected.
aws ecs describe-services --cluster $CLUSTER --services myapp-dev \
  --query 'services[0].deployments[].[status,taskDefinition,rolloutState,rolloutStateReason]' --output table
aws ecs describe-services --cluster $CLUSTER --services myapp-dev --query 'services[0].events[:6].[createdAt,message]' --output text
|  PRIMARY |  …task-definition/myapp-dev:3 |  COMPLETED |  ECS deployment ecs-svc/… completed. |
…  (service myapp-dev) has reached a steady state.
…  (service myapp-dev) (deployment ecs-svc/…) deployment failed: tasks failed to start.
…  (service myapp-dev) (task …) failed container health checks.

While accessing the dev task's http://IP:5000/, the service should remain available throughout (min 100% ensures old tasks are not stopped before new tasks are healthy). The whole drill takes about 5–10 minutes.

Identity isolation check (Modules 2, 6): in a test branch, change DeployProd's awsCredentials to aws-myapp-dev, run from that branch with “Run pipeline”. Expect DeployProd not to execute (the condition allows only main); temporarily remove the condition and try again, expecting AccessDeniedException … ecs:UpdateService … myapp-prod. Delete the test branch after verifying.
Audit (Module 7)
aws cloudtrail lookup-events --lookup-attributes AttributeKey=EventName,AttributeValue=AssumeRoleWithWebIdentity \
  --max-results 10 --query 'Events[].CloudTrailEvent' --output text | jq -r '[.eventTime,.requestParameters.roleArn,.errorCode // "OK"] | @tsv'

You should see the successful exchanges for the dev and prod roles, as well as records left by the negative test in step 5 (if any).

Cleanup (Module 8): disable the pipeline → run cleanup-ado-aws.sh → delete service connections and Environments → confirm nothing is left using the tag API and an IAM listing.
Acceptance checklist

Open-ended self-check (6 questions)

1. If the Azure DevOps organization is migrated to a new organization (new GUID), what needs to change on the AWS side?

Create an OIDC provider with the new GUID URL (in each account), change the Principal and condition-key prefix in every role's trust policy to the new provider, and update the organization name in the subject; delete the old provider after the switchover is complete. If you manage it with IaC, this is a parameter change.

2. Why does this lesson's deployment script reject an IMAGE_URI that is not a digest? When would you relax this?

To guarantee consistency across environments and precise rollback. Accepting tags should only be considered when ECS version consistency is explicitly in use and the repository is IMMUTABLE with unique tags, and even then it is less clear than a digest.

3. Each Toolkit task fetches credentials when it starts. What does this mean for long pipelines?

Each task has its own STS session (15 minutes by default); splitting long work into several tasks is safer than lengthening a single credential; but each exchange produces an STS call and a CloudTrail event, and a failed OIDC token request on the Azure DevOps side will also fail a single task (retries since 1.20.0).

4. If prod is to be moved to a separate account, what is the minimum set of changes needed?

Create the OIDC provider and prod role in the prod account (with the same subject), plus the ECS resources and the execution role; the ECR repository policy allows the prod account to pull (or the image is copied to the prod account); update the role ARN in the prod service connection; parameterize the account ID in the task definition template. The pipeline YAML itself barely changes.

5. What kinds of failures are the circuit breaker and CloudWatch alarm rollbacks each suited to?

Circuit breaker: tasks that fail to start, health check failures. Alarm rollback: tasks that are healthy but business metrics worsen (5xx, latency, error logs). Both can be enabled together; either trigger causes failure.

6. Without using the Toolkit, how would you obtain temporary AWS credentials in a container job on a self-hosted Linux agent? What are the prerequisites?

Use System.OidcRequestUri + serviceConnectionId to request an OIDC token (env mapped to System.AccessToken), write it to a file and set AWS_WEB_IDENTITY_TOKEN_FILE and AWS_ROLE_ARN, so the CLI/SDK calls AssumeRoleWithWebIdentity. Prerequisites: the pipeline is authorized to use that service connection; the trust policy subject matches that connection; the token must be requested again before it expires. Verify in your own organization before production use.

Sources and version notes

Basis for the technical facts in this lesson (verified 2026-11-15; all pages below were read that day)
TopicVerified conclusionSource (read 2026-11-15)
AWS Toolkit for Azure DevOps versionsLatest GitHub Release v1.26.0 (2026-10-01), previously v1.24.0 (2026-01-09), v1.22.0 (2025-08-16); CHANGELOG: 1.15.0 (2024-08-01) “Add support for OIDC authentication”; 1.18.0 (2024-12-03) Node 20; 1.19.0 fixed the OIDC request URL for the PowerShell task and shows a hint when OAuth is not enabled; 1.20.0 (2025-03-19) retries on OIDC token retrieval failures; the current source tasks declare Node10/Node20_1/Node24 executorsReleases · CHANGELOG
Toolkit OIDC configurationService connection: role ARN + Use OIDC, no keys; IAM OIDC provider https://vstoken.dev.azure.com/{org GUID}, ClientIdList api://AzureADTokenExchange; trust policy condition :aud,:sub = sc://{org name}/{project name}/{service connection name}; action sts:AssumeRoleWithWebIdentity; example template example_cfn.yaml; official docs “strongly recommend” using OIDCREADME · example_cfn.yaml
Toolkit credential implementationawsConnectionParameters.ts: default session name aws-vsts-tools; duration 900–43200 (variable aws.rolecredential.maxduration); pure OIDC is used only when there are no keys and a role ARN is set; the token is obtained through the Task API createOidcToken (passing the service connection ID) and requires System.AccessToken; log format OIDC Token generated: issuer: {…} sub: {…}, aud: {…}src/lib/awsConnectionParameters.ts
Toolkit task inputsECRPushImage: imageSource, sourceImageName/Tag (default latest), repositoryName, pushTag (default latest), autoCreateRepository, outputVariable (outputs the tagged image name); AWSShellScript: injects AWS_ACCESS_KEY_ID/SECRET/SESSION_TOKEN/REGION, inline up to 5000 characters; LambdaDeployFunction: codeonly/codeandconfiguration, publish defaults to true, no alias managementsrc/tasks/*/task.json · AWS Shell Script task
Toolkit credential sourcesservice connection (keys, role assumption, session token); variables AWS.AccessKeyID/SecretAccessKey/SessionToken/Region; standard environment variables (including AWS_ROLE_ARN); EC2 instance metadataToolkit User Guide: Getting started
AWS official blogread the organization GUID from the task log; the audience is the fixed Azure DevOps value; requires Toolkit ≥ 1.15; examples use AWSCLI@1 and AWSShellScript@1How to federate into AWS from Azure DevOps using OpenID Connect (2024-12-17)
Azure DevOps OIDC token APIPOST …/_apis/distributedtask/hubs/{hub}/plans/{planId}/jobs/{jobId}/oidctoken?serviceConnectionId=…, response oidcToken; System.OidcRequestUri variables and the example of “requesting a new idToken from a script” (AzureRM)Oidctoken - Create · Sprint 240 · Predefined variables
IAM OIDC providerURL is case-sensitive and unique per account; up to 100 audiences; IAM prefers verifying the JWKS endpoint against the trusted CA library, falling back to the thumbprint when necessary; the OIDC provider must be in the same account as the role that trusts itCreate an OIDC identity provider
App Runner / Express ModeApp Runner has not accepted new customers since 2026-04-30; existing customers can keep using it, no new features are planned, and ECS Express Mode is recommended; Express Mode needs an image, a task execution role and an infrastructure role, with no extra chargeApp Runner availability change · Express Mode overview(consistent with Lesson 4 of the Docker course)
ECS deploymentminimumHealthyPercent rounds up, maximumPercent rounds down; container image resolution: the first task determines the digest, later tasks and subsequent service updates reuse it, and force new deployment re-resolves it; Fargate Linux platform 1.3.0+; parameter versionConsistencyDeploy ECS services by replacing tasks
ECS circuit breakertwo-phase detection; BOUNDED_PERCENT defaults to 50, limited to 3–200; rolls back to the most recent COMPLETED deployment; ECS deployment controller onlyDeployment circuit breaker(consistent with Lesson 4 of the Docker course)
ECRauthentication token 12 hours, username AWS; IMMUTABLE rejects overwriting tagsRegistry authentication · Tag mutability
EKSaccess entries / access policies / authentication mode; EKS 1.37; control plane $0.10/hour (consistent with Lesson 7 of the K8s course)Access entries · EKS pricing
Lambdaversions are immutable; alias weighted routing (primary version + one additional version); wait published-version-active exists in the AWS CLI v2 referenceAliases · published-version-active
Azure Pipelines parallel jobsthe Microsoft-hosted free tier requires billing to be set up for the organization (linking an Azure subscription) before it can be enabled: private projects get 1 job, up to 1 hour per run, 1800 minutes per month; paid jobs run up to 31 hours per run; self-hosted gets 1 free; waiting for approval does not use a parallel job; public projects have been retired and will become private from 2027Configure and pay for parallel jobs(page updated 2026-11-03)
HelmHelm 4.3.2; --atomic → --rollback-on-failure; installation script get-helm-4same as the Helm course in this repository (verified 2026-11-15)

Video verification notes

The following videos were verified for title and channel on 2026-11-15 through the YouTube oEmbed endpoint (https://www.youtube.com/oembed?url=…&format=json): Bret Fisher, “Serverless for container fans via Amazon ECS and AWS Lambda” (7fjJqokRlKI); AWS Events, “AWS re:Invent 2024 - Unleashing the power of Amazon ECS for platform teams (SVS330)” (T-fFyEsLXXE), “AWS re:Invent 2023 - Dive deep into Amazon ECR (CON405)” (PHuKrcsAaDw), “AWS re:Invent 2023 - Boosting efficiency: How to realize 70% cost reduction with AWS Fargate -CON318” (WVGxnUEr1OU); AWS Developers, “Amazon EKS Auto Mode | Fully Automated Kubernetes Clusters” (s9d61eYkGzs), “Deploying a Modern Application Stack to AWS Fargate with Amazon ECS - AWS Online Tech Talks” (Nv7s-N8ZxQA); Amazon Web Services, “Amazon Elastic Container Registry (Amazon ECR) Explained | Amazon Web Services” (GtbTmvMcKRg); Containers from the Couch, “Circuit Breakers for Amazon ECS” (Y2Ez9M7A95Y), “EKS Pod Identity vs IRSA | Securely Connect Kubernetes Pods to AWS Services” (aUjJSorBE70), “Remotely access your containers on ECS using ECS Exec!” (NyiMoyx_xj4), “Cost optimization on AWS Fargate” (Cnmejv98sv0); Be A Better Dev, “How to Setup AWS ECS Fargate with a Load Balancer | Step by Step” (o7s-eigrMAI); TechWorld with Nana, “AWS EKS - Create Kubernetes cluster on Amazon EKS | the easy way” (p6xDCz00TxU); CoderDave, “Azure DevOps Environments EXPLAINED” (gN4j65w7wIM), “Azure DevOps Environments: Checks and Gates DEEP DIVE” (FbXKpo6oEyg), “Don't deploy now! How to DELAY a deployment” (MjkmKeEGOyc). oEmbed does not return durations or publish dates, so these are not shown on the cards. No verified video was found for “Azure DevOps OIDC federation to AWS”, Lambda alias weighted routing, IAM AccessDenied troubleshooting, or the AWS multi-account + Azure DevOps promotion topic; the related modules provide storyboard scripts only. All videos are in English, and some were recorded before the current version, so for details follow this lesson and the official documentation.

Voice narration notes

The “Voice” tab uses the browser's Web Speech API (speechSynthesis, en-US) to read the narration script aloud in real time; English terms are pronounced with en-US; the result depends on the voices installed on the operating system. This courseware generation environment cannot call a TTS service, so no MP3 is embedded; for offline audio, give the narration script to a TTS service such as Azure AI Speech to generate it.

Known limitations and conservative handling

  • Lab commands are written from the official docs, the CLI reference and the Toolkit source code,not executed line by line in a real AWS account and Azure DevOps organization; account IDs, GUIDs, ARNs, IPs, digests, revision numbers and raw service event text in the “expected output” are all examples.
  • The Toolkit's log wording and how errors are presented change between versions: the latest code in the repository reports an error containing the subject directly when a pure OIDC exchange fails, while released versions may show “invalid security token” on subsequent calls.
  • The basis for the “script approach” (calling System.OidcRequestUri and passing the AWS service connection ID) is that Microsoft's AzureRM examples and the Toolkit source use the same API; Microsoft's documentation does not specifically demonstrate AWS-type connections, so this course marks it for verification in your own organization.
  • The Toolkit reads System.AccessToken in a YAML pipeline without extra mapping; this is based on the AWS blog example; classic pipelines need “Allow scripts to access the OAuth token” ticked.
  • For the recovery behavior of the service revision after an ECS circuit-breaker rollback (including network configuration) and the raw service event text, go by your actual describe-services output.
  • Apart from the EKS $0.10/hour, the unit prices in the estimator are approximations of us-east-1 public prices, used only to demonstrate the formula; for actual ca-central-1 prices, check the AWS pricing page. Azure DevOps paid parallel job unit prices are not listed; check the Azure DevOps pricing page.
  • The reference path for deployment job output variables (including lifecycle hook names) is complex; this lesson references only outputs of regular jobs. When needed, follow Microsoft's “Deployment jobs” documentation.