Azure DevOps Hour 4: Going to the Cloud (AWS)
- 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}, audienceapi://AzureADTokenExchangeand subjectsc://{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
| # | Time | Module | Core content | Animation / interaction | Lab |
|---|---|---|---|---|---|
| 0 | Before class | Warm-up and AWS setup | AWS account, CLI, Toolkit extension, variable file, OIDC provider, ECR/ECS base resources | Environment self-check checklist | One-time script to create lab resources |
| 1 | 00–05 | Choosing an AWS deployment architecture | ECS 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 |
| 2 | 05–14 | AWS service connections and credentials (incl. OIDC) | Access keys vs role assumption vs OIDC; Toolkit credential resolution order; ADO OIDC token API; AssumeRoleWithWebIdentity script approach | Core animation: service connection → OIDC token → STS temporary credentials → ECR/ECS API; switch between 6 failure scenarios | Create an OIDC service connection and get it working sts get-caller-identity |
| 3 | 14–21 | Build and push to ECR | ECRPushImage task vs AWS CLI; ECR authentication token; immutable tags; read the digest and use it as an output variable | Tag drift vs digest pinning simulator | CI stage: build, push, output the digest |
| 4 | 21–30 | Deploy to ECS on Fargate | task definition revisions, iam:PassRole, update-service, wait services-stable, rolloutState, circuit breaker thresholds and rollback | Rolling deployment + circuit-breaker rollback animation | Automatic deployment to the dev environment |
| 5 | 30–38 | Deploy to EKS and Lambda | access entries + access policies (namespace scope), get-token, kubectl/Helm 4; Lambda versions, aliases, weighted routing | EKS authentication/authorization chain (401 vs 403) + alias weight slider | Helm deployment to EKS (optional); Lambda alias canary |
| 6 | 38–45 | Multi-account and environment promotion | a separate account/role/service connection per environment; Environments approvals and checks; checks on service connections; cross-account ECR pulls | Promotion flow simulator (approval, rejection, wrong connection use) | prod stage + approval |
| 7 | 45–54 | Hands-on cloud deployment troubleshooting | AccessDenied, AssumeRole failures, ECR login failures, stuck ECS deployments, EKS Unauthorized; locating with CloudTrail | Error message classifier + interactive troubleshooting tree | Inject 3 faults and fix them |
| 8 | 54–60 | Cost, cleanup and self-check | billing breakdown, the cheapest lab topology, Budgets, cleanup in dependency order | Cost estimator (editable unit prices) | Cleanup script + verify nothing is left behind |
| — | After class | Cheat sheet · Capstone lab | myapp: CI → ECR → ECS Fargate (dev automatic, prod approval) → circuit-breaker rollback drill → cleanup | Final quiz (12 questions) | Capstone lab |
Knowledge Coverage Matrix
| Target skills | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands / tasks | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| AWS compute service selection | ✓ | · | · | ✓ | ✓ | · | · | ✓ | aws ecs/eks/lambda list-* | M1 |
| Service connections without long-lived keys (OIDC) | · | ✓ | · | · | · | ✓ | ✓ | · | AWSShellScript@1,create-open-id-connect-provider | M2 |
| least-privilege IAM policies and PassRole | · | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | · | iam put-role-policy,iam:PassedToService | M2/M4 |
| ECR push, immutable tags, digest | · | · | ✓ | ✓ | ✓ | ✓ | ✓ | · | ECRPushImage@1,ecr describe-images | M3 |
| ECS deployment, waiting for stability, circuit-breaker rollback | · | · | · | ✓ | · | ✓ | ✓ | · | register-task-definition,update-service,wait services-stable | M4 / Capstone |
| EKS authorization and kubectl/Helm deployment | · | · | · | · | ✓ | · | ✓ | ✓ | eks create-access-entry,helm upgrade --install | M5 |
| Lambda version and alias releases | ✓ | · | · | · | ✓ | · | · | · | update-function-code --publish,update-alias | M5 |
| multi-account promotion and approvals | · | ✓ | · | · | · | ✓ | · | · | deployment jobs,environment: | M6 / Capstone |
| cloud deployment troubleshooting | · | ✓ | ✓ | ✓ | ✓ | · | ✓ | · | cloudtrail lookup-events,ecs describe-services | M7 |
| cost control and cleanup | ✓ | · | ✓ | · | ✓ | · | · | ✓ | budgets create-budget,ecs delete-service | M8 |
Topics not covered in this course (and where to learn them)
| Topic | Why not in this course | Where to learn |
|---|---|---|
| full ECS task definition fields, ALB/target groups, native ECS blue/green, hands-on Express Mode, ElastiCache | belongs to “how containers run on AWS”, which the Docker course covers in depth | Docker course Lesson 4 (ECS/ECR) |
| EKS cluster creation, Auto Mode, VPC CNI, Pod Identity, LBC | is a Kubernetes platform topic | K8s course Lesson 7 (EKS) |
| Azure-side workload identity federation (ARM service connections), ACR/ACA/AKS deployments | this course is its AWS counterpart | Hour 3 (Azure) |
| extends templates, protected resources, template security | belongs to pipeline governance | Hour 5 |
| managing all AWS resources with Terraform/CloudFormation | this course uses AWS CLI to create lab resources to reduce prerequisites | Terraform course |
| AWS CodePipeline/CodeBuild/CodeDeploy | this course focuses on “Azure Pipelines as CI/CD, AWS as the runtime platform” | CodePipeline User Guide |
How to use this course
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.
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).
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.
AdministratorAccess and use it in any real pipeline.Module 0 · Warm-up and AWS setup (complete before class)
- CompletedHour 2: an Azure DevOps organization (referred to below as
myorg), projectmyapp-lab, Azure Repos repositorymyapp(the Flask + gunicorn app from the Docker course, listening on port 5000,/healthzreturning 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 role | Both 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 task | AWSShellScript@1 / AWSCLI@1 tasks | The task is responsible for “getting credentials and injecting environment variables”; scripts use the CLI as usual |
az acr login / Docker@2 | aws ecr get-login-password / ECRPushImage@1 | ECR authentication tokens are valid for 12 hours |
| ACA revisions and traffic splitting | ECS task definition revisions + rolling service updates + circuit breaker | The rollback unit is always “the previous revision” |
Environments: myapp-dev / myapp-prod | Environments: myapp-aws-dev / myapp-aws-prod | Use 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.
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
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.
Module 1 · Choosing an AWS deployment architecture
- 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).
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).
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 Fargate | EKS | Lambda | |
|---|---|---|---|
| Pipeline calls | ecs register-task-definition,update-service,wait services-stable | eks update-kubeconfig + kubectl/helm | lambda update-function-code --publish,update-alias |
| Permissions the pipeline role needs | ecs:*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 rollback | deployment circuit breaker + automatic rollback to the previous COMPLETED deployment | helm --rollback-on-failure / kubectl rollout undo | point the alias back to the old version (within seconds) |
| Fixed cost | No cluster fee; billed per task vCPU/memory second | control plane 0.10 USD/hour + nodes (or Auto Mode management fee) | almost zero when there are no requests |
| Team requirements | Basic container knowledge is enough | Requires Kubernetes operations skills | Requires adapting to the event model (web apps need Lambda Web Adapter, etc.) |
| Azure equivalent | Azure Container Apps | AKS | Azure 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).
Architecture diagram: one Azure Pipelines pipeline, three AWS targets
Decision flowchart
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
| Command | Purpose | Notes |
|---|---|---|
aws ecs list-clusters / list-services --cluster | List ECS clusters and services | The pipeline's --cluster,--service parameters come from here |
aws eks list-clusters | List EKS clusters | Every cluster is billed every hour |
aws lambda list-functions | List functions | --query 'Functions[].[FunctionName,PackageType,Runtime]' |
aws apprunner list-services | List App Runner services | New customers' calls will be rejected when creating services; use only for inventorying existing resources |
aws ecs describe-clusters --include STATISTICS | Check the number of running tasks | Determine 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)
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
myapp-dev,myapp-prod that both services exist.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.
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'
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
Official documentation
- AWS Fargate for Amazon ECS
- Amazon ECS Express Mode
- AWS App Runner availability change
- Choosing an AWS container service
Video storyboard script (about 60 seconds)
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.
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.
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.
Module 2 · AWS service connections and credentials (incl. OIDC)
- 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}, audienceapi://AzureADTokenExchange, subjectsc://{org}/{project}/{service connection name}, actionsts:AssumeRoleWithWebIdentity. - Understand the Toolkit task's credential resolution order and session duration (default 900 seconds; variable
aws.rolecredential.maxdurationcan 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-identitya script approach to perform the exchange yourself, and know its prerequisites and limitations.
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
| Configuration | What to fill in the service connection | What the task calls internally | Advantages | Risks |
|---|---|---|---|---|
| ① Access key | Access Key ID + Secret Access Key | Signs requests directly with an IAM user key | Simplest | Long-lived key: once leaked, usable for a long time; needs rotation; IAM user permissions are often too broad |
| ② Access key + role assumption | Key + 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 environment | Still stores one long-lived key (used only for AssumeRole) |
| ③ OIDC federation (recommended) | Fill in only Role to Assume, check Use OIDC, no keys | Requests an OIDC token from Azure DevOps → sts:AssumeRoleWithWebIdentity | In Azure DevOps no AWS secret is stored; the trust policy can be scoped to a specific service connection | A 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-prodto 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
AssumeRoleWithWebIdentityevents 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
- The task reads the service connection parameters:
assumeRoleArn,useOIDC,roleSessionName(defaultaws-vsts-tools). - The task uses the job's
System.AccessTokento 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). - Azure DevOps returns a JWT:
iss=https://vstoken.dev.azure.com/{org GUID},aud=api://AzureADTokenExchange,sub=sc://{org}/{project}/{service connection}. - The task calls STS
AssumeRoleWithWebIdentity(RoleArn, RoleSessionName, WebIdentityToken, DurationSeconds). - 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-configurationand 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. - STS returns temporary credentials (
ASIA…access key, session token, expiration time), and the task passes them asAWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY/AWS_SESSION_TOKEN/AWS_REGIONenvironment 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.
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 | |
|---|---|---|---|
| Issuer | https://vstoken.dev.azure.com/{org GUID} | New ARM connections use the Entra issuer (see Lesson 3) | https://token.actions.githubusercontent.com |
| Audience | api://AzureADTokenExchange | api://AzureADTokenExchange | sts.amazonaws.com |
| subject | sc://org/project/service connection | sc://org/project/service connection (or new format) | repo:owner/repo:ref:… / environment:… |
| Exchange party | AWS STS AssumeRoleWithWebIdentity | Entra ID (federated credential) | AWS STS AssumeRoleWithWebIdentity |
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
Trust policy item-by-item mapping
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.
Core commands and tasks
| Command / task | Purpose | Key parameters |
|---|---|---|
aws iam create-open-id-connect-provider | Create 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-document | Create pipeline role and trust policy | --max-session-duration (default 3600) |
aws iam put-role-policy | Write an inline permissions policy for the role | Tighten per environment and per resource ARN |
AWSShellScript@1 | Run a Bash script with the service connection's credentials | awsCredentials,regionName,scriptType: inline|filePath (inline policy up to 5000 characters) |
AWSCLI@1 | Run an AWS CLI command | awsCommand,awsSubCommand,awsArguments |
variable aws.rolecredential.maxduration | Adjust temporary credential duration | 900–43200 seconds, ≤ role MaxSessionDuration |
aws sts get-caller-identity | Confirm who you are | On OIDC success, the Arn looks like assumed-role/role name/session name |
aws sts assume-role-with-web-identity | Manual exchange in the script approach | No 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)
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”.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-…" }
]
}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
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.
role assumed via OIDC Token and assumed-role/ado-myapp-dev-deploy/aws-vsts-tools.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.
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.
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
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
- aws/aws-toolkit-azure-devops (README: OIDC Federation, sample CloudFormation template example_cfn.yaml)
- AWS blog: How to federate into AWS from Azure DevOps using OpenID Connect (2024-12-17)
- AWS Toolkit for Azure DevOps user guide: Getting started
- IAM: Create an OpenID Connect (OIDC) identity provider
- Azure DevOps REST: Oidctoken - Create · Sprint 240: System.OidcRequestUri
Video storyboard script (about 90 seconds)
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.
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.
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.
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.
Module 3 · Build and push to ECR
- Push in two ways: with the Toolkit's
ECRPushImage@1task, or in aAWSShellScript@1step, usingaws ecr get-login-password | docker login+docker push; know the trade-offs of each. - Understand ECR authentication tokens:
GetAuthorizationTokenThe returned token is valid for 12 hours and has the same permissions as the IAM principal that obtained it; the username is fixed asAWS. - Design pipeline tags:
$(Build.BuildId)-<short SHA>; understand why an IMMUTABLE repository makeslatestthe 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”.
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 | |
|---|---|---|
| Login | task fetches the token and logs in internally | aws ecr get-login-password | docker login --username AWS --password-stdin |
| Inputs | imageSource (imagename / imageid),sourceImageName,sourceImageTag (default latest),repositoryName,pushTag (default latest),autoCreateRepository,outputVariable | any docker/buildx parameters (multi-platform, cache, SBOM, provenance) |
| Output | outputVariable 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 for | simple scenarios, classic pipelines | when you need buildx, caching, digest output (used in this course) |
sourceImageTag 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-a1b2c3dmaps 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
| Tag | Purpose | Used for deployment? |
|---|---|---|
$(Build.BuildId)-$(short SHA) | Unique per build; never overwritten in an IMMUTABLE repository | For human reading and lookup; deployment uses its corresponding digest |
1.4.0 (semantic version) | Added as an extra tag by the pipeline at release time | Same as above |
latest | Convenient for local development | Do not use for deployment; do not push it to IMMUTABLE repositories |
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
Tag vs digest
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.
Core commands and tasks
| Commands / tasks | Purpose | Notes |
|---|---|---|
aws ecr get-login-password | Get registry password (12 hours) | Used with docker login --username AWS --password-stdin {account}.dkr.ecr.{region}.amazonaws.com |
aws ecr describe-images | Look up the digest, push time, and scan status for a tag | --image-ids imageTag=T --query 'imageDetails[0].imageDigest' |
aws ecr batch-get-image | Get the manifest | Can be used to add a tag to an existing image (put-image) |
aws ecr wait image-scan-complete | Wait for the scan to complete on push | then use describe-image-scan-findings as a gate before the |
ECRPushImage@1 | Toolkit push task | Be sure to pushTag |
##vso[task.setvariable variable=X;isOutput=true] | set the output variable | The 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)
deploy/push.sh (see the “Commands” tab, Method B),chmod +x deploy/push.sh then commit.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.
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 | +--------------+---------------------------------+---------------+
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.
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).
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"
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
Official documentation
- Amazon ECR Push task (Toolkit)
- Private registry authentication
- Image tag mutability
- ECS: Container image resolution
- Set variables in scripts (isOutput)
Video storyboard script (about 60 seconds)
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.
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.
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.
Module 4 · Deploy to ECS on Fargate
- 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'staskDefinitionandrolloutState. - 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.
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-definitionCreates a new PRIMARY deployment, and the old one becomes ACTIVE until all of its old tasks are replaced. - Rolling parameters:
minimumHealthyPercent(rounded up) andmaximumPercent(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
- Render: in the repository's
deploy/taskdef.jsontemplate, replace the__IMAGE__,__FAMILY__,__VERSION__etc. with this run's values (for the image, userepository@sha256:…). - Register:
aws ecs register-task-definition --cli-input-json file://td.json→ new revision ARN. This step checksiam:PassRole(execution role, task role). - Update:
aws ecs update-service --cluster C --service S --task-definition new ARN. - Wait:
aws ecs wait services-stable(success condition: the service has only one deployment and runningCount = desiredCount). - Check: read the PRIMARY deployment and require
taskDefinition == new ARNandrolloutState == 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:
thresholdConfigurationDefaults 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.resetOnHealthyTaskControls whether the counter is reset to zero once tasks are healthy. - Rollback:
rollback=trueon failure, it rolls back to the most recent COMPLETED deployment (its task definition revision). Rollback details appear in the service events; therolloutStateset to FAILED is the failed deployment. - You can also add CloudWatch alarm (
alarmsconfiguration) 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.
| Method | Pros | Cons |
|---|---|---|
| CLI script (this lesson) | Transparent, easy to debug, precise permissions | You must write the wait and check logic yourself |
| CloudFormation parameter update | Consistent with IaC, stack rollback | Slow stack updates; you need to understand how the ECS circuit breaker and stack rollback interact |
| CodeDeploy blue/green | Traffic shifting, hooks | Requires ALB and CodeDeploy resources; ECS already has native blue/green (Lesson 4 of the Docker course) |
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
Circuit breaker threshold quick calculation
| desiredCount | 50% × desired | Threshold (bounded to 3–200) |
|---|---|---|
| 1 | 0.5 | 3 |
| 4 | 2 | 3 |
| 10 | 5 | 5 |
| 1000 | 500 | 200 |
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.
Core commands
| Command | Purpose | Key parameters / notes |
|---|---|---|
aws ecs register-task-definition | Register a new revision | --cli-input-json file://td.json; outputs taskDefinition.taskDefinitionArn |
aws ecs update-service | Switch the service to the new revision | --task-definition,--deployment-configuration (circuit breaker / alarms) |
aws ecs wait services-stable | Wait for stability | Checks every 15 seconds; exits with code 255 after 40 failed checks |
aws ecs describe-services | Deployment status and events | deployments[?status=='PRIMARY'],events[:10] |
aws ecs list-tasks --desired-status STOPPED + describe-tasks | Why tasks stopped | stoppedReason,containers[].reason,exitCode |
aws ecs describe-task-definition | View a given revision | Find 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)
deploy/taskdef.json and deploy/ecs-deploy.sh to the repository (chmod +x).myapp-aws-dev, and select None for resource. No approval for dev.- 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 “≤”.
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).
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
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.
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
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
Official documentation
- How the Amazon ECS deployment circuit breaker detects failures
- Deploy Amazon ECS services by replacing tasks
- aws ecs wait services-stable
- Grant a user permissions to pass a role to an AWS service
Video storyboard script (about 75 seconds)
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?
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.
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.
Module 5 · Deploy to EKS and Lambda
- Explain
kubectlThe authentication chain for accessing EKS:aws eks get-tokengenerate a presigned STSGetCallerIdentitytoken → 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,
AmazonEKSEditPolicylimited tomyappnamespace). - In AWSShellScript, use
aws eks update-kubeconfig+helm upgrade --install --rollback-on-failure --wait(Helm 4) to deploy by digest. - Use
update-function-code --publishto publish a Lambda version, and use the aliasliveweighted routing for a canary; rollback = point the alias back to the old version.
What: the two layers of permissions in EKS
| Layer | Who decides | What the pipeline role needs | Failure symptom |
|---|---|---|---|
| AWS API layer | IAM | eks:DescribeCluster (update-kubeconfig read endpoint and CA) | AccessDeniedException … eks:DescribeCluster |
| Kubernetes authentication | EKS (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 authorization | EKS access policy + Kubernetes RBAC | Associate an access policy (cluster or namespace scope), or an RBAC binding to the access entry's group | Error from server (Forbidden): … cannot create resource "deployments" … |
How: the authentication chain
- AWSShellScript injects temporary credentials (Module 2).
aws eks update-kubeconfig --name labWrite a kubeconfig whose user section is an exec plugin: every kubectl call runsaws eks get-token --cluster-name lab.get-tokenUse the current credentials locally to generate a presigned STSGetCallerIdentityURL (with the cluster name header), encoded ask8s-aws-v1.…a Bearer token (short-lived, about 15 minutes).- 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. - Look up the role ARN's access entry → get the Kubernetes username and groups; none → 401.
- Authorization: first check the associated EKS access policy (for example, namespace
myappEdit), then RBAC; if neither allows it → 403.
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-codewhich you can modify. - Version (1, 2, 3…): an immutable snapshot of code and configuration taken at publish time;
--publishmakes 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) | EKS | Lambda | |
|---|---|---|---|
| Release unit | Task definition revision | Deployment / Helm release revision | Function version |
| Traffic shifting | Rolling (or native blue/green) | Rolling (or Argo Rollouts, etc.) | Alias weighting |
| Rollback | Circuit breaker / old revision | --rollback-on-failure / helm rollback | Point the alias back to the old version |
| Extra pipeline permissions | iam:PassRole | Access entry + access policy | lambda:UpdateAlias (and PassRole, if changing the execution role) |
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
Lambda: versions and aliases
Animation A: kubectl request authentication and authorization (401 vs 403)
Animation B: Lambda alias weighted routing
EKS authorization commands (run by cluster admin)
| Command | Purpose | Notes |
|---|---|---|
aws eks describe-cluster --query cluster.accessConfig | Check authentication mode | Must be API or API_AND_CONFIG_MAP |
aws eks create-access-entry | Create an access entry for the IAM role | --principal-arn (role ARN),--type STANDARD |
aws eks associate-access-policy | associate access policy | --policy-arn arn:aws:eks::aws:cluster-access-policy/AmazonEKSEditPolicy --access-scope type=namespace,namespaces=myapp |
aws eks list-associated-access-policies | Verify authorization | Troubleshoot 403 |
kubectl auth can-i --list -n myapp | View permissions for the current identity | Print 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
| Command | Purpose |
|---|---|
aws lambda update-function-code --zip-file fileb://fn.zip --publish | Update $LATEST and publish a new version (returns Version); for an image package, use --image-uri repository@sha256:… |
aws lambda wait published-version-active --qualifier V | Wait 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 live | Check the current target and weights |
Lab 5A: Lambda alias canary (about 5 min, almost zero cost)
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 1aws 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:*\"]}]}"- 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%"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.
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":{}}'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
No oEmbed-verified video on Lambda alias weighted routing was found; please refer to the documentation and storyboard below.
Official documentation
- Grant IAM users access to Kubernetes with EKS access entries
- Access policy permissions
- Lambda function aliases
- Implement Lambda canary deployments using a weighted alias
- Toolkit: AWS Lambda Deploy Function task
Video storyboard script (about 75 seconds)
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.
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.
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.
Module 6 · Multi-account and environment promotion
- 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
stageDependenciescan only reference directly dependent stages.
What: recommended account and identity layout
| Account | Resources | Azure DevOps service connection | Role and trust subject |
|---|---|---|---|
| tools (777788889999) | ECR repository myapp (IMMUTABLE) | aws-myapp-build | ado-myapp-build ← sc://myorg/myapp-lab/aws-myapp-build; push only |
| dev (111122223333) | ECS cluster/service myapp-dev | aws-myapp-dev | ado-myapp-dev-deploy ← …/aws-myapp-dev |
| prod (444455556666) | ECS cluster/service myapp-prod | aws-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
| Control | Where it goes | Purpose |
|---|---|---|
| Approvals | Environment 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 control | prod service connection / Environment | Allow only refs/heads/main (and protected branches) to use it |
| Business hours | Environment | Deploy only during business hours |
| Exclusive lock | Environment | Only one run can deploy to prod at a time |
| Required template | prod service connection | Only pipelines that extend the approved template can use it (Lesson 5) |
| Pipeline permissions | Service connection → Security → Pipeline permissions | Do 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
- 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. - 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*). - 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-imagesto 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.
Multi-account promotion overview
Two gates: Environment and service connection
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 / syntax | Purpose |
|---|---|
environment: myapp-aws-prod | A 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-policy | Allow other accounts to pull |
az devops service-endpoint list | List service connections (for auditing; requires the azure-devops extension) |
az pipelines run --branch | Trigger 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)
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
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.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.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
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.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.
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
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
No verified video on “AWS multi-account + Azure DevOps promotion” was found.
Official documentation
- Create and target an environment
- Define approvals and checks
- Expressions (stageDependencies)
- ECR private repository policy examples
- Organizing Your AWS Environment Using Multiple Accounts
Video storyboard script (about 60 seconds)
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.
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.
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.
Module 7 · Cloud deployment troubleshooting in practice
- 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.
What: the five-layer model
| Layer | Typical error signature | First diagnostic command |
|---|---|---|
| ① Azure DevOps | System.AccessToken is undefined,not have permissions to use the referenced service connection, checks not passing | Run page “Checks” panel; service connection Security |
| ② STS (get credentials) | AssumeRoleWithWebIdentity / AssumeRole operation's AccessDenied,InvalidIdentityToken,ValidationError | issuer/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 |
| ④ ECR | no basic auth credentials,authorization token has expired,name unknown,tag invalid … immutable | aws ecr describe-repositories; sign in again |
| ⑤ Runtime (ECS/EKS) | CannotPullContainerError,ResourceInitializationError, health check failures, circuit breaker rollback; Unauthorized/Forbidden | describe-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) andwith 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, useaws sts decode-authorization-message --encoded-message …to decode (requiressts:DecodeAuthorizationMessagepermission).
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
| Pattern | Service event / stop reason (example) | Common root cause |
|---|---|---|
| Task cannot pull image | CannotPullContainerError: … | digest/tag does not exist; cross-account repository policy; execution role lacks permissions |
| Task cannot reach ECR | ResourceInitializationError: 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 start | Essential container in task exited (exitCode 1/137) | wrong command or environment variable, port conflict, OOM |
| Health check failures | Task failed container health checks / ELB health check failures | wrong path or port, startup slower than startPeriod, dependencies not ready |
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
Use CloudTrail to locate a failed call
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
| Command | Question it answers |
|---|---|
aws sts get-caller-identity | Who am I right now (which role, which session, which account)? |
aws iam get-role --role-name R --query Role.AssumeRolePolicyDocument | Who is allowed to assume the role in the trust policy? |
aws iam list-role-policies / get-role-policy / list-attached-role-policies | What permissions does the role have? |
aws iam simulate-principal-policy --policy-source-arn ROLE --action-names A --resource-arns R | Is 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=X | What exactly happened in this call (errorCode, errorMessage)? |
aws sts decode-authorization-message --encoded-message M | Which 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 15m | What did the container itself output? |
kubectl auth can-i --list -n myapp | What 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.
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).
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.
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.
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.
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
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
No verified video on IAM AccessDenied troubleshooting or CloudTrail queries was found.
Official documentation
- Troubleshoot access denied error messages
- Testing IAM policies with the IAM policy simulator
- Amazon ECS stopped task error messages
- Amazon ECS service event messages
- Troubleshoot problems with Amazon EKS clusters
Video storyboard script (about 60 seconds)
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.
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.
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.
Module 8 · Cost, cleanup and self-check
- 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.
What: billable items in this lesson
| Resource | Billing model | Usage in this lesson | Cost-saving tips |
|---|---|---|---|
| Fargate tasks | Per vCPU and memory × seconds running (Linux minimum 1 minute) | 2 services × 1 task × 0.25 vCPU / 0.5 GB; briefly doubles during deployment | When 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 address | Each public IPv4 is billed by the hour (including public IPs automatically assigned to tasks) | 1 per task | In production, use private subnets + ALB; delete after the lab is done |
| ECR | Storage is billed per GB-month; cross-region and internet transfer billed separately | Build 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 Logs | Ingestion billed per GB, storage per GB-month | Very little | Set a retention period (7 days in this lesson) |
| EKS (optional) | Control plane $0.10/hour (standard support) + node / Auto Mode management fees | Only if doing Lab 5B | Delete the cluster when done, or at least delete the access entries |
| Lambda | Requests + GB-seconds (free tier available) | Dozens of invocations | Nearly zero |
| ALB / NAT gateway | Per hour + usage | Not used in this lesson | These two items are the usual big-ticket costs in lab bills |
| Azure Pipelines | Microsoft-hosted free tier (once enabled) or paid parallel jobs; 1 free self-hosted | About 5–15 minutes per run | Waiting 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)
- Azure DevOps: first disable or delete the pipelines (so that no deployment is triggered during cleanup).
- ECS services:
delete-service --force(this stops tasks), then waitservices-inactive. - Task definitions: deregister all revisions, then
delete-task-definitions; delete the cluster. - ECR repositories (
--forceincluding images), log groups, Lambda functions and aliases. - EKS access entries (if any).
- IAM: delete inline policies / detach managed policies → delete roles; finally delete the OIDC provider.
- Security groups (can be deleted only after the dependent ENIs are released).
- Azure DevOps: delete service connections and Environments; optionally uninstall the extension.
Resource dependencies and cleanup order
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.
Cost and cleanup commands
| Command | Purpose |
|---|---|
aws budgets create-budget | Create 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-inactive | Delete the service and stop its tasks |
aws ecs deregister-task-definition / delete-task-definitions | Deregister and delete task definition revisions |
aws ecr delete-repository --force | Delete the repository and its images |
aws resourcegroupstaggingapi get-resources --tag-filters Key=project,Values=ado-lab | List 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)
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.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
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.
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
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
Official documentation
- AWS Fargate pricing
- Amazon VPC pricing (public IPv4, NAT gateway)
- Amazon EKS pricing
- Creating a budget
- Azure Pipelines: Configure and pay for parallel jobs
Video storyboard script (about 45 seconds)
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.
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.
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.
Command cheat sheet
1. Service connections and credentials
| Purpose | Command / configuration |
|---|---|
| OIDC provider | aws iam create-open-id-connect-provider --url https://vstoken.dev.azure.com/<org GUID> --client-id-list api://AzureADTokenExchange |
| Trust policy condition | vstoken.dev.azure.com/<GUID>:aud = api://AzureADTokenExchange; …:sub = sc://<org>/<project>/<service connection>; action sts:AssumeRoleWithWebIdentity |
| Service connection | Type AWS; Role to Assume = role ARN; check Use OIDC; leave keys blank; Role Session Name recommended as ado-<app>-<env> |
| Credential duration | variable aws.rolecredential.maxduration: 900–43200, ≤ role MaxSessionDuration (default 3600) |
| Who is calling | aws sts get-caller-identity (OIDC success: assumed-role/role name/session name, the key starts with ASIA) |
| Script approach | POST ${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
| Purpose | How to write it |
|---|---|
| Toolkit script task | task: AWSShellScript@1 + awsCredentials,regionName,scriptType: filePath,disableAutoCwd: true,workingDirectory |
| Cross-stage output variable | step name: img + isOutput=true; downstream job $[ stageDependencies.Build.Push.outputs['img.IMAGE_URI'] ]; downstream stage dependsOn must include Build |
| deployment job | deployment: X + environment: myapp-aws-prod + strategy.runOnce.deploy.steps; remember - checkout: self |
| deploy to prod only on main | condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main')) |
| ECR push task | ECRPushImage@1: always set pushTag (default latest) |
6. Least-privilege snippet (pipeline role)
| Capability | Actions | Resource |
|---|---|---|
| ECR login | ecr:GetAuthorizationToken | * |
| Push | ecr:BatchCheckLayerAvailability,InitiateLayerUpload,UploadLayerPart,CompleteLayerUpload,PutImage | repository ARN |
| ECS deployment | ecs:RegisterTaskDefinition,DescribeTaskDefinition (*); ecs:UpdateService,DescribeServices | service ARN |
| Pass role | iam:PassRole + condition iam:PassedToService=ecs-tasks.amazonaws.com | execution role / task role ARN |
| EKS | eks:DescribeCluster + access entries + namespace-scoped access policy | cluster ARN |
| Lambda | lambda:UpdateFunctionCode,PublishVersion,GetAlias,UpdateAlias | function ARN and function ARN:* |
7. One-line troubleshooting
| Error keyword | Check first |
|---|---|
System.AccessToken is undefined | Classic pipelines: tick Allow scripts to access the OAuth token; scripts need env mapping |
No OpenIDConnect provider found | Whether the provider URL and issuer match exactly, and whether it is the same account |
Not authorized to perform sts:AssumeRoleWithWebIdentity | Trust policy sub/aud (renamed? case?) |
DurationSeconds exceeds the MaxSessionDuration | maxduration variable vs role setting |
not authorized to perform: iam:PassRole | PassRole resource and condition |
no basic auth credentials / token has expired | Re-login to ECR; hostname matches |
ResourceInitializationError … connection issue … ECR | assignPublicIp / NAT / VPC endpoints |
deployment failed: tasks failed to start | stoppedReason of stopped tasks |
Unauthorized (kubectl) | Access entry (role ARN) |
Forbidden (kubectl) | Access policy scope / RBAC |
Capstone lab + final quiz
- 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-deployandado-myapp-prod-deploytwo 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.
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).
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.
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.
- 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-stableFinal 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.
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.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-ado-aws.sh → delete service connections and Environments → confirm nothing is left using the tag API and an IAM listing.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
| Topic | Verified conclusion | Source (read 2026-11-15) |
|---|---|---|
| AWS Toolkit for Azure DevOps versions | Latest 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 executors | Releases · CHANGELOG |
| Toolkit OIDC configuration | Service 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 OIDC | README · example_cfn.yaml |
| Toolkit credential implementation | awsConnectionParameters.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 inputs | ECRPushImage: 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 management | src/tasks/*/task.json · AWS Shell Script task |
| Toolkit credential sources | service connection (keys, role assumption, session token); variables AWS.AccessKeyID/SecretAccessKey/SessionToken/Region; standard environment variables (including AWS_ROLE_ARN); EC2 instance metadata | Toolkit User Guide: Getting started |
| AWS official blog | read 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@1 | How to federate into AWS from Azure DevOps using OpenID Connect (2024-12-17) |
| Azure DevOps OIDC token API | POST …/_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 provider | URL 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 it | Create an OIDC identity provider |
| App Runner / Express Mode | App 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 charge | App Runner availability change · Express Mode overview(consistent with Lesson 4 of the Docker course) |
| ECS deployment | minimumHealthyPercent 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 versionConsistency | Deploy ECS services by replacing tasks |
| ECS circuit breaker | two-phase detection; BOUNDED_PERCENT defaults to 50, limited to 3–200; rolls back to the most recent COMPLETED deployment; ECS deployment controller only | Deployment circuit breaker(consistent with Lesson 4 of the Docker course) |
| ECR | authentication token 12 hours, username AWS; IMMUTABLE rejects overwriting tags | Registry authentication · Tag mutability |
| EKS | access 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 |
| Lambda | versions are immutable; alias weighted routing (primary version + one additional version); wait published-version-active exists in the AWS CLI v2 reference | Aliases · published-version-active |
| Azure Pipelines parallel jobs | the 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 2027 | Configure and pay for parallel jobs(page updated 2026-11-03) |
| Helm | Helm 4.3.2; --atomic → --rollback-on-failure; installation script get-helm-4 | same 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.OidcRequestUriand 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-servicesoutput. - 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.