GitLab Hour 4: Moving to the Cloud (AWS)
id_tokens a short-lived JWT, exchange it with AWS STS for temporary credentials, push myapp to ECR, then deploy to ECS on Fargate, EKS, and Lambda, and complete multi-account promotion, troubleshooting, and cleanup- Based on “how much the team is willing to operate,” choose among ECS on Fargate / ECS Express Mode / EKS / Lambda these, and explain which AWS APIs a GitLab job must call for each landing point.
- Build hands-on OIDC federation from GitLab.com to IAM: the IAM OIDC identity provider
https://gitlab.com, the job’sid_tokens: GITLAB_OIDC_TOKEN: aud: sts.amazonaws.com, and the trust policy’sgitlab.com:aud,gitlab.com:sub,gitlab.com:project_idconditions. - Write working
aws sts assume-role-with-web-identitysnippets (variablesAWS_ROLE_ARN), and also use the AWS SDK’s nativeAWS_WEB_IDENTITY_TOKEN_FILEway, and understand the separate lifetimes of the ID token and the STS session. - Build myapp on a GitLab-hosted runner with Docker-in-Docker and push it to an immutable-tag ECR repository
myapp, referencing it by digest digest, deployed to ECS Fargate, and make the pipeline turn red honestly on failure. - Use GitLab agent for Kubernetes or EKS access entries , two ways to deploy to EKS; use Lambda versions and aliases for progressive rollouts.
- Design dev / prod multi-account promotion: environment-scoped variables, protected tags, protected environments, and deployment approvals (Premium), and independently troubleshoot errors such as
Not authorized to perform sts:AssumeRoleWithWebIdentity,Incorrect token audience,No OpenIDConnect provider foundand similar typical errors.
1-hour time allocation table
| # | Time | Module | Core content | Animation / interaction | Lab (AWS account · ca-central-1) |
|---|---|---|---|---|---|
| 0 | Before class | Warm-up and AWS setup | AWS CLI v2, lab identity, budget alerts, getting the GitLab project ID and group ID | OIDC prerequisite self-check | aws sts get-caller-identity,glab api projects/:id |
| 1 | 00–05 | AWS deployment architecture selection | ECS Fargate / Express Mode / EKS / Lambda; current App Runner status; CI role ≠ runtime role | Decision tool | clusters, log groups, execution roles |
| 2 | 05–13 | OIDC federation: GitLab → IAM | OIDC providers,id_tokens and aud,gitlab.com:sub formats, ID-type condition keys, two ways to exchange for credentials | Core animation: id_token → STS token exchange (including failure scenarios) | Create the provider and role; the job prints claims and identity |
| 3 | 13–21 | Build and push to ECR | DinD,get-login-password, IMMUTABLE, scan on push, digest, lifecycle policies | Tag vs digest push simulation | CI push sha- tag |
| 4 | 21–29 | Deploy to ECS on Fargate | Register task definition, update service,wait services-stable, circuit-breaker rollback, Verify step,environment and resource_group | rolling deployment + circuit-breaker state machine | Pipeline deploys myapp-dev |
| 5 | 29–37 | Deploy to EKS and Lambda | GitLab agent (ci_access, kubecontext) vs EKS access entries; Lambda version and alias weighting | Lambda alias traffic shifting | (optional) Lambda alias 10% canary |
| 6 | 37–45 | Multi-account and environment promotion | one provider per account, one role per environment, environment scope AWS_ROLE_ARN, protected tags + ref_protected, deployment approvals | Trust matrix evaluator | Prod role trusts only protected tags |
| 7 | 45–54 | Troubleshooting cloud deployments in practice | Four-layer model: token → STS trust → IAM permissions → service behavior; CloudTrail | Diagnostic challenges + interactive troubleshooting tree | Intentionally cause aud / sub errors and fix them |
| 8 | 54–60 | Cost, cleanup and self-check | Cost breakdown, cleanup order, reclaiming roles / providers / variables / agent tokens | Cost estimator | One-click cleanup script |
| — | After class | Cheat sheet · Capstone lab | id_tokens → STS → ECR (immutable) → ECS (dev automatic / prod tag + manual) → rollback → cleanup | Final quiz (12 questions) | Capstone lab |
Knowledge Coverage Matrix
| Target skills | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands / keywords | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Choosing AWS compute services by scenario | ✓ | · | · | ✓ | ✓ | · | · | ✓ | Decision table | M1 |
| Keyless: id_tokens → STS temporary credentials | · | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | · | id_tokens,aws sts assume-role-with-web-identity | M2 |
| write a minimal working trust policy (aud / sub / project_id) | · | ✓ | · | · | · | ✓ | ✓ | · | aws iam create-role | M2 / M6 |
| push immutable images and reference them by digest | · | · | ✓ | ✓ | ✓ | ✓ | ✓ | · | aws ecr get-login-password,docker push | M3 |
| ECS deployment, waiting for stability, circuit-breaker rollback | · | · | · | ✓ | · | ✓ | ✓ | · | aws ecs update-service,aws ecs wait services-stable | M4 / capstone |
| EKS: GitLab agent or access entries | · | · | · | · | ✓ | · | ✓ | · | ci_access,aws eks create-access-entry | M5 (reading) |
| Lambda versions / progressive alias rollout | ✓ | · | · | · | ✓ | · | · | · | aws lambda update-alias --routing-config | M5 (optional) |
| multi-account, environments and promotion | · | ✓ | · | ✓ | · | ✓ | · | · | environment:, environment-scoped variables, protected tags | Capstone |
| Locating cloud deployment faults | · | ✓ | ✓ | ✓ | ✓ | · | ✓ | · | CloudTrail,describe-services | M7 |
| cost control and complete cleanup | · | · | ✓ | · | · | · | · | ✓ | aws ecs delete-service --force | M8 |
Topics not covered in this hour (and where to learn them)
| Topic | Why it is not in this hour | Where to learn it |
|---|---|---|
| Dockerfile, multi-stage builds, ECS task definition fields and ALB details | Containers are already covered in depth in the Docker course; this hour only covers how GitLab drives them | Docker lesson 4 (AWS ECS / ECR / EKS) |
| EKS cluster creation, VPC CNI, Pod Identity | Belongs to Kubernetes platform operations | K8s lesson 7 (EKS) |
| Manage OIDC providers, roles and ECS resources with Terraform | This hour uses the CLI so every step is “visible”; production should use IaC instead | Terraform lesson 4 (AWS) |
Pipeline syntax basics (rules,needs,extends, variables) | Covered in lesson 2 | Lesson 2 |
| Azure federated credentials (Entra workload identity) | Covered in the previous lesson; this hour maps to it one-to-one | Lesson 3 (Azure) |
| How the same topic is written in GitHub Actions / Azure Pipelines | This hour covers GitLab only; compare the others as needed | GitHub lesson 4 (AWS) · Azure DevOps lesson 4 |
| CI/CD components, security scanning, supply chain hardening | Belongs to the “production-grade GitLab CI” topic | Lesson 5 |
How to use this course material
Theory · diagrams · animations · commands · labs · production cases · troubleshooting · quizzes · audio · video. Read “Theory” and “Animation” first, then do the “Lab”. The token exchange animation in module 2 is the core of the whole course.
A quiz score ≥ 70% or clicking “Mark module complete” counts toward progress. Progress is saved in this browser (it is cleared on refresh if local storage is disabled).
The “Audio” page uses the browser’s Web Speech API (en-US) to read the script aloud; if no Chinese voice pack is installed, the script can still be read.
id_tokens available since 15.7, the old CI_JOB_JWT / CI_JOB_JWT_V2 has already been removed in GitLab 17.0. The ID token sub default format project_path:{group}/{project}:ref_type:{type}:ref:{branch_name}, which can be customized through the project API’s ci_id_token_sub_claim_components setting. On the AWS side, IAM provides extra condition keys for GitLab.com gitlab.com:project_id,gitlab.com:namespace_id etc. (GitLab.com only; self-managed / Dedicated support only sub and aud). Example images: docker:29 + docker:29-dind,amazon/aws-cli:2.40.4,alpine/k8s:1.37.2 (Kubernetes stable v1.37.2), Helm v4.3.2. In production, pin images by digest.Module 0 · Warm-up and AWS setup (complete before class)
- Completedlesson 2(pipelines, jobs,
rules,extends, CI/CD variables, hosted runners) andlesson 3(id_tokensthe matching Azure flow). - A project exists on GitLab.com
mygroup-lab/myapp(the Flask + gunicorn app from the Docker course, listening on 5000, serving/healthz, with the Dockerfile in the repository root and the default branchmain)./healthzThe app does not depend on Redis, and this hour does not deploy it, so seeinghits=N/Aon the page is normal. - A lab-only AWS account (strongly recommended: do not use your company’s production account), plus an administrative identity with IAM, ECR, ECS, EC2 (security groups), and CloudWatch Logs permissions (an IAM Identity Center user or an admin role).
- Locally: AWS CLI v2, a signed-in
glab(glab auth status),jq, Git, Docker (for local debugging only; CI builds run on GitLab hosted runners).
Connection to the previous lesson
| Lesson 3 (Azure) | This hour (AWS) | Notes |
|---|---|---|
| Entra app registration / user-assigned managed identity | IAM role | cloud identity that a GitLab job “assumes” |
| Federated credential (issuer + subject + audience) | IAM OIDC identity provider + role trust policy conditions | AWS splits “who to trust” into two layers: an account-level provider + role-level conditions |
az login --federated-token "$GITLAB_OIDC_TOKEN" | aws sts assume-role-with-web-identity --web-identity-token "$GITLAB_OIDC_TOKEN" | The same id_tokens keyword, the same variable name GITLAB_OIDC_TOKEN |
aud api://AzureADTokenExchange | aud sts.amazonaws.com (this hour’s convention) | aud goes in id_tokens , and it must match the audience registered in the cloud |
AZURE_CLIENT_ID / AZURE_TENANT_ID / AZURE_SUBSCRIPTION_ID | AWS_ROLE_ARN (+ AWS_DEFAULT_REGION) | are not secrets, so CI/CD variables are fine for them |
| ACR / Container Apps / AKS | ECR / ECS Fargate / EKS | Image registry / managed containers / Kubernetes |
Step 1: confirm your AWS identity and region
aws --version export AWS_REGION=ca-central-1 aws configure set region $AWS_REGION # or set it in your SSO profile aws sts get-caller-identity export ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
aws-cli/2.x.x Python/3.x Linux/6.x
{
"UserId": "AROAEXAMPLEID:you@example.com",
"Account": "111122223333",
"Arn": "arn:aws:sts::111122223333:assumed-role/AWSReservedSSO_AdministratorAccess_abc123/you@example.com"
}
All example account numbers in this hour are 111122223333 (placeholder values commonly used in AWS docs); replace them with your own $ACCOUNT_ID. Do not create an IAM user with long-term access keys for the lab, and certainly do not store them in GitLab CI/CD variables; that is exactly the practice this hour aims to retire.
Step 2: set a budget alert (1 minute, strongly recommended)
cat > budget.json <<'EOF'
{ "BudgetName": "gitlab-lab-10usd", "BudgetLimit": {"Amount": "10", "Unit": "USD"},
"TimeUnit": "MONTHLY", "BudgetType": "COST" }
EOF
cat > notify.json <<'EOF'
[{ "Notification": {"NotificationType":"ACTUAL","ComparisonOperator":"GREATER_THAN","Threshold":50,"ThresholdType":"PERCENTAGE"},
"Subscribers": [{"SubscriptionType":"EMAIL","Address":"you@example.com"}] }]
EOF
aws budgets create-budget --account-id $ACCOUNT_ID --budget file://budget.json \
--notifications-with-subscribers file://notify.json
Send an email when actual spend exceeds USD 5 (50% of USD 10). Plain budgets that only send notifications are not charged separately; for budgets with automated actions, see the AWS Budgets pricing page.
Step 3: get your GitLab project ID and group ID (needed in module 2)
GitLab.com ID tokens include both the path (project_path, which changes on rename or transfer), and the numeric ID (project_id,namespace_id, never reused). The AWS and GitLab docs both warn that deleted group or project paths can be re-registered by someone else, so the trust policy should, in addition to the sub path, also pin the numeric ID.
export GL_PROJECT=mygroup-lab/myapp # replace with your <username>-lab/myapp
glab api "projects/$(printf %s "$GL_PROJECT" | jq -sRr @uri)" \
| jq '{path_with_namespace, project_id: .id, namespace_id: .namespace.id, default_branch, visibility}'
{
"path_with_namespace": "mygroup-lab/myapp",
"project_id": 12345678,
"namespace_id": 87654321,
"default_branch": "main",
"visibility": "private"
}
project_path:mygroup-lab/myapp:ref_type:branch:ref:main (branch) or project_path:mygroup-lab/myapp:ref_type:tag:ref:v1.1 (tag). There is no environment-style sub. This differs from GitHub, where environment constraints are handled by other mechanisms (module 6). If the project has been customized through the API ci_id_token_sub_claim_components, the format will differ. The most reliable approach is to, in the module 2 lab,have the job print the actual claims (print only the payload, never the token itself) before writing the trust policy.Warm-up: answer from memory (30 seconds)
Why is “storing AWS_ACCESS_KEY_ID as a masked GitLab variable” no longer the recommended approach?
Long-term keys do not expire automatically. Once they leak through job logs, a tampered script, a merge request pipeline from a fork, or a departing employee, they stay valid until someone rotates them manually. OIDC gives each job temporary credentials (1 hour by default) that are constrained by a trust policy, and only jobs that meet the conditions (project ID, branch or tag, protected status) can obtain them.
How does a GitLab job get an OIDC token?
Declare an id_tokens in the job, for example id_tokens: { GITLAB_OIDC_TOKEN: { aud: sts.amazonaws.com } }. GitLab issues tokens only to jobs that declare the id_tokens key, and places each token in a CI/CD variable of the same name. The old predefined variable CI_JOB_JWT_V2 was removed in 17.0.
Is the subject of the lesson 3 Azure federated credential and the gitlab.com:sub in the AWS trust policy the same thing?
Yes, both come from the same GitLab ID token’s sub claim. Azure federated credentials require an exact match (or a flexible federated credential expression), while the AWS trust policy can use StringEquals exact matching, and can also use StringLike wildcards. For GitLab.com, AWS additionally provides project_id,namespace_id and other condition keys.
Module 1 · AWS deployment architecture selection
- Explain the operational boundaries and billing models of ECS on Fargate, ECS Express Mode, EKS, and Lambda, and the matching CLI calls in a GitLab job.
- Know the current status of App Runner: no longer accepting new customers (existing customers can keep using it, but no new features are added), and AWS officially recommends migrating to ECS Express Mode.
- Understand that “wherever you deploy, the GitLab → AWS identity chain is the same”:
id_tokens→ STS → temporary credentials → service API, and distinguish CI role from the runtime role.
What: four main landing points
| ECS on Fargate | ECS Express Mode | EKS | Lambda | |
|---|---|---|---|---|
| What you deliver | Image + task definition JSON + service config | Image + two IAM roles (one API call) | Image + Kubernetes manifests / Helm chart | Zip package or container image + function configuration |
| What AWS manages for you | Servers, scheduling, rolling deployments | On top of ECS, automatically creates an ALB (with TLS), auto scaling, networking, and logging | Control plane (Auto Mode also manages nodes) | All servers and scaling; billed per request |
| How to deploy from a GitLab job | aws ecs register-task-definition + update-service + wait services-stable | aws ecs create-express-gateway-service / update the service with the same name | kubecontext injected by the GitLab agent, or aws eks update-kubeconfig + kubectl/helm | aws lambda update-function-code --publish + update-alias |
| Core permissions the CI role needs | ecs:RegisterTaskDefinition,ecs:UpdateService,ecs:DescribeServices,iam:PassRole | Create/update Express services + iam:PassRole | With the agent: No AWS permissions needed; with access entries: eks:DescribeCluster + access entries | lambda:UpdateFunctionCode,PublishVersion,UpdateAlias |
| Typical starting cost | Billed per task vCPU / memory-second | Express Mode itself is free; you pay only for the underlying resources (Fargate, ALB, etc.) | Cluster hourly fee + nodes / Fargate | Requests + GB-seconds, with a free tier |
Why: why the choice affects .gitlab-ci.yml
At its core, a deployment job is “which set of AWS APIs to call with temporary credentials”. ECS is RegisterTaskDefinition → UpdateService → DescribeServices polling; EKS can bypass AWS APIs entirely, using the in-cluster GitLab agent agent that proxies Kubernetes API requests through the KAS tunnel, so the job only needs to switch kubecontext; Lambda is UpdateFunctionCode → PublishVersion → UpdateAlias. The choice determines the CI role’s permission policy, the rollback approach, and where to start troubleshooting.
One clear difference from GitHub: GitLab has no“official AWS deploy Action” layer, so most teams call the AWS CLI directly in the job’s script script. The benefit is that every step is transparent; the cost is that you must write the “wait for stability” and “verify PRIMARY revision” logic yourself (module 4 covers it).
How: current status of App Runner (verified)
The AWS official doc “AWS App Runner availability change” states that App Runner is no longer open to new customers; existing customers can keep using it, AWS keeps investing in security and availability, but no new features are planned. AWS recommends migrating to Amazon ECS Express Mode: you provide one image and two IAM roles (task execution role ecsTaskExecutionRole and infrastructure role ecsInfrastructureRoleForExpressServices), and ECS creates the Fargate service, ALB, auto scaling, and networking in your account. Express Mode itself carries no extra charge.
When: how to choose
- A web/API service, and the team does not want to touch Kubernetes: start with ECS Express Mode; when you need fine-grained control, switch to a “regular” ECS service. Express Mode creates ordinary ECS/ELB resources that you can take over directly.
- Need precise control over each release (circuit breaker, deployment configuration, multiple containers): ECS on Fargate + CLI (this hour’s main path).
- Already have a Kubernetes platform or need the CRD ecosystem: EKS + GitLab agent (the cluster is maintained by the platform team; application projects are only authorized for an agent’s context and namespace).
- Event-driven, intermittent traffic, single execution ≤ 15 minutes: Lambda (images up to 10 GB).
CI role ≠ runtime role
| Role | Who assumes it | Purpose | Name in this hour |
|---|---|---|---|
| CI deploy role | GitLab job (via OIDC) | Push images, register task definitions, update services | gitlab-myapp-dev-deploy |
| Task execution role | ECS agent | Pull ECR images, write CloudWatch logs | myappTaskExecutionRole |
| Task role / Pod Identity / Lambda execution role | Your application code | App accesses S3, DynamoDB, etc. | (not needed in this hour) |
eks:DescribeCluster; whether you can kubectl apply depends on EKS access entries, or you can simply hand it to the GitLab agent. ② “App Runner has been shut down”: it has not been shut down; it just no longer accepts new customers. ③ “Express Mode is a different compute service”: it is just a faster way to create and manage ECS, and the underlying service is still Fargate. ④ “A broad CI role saves effort”: an overly broad CI role hands AWS administrator access to anyone who can change .gitlab-ci.yml .Comparison with GitHub / Azure DevOps
| Step | GitLab (this hour) | GitHub Actions | Azure Pipelines |
|---|---|---|---|
| Request OIDC token | id_tokens: + aud | permissions: id-token: write | Service connection (workload identity federation) |
| Exchange for AWS credentials | aws sts assume-role-with-web-identity | configure-aws-credentials Action | AWS Toolkit task / service connection |
| See | this hour | GitHub lesson 4 | Azure DevOps lesson 4 |
Architecture diagram: one identity chain, four landing points
Decision flow
Interactive: deployment target selector
Answer 4 questions to see the recommended deployment target, the key commands in a GitLab job, and the core permissions of the CI role. Each step shows the reasoning behind the decision.
Core commands: survey the “foundation” of your account
| Command | Purpose | Notes |
|---|---|---|
aws ec2 describe-vpcs --filters Name=is-default,Values=true | Find the default VPC | This hour’s labs use the public subnets of the default VPC, which avoids NAT gateway costs |
aws ecs create-cluster --cluster-name myapp-lab | Create an ECS cluster | The cluster itself is free; the first use automatically creates the ECS service-linked role |
aws service-quotas get-service-quota --service-code fargate --quota-code L-3032A538 | Check the Fargate On-Demand vCPU quota | New accounts may have a low quota |
aws apprunner list-services | Check whether this is an existing App Runner customer | New accounts are refused when creating services (see the official notice) |
aws ecs create-express-gateway-service … | Express Mode creates the full stack in one step | Requires the execution role and infrastructure role ARNs |
export AWS_REGION=ca-central-1 VPC_ID=$(aws ec2 describe-vpcs --filters Name=is-default,Values=true --query 'Vpcs[0].VpcId' --output text) SUBNETS=$(aws ec2 describe-subnets --filters Name=vpc-id,Values=$VPC_ID Name=default-for-az,Values=true \ --query 'Subnets[].SubnetId' --output text | tr '\t' ',') echo "VPC=$VPC_ID SUBNETS=$SUBNETS" aws ecs create-cluster --cluster-name myapp-lab --tags key=course,value=gitlab-part4 \ --query 'cluster.[clusterName,status]' --output text
VPC=vpc-0a1b2c3d SUBNETS=subnet-0aaa,subnet-0bbb,subnet-0ccc myapp-lab ACTIVE
Express Mode in GitLab (for reference)
deploy-express:
extends: .aws-oidc # reusable template defined in module 2
stage: deploy
script:
- aws ecs create-express-gateway-service
--service-name myapp-express
--primary-container "{\"image\":\"$IMAGE_URI\",\"containerPort\":5000}"
--execution-role-arn arn:aws:iam::111122223333:role/ecsTaskExecutionRole
--infrastructure-role-arn arn:aws:iam::111122223333:role/ecsInfrastructureRoleForExpressServices
--health-check-path /healthz
--scaling-target '{"minTaskCount":1,"maxTaskCount":3}'
Syntax adapted from the CLI example in the ECS Express Mode getting-started docs (--primary-container accepts JSON,--scaling-target sets the minimum/maximum task count; if you omit it, --cpu/--memory the default is 1 vCPU / 2 GB, which can be --cpu/--memory lowered (check the docs for allowed values). This is a newer API; the subcommand does not exist in older CLI versions. Common error: Forgetting that Express Mode creates an ALB (billed hourly) means charges keep running if you do not delete it after the lab.
Lab 1: prepare the ECS cluster and network (about 3 min)
aws ecs create-cluster --cluster-name myapp-lab --tags key=course,value=gitlab-part4 aws logs create-log-group --log-group-name /ecs/myapp aws logs put-retention-policy --log-group-name /ecs/myapp --retention-in-days 3
Log retention is 3 days, so lab logs do not take up storage long term.
MYIP=$(curl -s https://checkip.amazonaws.com) TASK_SG=$(aws ec2 create-security-group --group-name myapp-task-sg --description "myapp lab tasks" \ --vpc-id $VPC_ID --query GroupId --output text) aws ec2 authorize-security-group-ingress --group-id $TASK_SG --protocol tcp --port 5000 --cidr $MYIP/32 echo $TASK_SG
sg-0123456789abcdef0
To save money, this hour skips the ALB, and tasks get public IPs directly. This is only suitable for labs; production should use a private subnet + ALB (see Docker lesson 4).
cat > ecs-tasks-trust.json <<'EOF'
{ "Version": "2012-10-17",
"Statement": [{ "Effect": "Allow", "Principal": {"Service": "ecs-tasks.amazonaws.com"}, "Action": "sts:AssumeRole" }] }
EOF
aws iam create-role --role-name myappTaskExecutionRole --assume-role-policy-document file://ecs-tasks-trust.json
aws iam attach-role-policy --role-name myappTaskExecutionRole \
--policy-arn arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicycat > ~/gitlab-part4.env <<EOF export AWS_REGION=$AWS_REGION ACCOUNT_ID=$ACCOUNT_ID VPC_ID=$VPC_ID SUBNETS=$SUBNETS TASK_SG=$TASK_SG export GL_PROJECT=$GL_PROJECT PROJECT_ID=12345678 NAMESPACE_ID=87654321 CLUSTER=myapp-lab EOF source ~/gitlab-part4.env
Replace PROJECT_ID,NAMESPACE_ID with the real values found in pre-class step 3.
aws ecs describe-clusters --clusters myapp-lab --query 'clusters[0].status' returns "ACTIVE".Case 1: a new account cannot create an App Runner service
Problem: A team opened a new AWS account for a new business line by following an old blog post, planning to use App Runner; creating the service failed. Root cause: App Runner no longer accepts new customers. Fix: Switch to ECS Express Mode, and in the GitLab job replace it with aws ecs create-express-gateway-service; for App Runner services in older accounts, follow the official guide and migrate gradually using Route 53 weighted records. Lesson: Before choosing a service, read its “availability change” announcement.
Case 2: EKS just to run one API
Problem: A three-person team deployed a single Flask API to EKS; the monthly cluster and node costs far exceeded the value of the app, and they had to maintain the agent, access entries and a Helm chart. Fix: Moved to ECS on Fargate; the CI role’s permissions were reduced to a set of ECS APIs. Limit: The cost only makes sense if the company already has a shared EKS platform and GitLab agent, so that app teams need only namespace-level access.
Case 3: the CI role had AdministratorAccess attached
Problem: To “get it working first”, the deployment role had AdministratorAccess attached, and the trust policy only checked aud. An audit found that on GitLab.com, a job from any project could get administrator credentials just by knowing the role ARN. Fix: Add gitlab.com:sub and gitlab.com:project_id to the trust policy, and narrow the permission policy to the ECR repository myapp and the ECS service myapp-dev. Lesson: The OIDC provider only means “trust tokens issued by gitlab.com”; the real boundary is the role conditions.
Common errors and fixes
An error occurred (AccessDeniedException) when calling the CreateService operation (App Runner)
Cause: The account is not an existing App Runner customer, or the identity lacks App Runner permissions. Fix: For new projects, switch to ECS Express Mode.
Unable to assume the service linked role. Please verify that the ECS service linked role exists.
Cause: A new account using ECS for the first time has not yet created the service-linked role AWSServiceRoleForECS (it is usually created automatically, though occasionally with a delay).
aws iam get-role --role-name AWSServiceRoleForECS || aws iam create-service-linked-role --aws-service-name ecs.amazonaws.com
You've reached the limit on the number of vCPUs you can run concurrently
Cause: Insufficient Fargate On-Demand vCPU quota (common in new accounts). Fix: Check and request an increase with Service Quotas; in the lab, reduce desiredCount.
aws: error: argument operation: Invalid choice … create-express-gateway-service
Cause: The AWS CLI version in the job image is too old and does not recognize the new API. Fix: Use a newer amazon/aws-cli tag, and pin it by digest so the same pipeline does not behave differently on different dates.
1. List the default subnet IDs for each availability zone in the default VPC, joined by commas.
aws ec2 describe-subnets --filters Name=vpc-id,Values=$VPC_ID Name=default-for-az,Values=true \ --query 'Subnets[].SubnetId' --output text | tr '\t' ','
2. Confirm that the ECS service-linked role exists.
aws iam get-role --role-name AWSServiceRoleForECS --query Role.Arn --output text
Your company already has a shared EKS cluster with the GitLab agent installed, and your team has 3 HTTP services but no one understands AWS IAM. Which deployment approach would you prefer?
I prefer “EKS + GitLab agent”: the platform team only needs to authorize the application project in the agent configuration’s ci_access section; then the job kubectl config use-context …:agent can deploy,with no AWS credentials needed at all, so there is no need to create an IAM role for each project. Image pushes still need ECR permissions (the platform can provide a shared push role, or use the GitLab container registry plus cluster pull credentials). Without an existing platform, ECS Express Mode is the easier choice.
Verified teaching videos
Official docs
- AWS App Runner availability change
- Amazon ECS Express Mode
- GitLab Docs: Deploy to AWS from GitLab CI/CD
Video storyboard (about 60 seconds)
This course material cannot directly generate video or MP3 files; the storyboard and narration below can be fed to a video tool.
Scene: a GitLab job card with a fox icon emits a JWT token that flies to an STS shield; behind the shield, four lines branch out to ECR, ECS, EKS and Lambda.
Narration: wherever you deploy, a GitLab job does one thing: it exchanges its ID token for temporary credentials.
Scene: four cards flip to show their respective CLI calls; the EKS card also shows a tunnel running from the in-cluster agent back to GitLab.
Narration: ECS means registering a task definition and then updating the service; EKS can use access entries, or hand the work to the GitLab agent in the cluster; Lambda means updating code, publishing a version and switching the alias.
Scene: the App Runner card turns gray, and an arrow points to ECS Express Mode.
Narration: App Runner no longer accepts new customers; for new projects, choose ECS Express Mode.
Module 2 · OIDC federation: GitLab → IAM
- Create an IAM OIDC identity provider (URL
https://gitlab.com, audiencests.amazonaws.com), and explain why GitLab.com does not require a manually maintained thumbprint, and what a self-managed instance must meet. - Use
id_tokensto requestGITLAB_OIDC_TOKEN, so thataudmatches the audience list of the IAM provider and the trust policy’sgitlab.com:audcondition: all three must agree. - Write a minimal trust policy with
gitlab.com:sub(project_path:…:ref_type:…:ref:…) andgitlab.com:project_idconditions, and know which condition keys are available only on GitLab.com. - Exchange for credentials in two ways: explicitly
aws sts assume-role-with-web-identity+ export variables, or the SDK-nativeAWS_ROLE_ARN+AWS_WEB_IDENTITY_TOKEN_FILE.
id_tokens concepts; an IAM role = trust policy + permission policy. Importance:★★★★★ (all later modules in this hour depend on it)What: three things
| Object | Location | Purpose | Key value |
|---|---|---|---|
| IAM OIDC identity provider | One per AWS account (the same URL can only be created once within an account) | Tells STS: “JWTs signed by this issuer can be trusted by roles in this account” | URL https://gitlab.com; audience (client ID) sts.amazonaws.com; ARN arn:aws:iam::111122223333:oidc-provider/gitlab.com |
| IAM role + trust policy | One per project / environment (least privilege) | Specifies which tokens may assume this role | Principal.Federated = provider ARN; Action = sts:AssumeRoleWithWebIdentity; Condition checks aud, sub, project_id |
In the job, the id_tokens | .gitlab-ci.yml job-level keyword | makes GitLab issue a JWT for the job and place it in a same-named variable | GITLAB_OIDC_TOKEN: { aud: sts.amazonaws.com } |
Why: what it gains over storing an access key
- No long-term secret: no AWS keys are stored in GitLab; the exposure is limited to one job’s temporary credentials (1 hour by default).
- Fine-grained trust: the trust policy can be as precise as “project 12345678’s main branch” or “protected v* tags”; tokens from other projects or branches carry a different sub, so STS rejects them outright.
- Auditable: the CloudTrail
AssumeRoleWithWebIdentityevent records the token’s subject; the role session name is set togitlab-<project ID>-<pipeline ID>-<job ID>, so every AWS call can be traced back to a specific job.
How: seven steps of the token exchange
- The job declares
id_tokens, and GitLab issues a JWT (RS256) at job start, as the CI/CD variableGITLAB_OIDC_TOKENpassed to the Runner. No declaration, no token. - The token includes
iss=https://gitlab.com,aud=sts.amazonaws.com(the value you wrote inid_tokens),sub=project_path:mygroup-lab/myapp:ref_type:branch:ref:mainplusproject_id,namespace_id,ref_protected,environment,runner_environmentand other claims. - The script calls STS
AssumeRoleWithWebIdentity(this call itself needs no AWS credentials), passing the RoleArn (variableAWS_ROLE_ARN), the token, a session name, and a duration. - STS uses
issto find the account holding the role with an OIDC provider whose URL ishttps://gitlab.com, and fetcheshttps://gitlab.com/.well-known/openid-configurationand the JWKS to verify the signature and validity period. - STS checks
audwhether it is in the provider’s audience (client ID) list. - STS evaluates the trust policy conditions:
gitlab.com:aud,gitlab.com:sub, and GitLab.com-onlygitlab.com:project_id,gitlab.com:namespace_idand so on. - After passing, it returns temporary credentials (
ASIA…beginning with AccessKeyId, SecretAccessKey, SessionToken and Expiration). The script exports them as environment variables, and afterwardsawsthe CLI / SDK uses them automatically.
What should aud be? (verified)
GitLab docs state aud set by id_tokens ; if left unset, it defaults to the instance domain; “the audience should represent the service that verifies and accepts the token”. On the AWS side, the only requirements are that the token’s aud is in the provider’s audience list and matches the trust policy’s gitlab.com:aud condition. The GitLab docs examples use the instance URL (such as https://gitlab.example.com), but this hour uses sts.amazonaws.com throughout, which is more precise semantically and matches lesson 3’s convention of “one aud per cloud”. Both work; the key is that all three must match.
sub format (default)
| Trigger | sub example | Notes |
|---|---|---|
| Push to branch main | project_path:mygroup-lab/myapp:ref_type:branch:ref:main | for dev deployment |
| Push tag v1.1 | project_path:mygroup-lab/myapp:ref_type:tag:ref:v1.1 | for prod release (module 6) |
| Merge request pipeline (source branch feature/login) | project_path:mygroup-lab/myapp:ref_type:branch:ref:feature/login | ref is source branch; for an MR from a fork, project_path is the fork project |
If the project has customized ci_id_token_sub_claim_components = ["project_id","ref_type","ref"] | project_id:12345678:ref_type:branch:ref:main | via the project API; since GitLab 18.7, sub can also include ref_protected, and when the job specifies an environment it can include environment_protected and deployment_tier |
environment: production, the sub is still in branch/tag form. The environment name appears only in the environment claim, and it is not in the list of GitLab.com condition keys supported by AWS. So “only jobs in the production environment can assume the prod role” must be enforced through protected tags / branches + gitlab.com:ref_protected condition + GitLab protected environments combination (module 6).AWS-supported GitLab.com condition keys (verified)
| Condition key | From claim | Purpose |
|---|---|---|
gitlab.com:aud / gitlab.com:sub | Standard claim | Supported by all GitLab instances (self-managed uses <your hostname>:sub) |
gitlab.com:project_id | project_id | Recommended: unchanged on project rename or transfer, and IDs are never reused |
gitlab.com:namespace_id | namespace_id | Lock to group (organization-level trust) |
gitlab.com:ref_protected | ref_protected | Trust only jobs from protected branches / tags |
gitlab.com:user_id,:user_login,:user_email,:user_access_level | Triggering user | Restrict by person (use sparingly; people change) |
gitlab.com:pipeline_source,:runner_environment | Pipeline source, runner type | e.g. only allow gitlab-hosted runners, or exclude certain trigger sources |
GitLab and IAM docs both state that these additional condition keys are only for the GitLab.com multi-tenant SaaS; GitLab Self-Managed and Dedicated only support sub and aud.
Is a thumbprint still needed?
IAM docs state: AWS uses its trusted root CA library to verify the TLS certificate of the OIDC provider’s JWKS endpoint, and falls back to a thumbprint only in special cases, such as when the certificate is not issued by these CAs. gitlab.com Because GitLab.com uses a public CA,you do not need to compute and rotate the thumbprint manually, and the CLI’s --thumbprint-list can be omitted. For self-managed instances, the real prerequisite is that /.well-known/openid-configuration and jwks_uri are reachable over the public internet with a complete certificate chain. If they cannot be reached publicly, the alternative given in GitLab docs is to place the discovery document and JWKS in a public location (such as S3) and set a custom issuer URL, with a warning that a misconfigured bucket could lead to takeover of the linked cloud account.
Two lifetimes, do not confuse them
| ID token (GITLAB_OIDC_TOKEN) | STS temporary credentials | |
|---|---|---|
| Issued by | GitLab | AWS STS |
| Lifetime | Until the job timeout; if no timeout is set, 5 minutes (GitLab docs) | --duration-seconds, default 3600; cannot exceed the role’s MaxSessionDuration (1–12 hours) |
| After expiry, | it cannot get new credentials | reports ExpiredToken; with the AWS_WEB_IDENTITY_TOKEN_FILE method, the SDK automatically renews using the still-valid ID token |
StringLike project_path:mygroup-lab/* is enough”: anyone who creates a new project in the group and writes a job on any branch can get credentials. ③ “The role ARN is a secret”: an ARN is not a credential, so a normal CI/CD variable is fine (environment scoping can tell dev from prod). ④ “You can still use $CI_JOB_JWT_V2”: it was removed in GitLab 17.0 and must be replaced with id_tokens.Sequence diagram: Runner ↔ GitLab ↔ AWS STS ↔ AWS services
Trust policy anatomy
Core animation: id_token → STS AssumeRoleWithWebIdentity token exchange
Choose a scenario, then click “Next” or “Auto-play”. The highlighted box shows the current handler; the terminal below shows the job log and STS responses. Failure scenarios stop at the step where the real failure happens and show the original AWS CLI error.
Core commands and keywords
| Command / keyword | Purpose | Key parameters / notes |
|---|---|---|
aws iam create-open-id-connect-provider | Create the OIDC provider (once per account) | --url https://gitlab.com --client-id-list sts.amazonaws.com; --thumbprint-list can be omitted |
aws iam add-client-id-to-open-id-connect-provider | Add an audience to the provider | Used when changing aud |
aws iam create-role --assume-role-policy-document | Create the CI role | --max-session-duration 3600 (seconds, 1–12 hours) |
aws iam update-assume-role-policy | Modify the trust policy | Takes effect within seconds |
id_tokens: NAME: aud: | Job requests an ID token | One aud per token; it can be used in script,before_script,after_script . |
aws sts assume-role-with-web-identity | Exchange an ID token for temporary credentials | --role-arn --role-session-name --web-identity-token --duration-seconds |
AWS_ROLE_ARN + AWS_WEB_IDENTITY_TOKEN_FILE | SDK/CLI native web identity credential provider | Automatically calls AssumeRoleWithWebIdentity when both are present; optional AWS_ROLE_SESSION_NAME |
glab variable set AWS_ROLE_ARN | Write to project CI/CD variables | --scope dev Set environment scope (module 6) |
source ~/gitlab-part4.env
# 1) OIDC provider (skip if the account already has one)
aws iam list-open-id-connect-providers --query 'OpenIDConnectProviderList[].Arn' --output text | grep -q 'oidc-provider/gitlab.com' \
|| aws iam create-open-id-connect-provider \
--url https://gitlab.com \
--client-id-list sts.amazonaws.com \
--tags Key=course,Value=gitlab-part4
aws iam get-open-id-connect-provider \
--open-id-connect-provider-arn arn:aws:iam::$ACCOUNT_ID:oidc-provider/gitlab.com \
--query '{url:Url,aud:ClientIDList}'
{
"url": "gitlab.com",
"aud": ["sts.amazonaws.com"]
}
Reusable template .aws-oidc (Approach A: explicit exchange, as in the GitLab docs)
variables:
AWS_DEFAULT_REGION: ca-central-1
.aws-oidc:
image:
name: amazon/aws-cli:2.40.4
entrypoint: [""] # the official image’s entrypoint is aws, so it must be cleared
id_tokens:
GITLAB_OIDC_TOKEN:
aud: sts.amazonaws.com
before_script:
- >
aws_sts_output=$(aws sts assume-role-with-web-identity
--role-arn "${AWS_ROLE_ARN}"
--role-session-name "gitlab-${CI_PROJECT_ID}-${CI_PIPELINE_ID}-${CI_JOB_ID}"
--web-identity-token "${GITLAB_OIDC_TOKEN}"
--duration-seconds 3600
--query 'Credentials.[AccessKeyId,SecretAccessKey,SessionToken]'
--output text)
- export $(printf "AWS_ACCESS_KEY_ID=%s AWS_SECRET_ACCESS_KEY=%s AWS_SESSION_TOKEN=%s" $aws_sts_output)
- aws sts get-caller-identity
The GitLab docs deliberately put the STS call in its own step (assign first, then export), so when STS fails the job fails with the correct exit code instead of continuing with empty credentials. Session names may contain only letters, digits and +=,.@-, length 2–64.
Approach B: hand off to the AWS SDK’s web identity provider
.aws-oidc-file:
image:
name: amazon/aws-cli:2.40.4
entrypoint: [""]
id_tokens:
GITLAB_OIDC_TOKEN:
aud: sts.amazonaws.com
before_script:
- echo "$GITLAB_OIDC_TOKEN" > /tmp/web-identity-token
- export AWS_WEB_IDENTITY_TOKEN_FILE=/tmp/web-identity-token
- export AWS_ROLE_SESSION_NAME="gitlab-${CI_PROJECT_ID}-${CI_JOB_ID}"
- aws sts get-caller-identity # AWS_ROLE_ARN comes from the CI/CD variables
Comparison: A makes every step visible and suits teaching and troubleshooting. B has shorter code, and the SDK renews credentials automatically using the still-valid ID token when they near expiry, which suits long-running jobs (Terraform, long deployments). The variable names AWS_ROLE_ARN are exactly the standard names the SDK recognizes, which is why this hour uses them throughout. Common error: Writing the token file into the project directory, which then gets artifacts packaged and uploaded. Tokens stay valid until the job times out, so always write it to /tmp.
Lab 2: set up OIDC trust and have the job prove “who I am” (about 8 min)
.gitlab-ci.yml add the following (decodes only the payload; does not print the token itself):
stages: [whoami]
whoami-claims:
stage: whoami
image: alpine:3.22
id_tokens:
GITLAB_OIDC_TOKEN:
aud: sts.amazonaws.com
rules:
- if: $CI_PIPELINE_SOURCE == "web" || $CI_COMMIT_BRANCH == "main"
script:
- apk add --no-cache jq >/dev/null
- |
P=$(echo "$GITLAB_OIDC_TOKEN" | cut -d. -f2 | tr '_-' '/+')
while [ $(( ${#P} % 4 )) -ne 0 ]; do P="$P="; done
echo "$P" | base64 -d | jq '{iss, aud, sub, project_id, namespace_id, ref, ref_type, ref_protected, runner_environment, exp, iat}'
git add .gitlab-ci.yml && git commit -m "ci: print OIDC claims" && git push glab ci view # or glab ci trace whoami-claims
{
"iss": "https://gitlab.com",
"aud": "sts.amazonaws.com",
"sub": "project_path:mygroup-lab/myapp:ref_type:branch:ref:main",
"project_id": "12345678",
"namespace_id": "87654321",
"ref": "main",
"ref_type": "branch",
"ref_protected": "true",
"runner_environment": "gitlab-hosted",
"exp": 1794830400,
"iat": 1794826800
}
The base64url segments of a JWT are usually missing = padding; the while loop above fills it in. Do not echo $GITLAB_OIDC_TOKEN itself, because it can be used to exchange for credentials while valid. exp − iat Its expiry equals the job timeout (1 hour in this example).
SUB_DEV="project_path:mygroup-lab/myapp:ref_type:branch:ref:main" # ← replace with the sub from your log
cat > trust-dev.json <<EOF
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": { "Federated": "arn:aws:iam::$ACCOUNT_ID:oidc-provider/gitlab.com" },
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"gitlab.com:aud": "sts.amazonaws.com",
"gitlab.com:sub": "$SUB_DEV",
"gitlab.com:project_id": "$PROJECT_ID"
}
}
}]
}
EOF
aws iam create-role --role-name gitlab-myapp-dev-deploy \
--assume-role-policy-document file://trust-dev.json --max-session-duration 3600 \
--tags Key=course,Value=gitlab-part4 --query Role.Arn --output text
glab variable set AWS_ROLE_ARN --value "arn:aws:iam::$ACCOUNT_ID:role/gitlab-myapp-dev-deploy"
arn:aws:iam::111122223333:role/gitlab-myapp-dev-deploy ✓ Created variable AWS_ROLE_ARN for mygroup-lab/myapp with scope *.
.aws-oidc template to .gitlab-ci.yml, then add a job:
whoami-aws:
stage: whoami
extends: .aws-oidc
rules:
- if: $CI_COMMIT_BRANCH == "main"
script:
- aws sts get-caller-identity --query Arn --output text
{
"UserId": "AROAEXAMPLE:gitlab-12345678-2087654321-11223344556",
"Account": "111122223333",
"Arn": "arn:aws:sts::111122223333:assumed-role/gitlab-myapp-dev-deploy/gitlab-12345678-2087654321-11223344556"
}
arn:aws:sts::111122223333:assumed-role/gitlab-myapp-dev-deploy/gitlab-12345678-2087654321-11223344556
Job succeededfeature/oidc-test, change the whoami-aws rule to if: $CI_COMMIT_BRANCH and push. The job will fail, and the log shows An error occurred (AccessDenied) when calling the AssumeRoleWithWebIdentity operation: Not authorized to perform sts:AssumeRoleWithWebIdentity— because sub has become …:ref:feature/oidc-test. Delete the branch after verifying. This is the first troubleshooting case in module 7.AssumeRoleWithWebIdentity, you should see one success and one failure; the errorCode of the failure event is AccessDenied.Case 1: all deployments failed after upgrading from CI_JOB_JWT_V2 to GitLab 17
Problem: After a self-managed instance was upgraded to 17.0, all AWS deploy jobs reported aws: error: argument --web-identity-token: expected one argument. Root cause: The script still used the removed $CI_JOB_JWT_V2, so the variable was empty. Fix: Add id_tokens: GITLAB_OIDC_TOKEN: aud: … in the shared template and replace the variable name; keep aud in sync with the IAM provider audience. Prevention: Watch GitLab deprecation announcements, and centralize cloud login logic in one template or CI/CD component.
Case 2: after a project was deleted, its path was re-registered by someone else
Problem: An audit found that a production role’s condition only had gitlab.com:sub = project_path:acme/payments:…, but that project had long been deleted, and paths on GitLab.com can be re-registered. Fix: Add gitlab.com:project_id (or namespace_id) conditions to all roles, and delete roles that are no longer used. GitLab also refuses to issue tokens when it detects that a path in sub previously belonged to another project (reporting ID token issuance is disabled …), and suggests changing the sub component to project_id.
Case 3: long-running job credentials expired
Problem: A data migration job ran for 90 minutes; from minute 61 it reported ExpiredToken. Fix: Switch to approach B (AWS_WEB_IDENTITY_TOKEN_FILE), where the SDK renews automatically using the still-valid ID token; set the job timeout to 2 hours so the ID token’s exp extends accordingly. You can also raise the role’s MaxSessionDuration and pass --duration-seconds 7200.
Common errors and fixes
An error occurred (AccessDenied) when calling the AssumeRoleWithWebIdentity operation: Not authorized to perform sts:AssumeRoleWithWebIdentity
Cause: STS signature verification passed, but the trust policy conditions were not met. The most common cause is a sub mismatch (wrong branch or tag, project renamed or transferred, or the source branch of an MR pipeline); next come a wrong project_id, or a wildcard written as StringEquals in a condition, or a wrong role ARN.
aws iam get-role --role-name gitlab-myapp-dev-deploy --query Role.AssumeRolePolicyDocument # compare the sub and project_id printed by the whoami-claims job
Fix: Make the conditions exactly match the actual claims; when a wildcard is needed, use StringLike.
An error occurred (InvalidIdentityToken) when calling the AssumeRoleWithWebIdentity operation: Incorrect token audience
Cause:id_tokens aud is not in the OIDC provider’s audience list (for example, the job wrote aud: https://gitlab.com but the provider only registered sts.amazonaws.com). Fix: change the job’s aud, or aws iam add-client-id-to-open-id-connect-provider --client-id https://gitlab.com, and sync the trust policy’s gitlab.com:aud.
An error occurred (InvalidIdentityToken) when calling the AssumeRoleWithWebIdentity operation: No OpenIDConnect provider found in your account for https://gitlab.com
Cause: The account holding the role has no OIDC provider for this URL, the most common issue in multi-account setups. IAM requires the OIDC provider referenced by a trust policy to be in the same account as the role.
aws iam list-open-id-connect-providers
aws: error: argument --web-identity-token: expected one argument
Cause:$GITLAB_OIDC_TOKEN is empty: the job (or the template it extends) has no id_tokens, the variable name is misspelled, or it still uses the removed CI_JOB_JWT_V2. Fix: Declare id_tokens in the job, and confirm that the variable names match.
An error occurred (ValidationError) when calling the AssumeRoleWithWebIdentity operation: The requested DurationSeconds exceeds the MaxSessionDuration set for this role.
Fix: Reduce --duration-seconds, or aws iam update-role --role-name R --max-session-duration 7200.
An error occurred (InvalidIdentityToken) … Couldn't retrieve verification key from your identity provider
Cause: (self-managed instance) .well-known or jwks_uri is unreachable from the public internet, blocked by a firewall, or responds in more than 5 seconds. Fix: Open these two endpoints, or follow the GitLab docs to place the discovery document and JWKS in a public location and set a custom issuer URL.
1. Without changing the provider, let the dev role accept both the main branch and protected release/* branches.
cat > trust-dev2.json <<EOF
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Principal":{"Federated":"arn:aws:iam::$ACCOUNT_ID:oidc-provider/gitlab.com"},
"Action":"sts:AssumeRoleWithWebIdentity",
"Condition":{
"StringEquals":{"gitlab.com:aud":"sts.amazonaws.com","gitlab.com:project_id":"$PROJECT_ID","gitlab.com:ref_protected":"true"},
"StringLike":{"gitlab.com:sub":[
"project_path:mygroup-lab/myapp:ref_type:branch:ref:main",
"project_path:mygroup-lab/myapp:ref_type:branch:ref:release/*"]}}}]}
EOF
aws iam update-assume-role-policy --role-name gitlab-myapp-dev-deploy --policy-document file://trust-dev2.json2. In CloudTrail, look up the last 10 AssumeRoleWithWebIdentity events.
aws cloudtrail lookup-events --lookup-attributes AttributeKey=EventName,AttributeValue=AssumeRoleWithWebIdentity \ --max-results 10 --query 'Events[].[EventTime,Username]' --output table
A colleague suggests: “The trust policy only checks aud, and then in the .gitlab-ci.yml ’s rules rules, restrict the deploy job to run only on the main branch.” Please evaluate.
Not acceptable. .gitlab-ci.yml It can be changed on any branch by anyone with Developer permission, so rules is only a voluntary constraint; and when only aud is checked, on GitLab.com any project can get credentials just by knowing the role ARN. The constraint must be placed on the AWS side: gitlab.com:sub pin the project path and branch precisely, then add gitlab.com:project_id; production roles should further require gitlab.com:ref_protected = true, and pair them with GitLab protected branches / tags (who can push).
Verified teaching videos
Official docs
- GitLab Docs: Configure OpenID Connect in AWS to retrieve temporary credentials
- GitLab Docs: OpenID Connect (OIDC) Authentication Using ID Tokens (claims list)
- GitLab Docs: Connect to cloud services (sub customization)
- IAM: Create an OIDC identity provider
- IAM: Available keys for AWS OIDC federation (GitLab.com tab)
Video storyboard (about 90 seconds)
Screen: in the GitLab CI/CD variables list, a key “AWS_SECRET_ACCESS_KEY” is crossed out and replaced by an expiring ticket, GITLAB_OIDC_TOKEN.
Narration: no keys are stored. Each job gets a temporary ticket. GitLab issues the ticket, and it becomes invalid when the job ends.
Screen: the JWT expands into four lines, iss, aud, sub and project_id; project_path inside sub and ref:main blink.
Narration: sub and project_id matter most. sub shows which branch of which project the request comes from, and project_id ensures that even if the path is re-registered by someone else, they cannot impersonate the project.
Screen: the STS shield checks off in turn: issuer registered, signature valid, audience matched, trust conditions met.
Narration: STS first confirms that gitlab.com is registered in the account, then verifies the signature and audience, and finally checks each condition in the role's trust policy.
Screen: returns temporary credentials starting with ASIA, with a 1-hour countdown, then pushes the image and updates the service.
Narration: once it passes, you get one hour of temporary credentials, which are used for pushing the image and updating the service.
Module 3 · Build and push to ECR
- Create IMMUTABLE, an ECR repository that scans on push
myapp, and configure a lifecycle policy to control storage costs. - In the job, use
aws ecr get-login-password | docker loginto log in, using!referenceReuse the OIDC snippet from Module 2. - Write an idempotent build job: if the tag already exists, reuse its digest; use
artifacts:reports:dotenvto passIMAGE_URI=…@sha256:…to the deploy job. - Write the minimum ECR permissions for the CI role (
GetAuthorizationTokenonlyResource: "*").
services,artifacts. Importance:★★★★What: the four things involved in an ECR push
| Step | AWS API / Command | Description |
|---|---|---|
| Log in | ecr:GetAuthorizationToken → aws ecr get-login-password | Docker password validity 12 hours; the username is fixed as AWS; this API does not support resource-level permissions |
| Upload layers | BatchCheckLayerAvailability,InitiateLayerUpload,UploadLayerPart,CompleteLayerUpload | layers that already exist are skipped |
| Write manifest | PutImage | in an IMMUTABLE repository, rejected here if the tag already exists |
| Scan | basic scanning (on push) or enhanced scanning (Amazon Inspector) | Scan asynchronously completes; use aws ecr wait image-scan-complete wait for |
Why: immutable tags + digest
- Mutable tag (MUTABLE):
latestOverwritten every time, so you cannot tell which image ran yesterday, and a rollback cannot recover the original content. - Immutable tag (IMMUTABLE):
sha-3f2a9c1Once pushed, it always points to the same digest. The cost: re-running the pipeline and pushing the same tag again will fail, so the build job should first check whether the tag already exists. - Deploy by digest:
myapp@sha256:…The digest is a content hash. If the task definition uses the digest, scaling, restarting and rolling back all pull the same content, and it maps one-to-one to scan results.
How: how to build on GitLab hosted Runners
| Approach | Key points | This lesson |
|---|---|---|
| Docker-in-Docker | image: docker:29 + services: [docker:29-dind],DOCKER_TLS_CERTDIR: "/certs"; hosted Linux Runners run in privileged mode and support DinD | Uses |
| BuildKit rootless / Buildah | does not need privileges, suitable for self-managed Kubernetes Runners | Note |
| Kaniko | the upstream project is archived and no longer maintained; not recommended for new pipelines | Not recommended |
docker:29 The image is based on Alpine and has no AWS CLI, so you need apk add aws-cli; the Module 2 .aws-oidc template uses the amazon/aws-cli image; here we only borrow its before_script: !reference [.aws-oidc, before_script]. Note that it id_tokens is not carried over with !reference the build job must declare it itself (or move the id_tokens into a separate .oidc-token template, and then extends include it).
When: should you also push to the GitLab Container Registry?
This course's convention is to push the myapp image to registry.gitlab.com/mygroup-lab/myapp (using $CI_REGISTRY_USER / $CI_REGISTRY_PASSWORD, no extra credentials needed), which makes tracing and local debugging in GitLab easier; at runtime on AWS, the image is pulled only from ECR—same-region pulls are fast, IAM execution roles can authenticate them, and it does not depend on the availability of an external registry.
Resource: "*"; the push action is then scoped to the repository ARN. ② “Log in once and every job can push”—the login state is kept in the current job's container,not across jobs. ③ “You can read the scan results right after pushing”—scanning is asynchronous. ④ “Writing IMAGE_URI into variables makes it available to the next job”—values generated at runtime must be passed on using artifacts:reports:dotenv to pass them on.Data flow of the build job
Tags, digests and immutability
Interactive: mutable tag vs immutable tag vs deploy by digest
Click the four buttons in turn and watch how the ECR repository (left) and the tasks in the ECS service (right) change, as well as the job log output.
Core commands
| Command | Purpose | Notes |
|---|---|---|
aws ecr create-repository --image-tag-mutability IMMUTABLE --image-scanning-configuration scanOnPush=true | Create repository | Encrypted with AES256 by default; KMS can be used |
aws ecr get-login-password | docker login --username AWS --password-stdin REGISTRY | Log in | Password valid for 12 hours |
aws ecr describe-images --image-ids imageTag=TAG | Check whether a tag exists and get its digest | returns when not found ImageNotFoundException (non-zero exit) |
aws ecr wait image-scan-complete | Wait for scan to complete | then describe-image-scan-findings |
aws ecr put-lifecycle-policy | Automatically clean up old images | Control storage costs |
artifacts:reports:dotenv | Pass runtime variables to later jobs | Later jobs get it through needs/ stage order, automatically available |
aws ecr create-repository --repository-name myapp \
--image-tag-mutability IMMUTABLE \
--image-scanning-configuration scanOnPush=true \
--tags Key=course,Value=gitlab-part4 \
--query repository.repositoryUri --output text
cat > lifecycle.json <<'EOF'
{"rules":[
{"rulePriority":1,"description":"untagged 1 day","selection":{"tagStatus":"untagged","countType":"sinceImagePushed","countUnit":"days","countNumber":1},"action":{"type":"expire"}},
{"rulePriority":2,"description":"keep 20 sha- images","selection":{"tagStatus":"tagged","tagPrefixList":["sha-"],"countType":"imageCountMoreThan","countNumber":20},"action":{"type":"expire"}}
]}
EOF
aws ecr put-lifecycle-policy --repository-name myapp --lifecycle-policy-text file://lifecycle.json
111122223333.dkr.ecr.ca-central-1.amazonaws.com/myapp
Build job (complete)
stages: [build, deploy]
variables:
AWS_DEFAULT_REGION: ca-central-1
ECR_REGISTRY: 111122223333.dkr.ecr.ca-central-1.amazonaws.com
IMAGE_TAG: sha-$CI_COMMIT_SHORT_SHA
build-push:
stage: build
image: docker:29
services:
- docker:29-dind
variables:
DOCKER_TLS_CERTDIR: "/certs"
id_tokens:
GITLAB_OIDC_TOKEN:
aud: sts.amazonaws.com
rules:
- if: $CI_COMMIT_BRANCH == "main" || $CI_COMMIT_TAG
before_script:
- apk add --no-cache aws-cli >/dev/null
- !reference [.aws-oidc, before_script]
script:
- aws ecr get-login-password | docker login --username AWS --password-stdin "$ECR_REGISTRY"
- |
if DIGEST=$(aws ecr describe-images --repository-name myapp --image-ids imageTag=$IMAGE_TAG \
--query 'imageDetails[0].imageDigest' --output text 2>/dev/null); then
echo "tag $IMAGE_TAG already exists → reuse $DIGEST"
else
docker build --pull -t "$ECR_REGISTRY/myapp:$IMAGE_TAG" -t "$CI_REGISTRY_IMAGE:$IMAGE_TAG" .
docker push "$ECR_REGISTRY/myapp:$IMAGE_TAG"
echo "$CI_REGISTRY_PASSWORD" | docker login -u "$CI_REGISTRY_USER" --password-stdin "$CI_REGISTRY"
docker push "$CI_REGISTRY_IMAGE:$IMAGE_TAG"
DIGEST=$(aws ecr describe-images --repository-name myapp --image-ids imageTag=$IMAGE_TAG \
--query 'imageDetails[0].imageDigest' --output text)
fi
- echo "IMAGE_URI=$ECR_REGISTRY/myapp@$DIGEST" >> build.env
- cat build.env
artifacts:
reports:
dotenv: build.env
ECR_REGISTRY The account ID in it is also not a secret, so it can be written in YAML; with multiple accounts, switch to per-environment variables (Module 6). $CI_REGISTRY_IMAGE In this project it is registry.gitlab.com/mygroup-lab/myapp.
CI role ECR permissions (inline policy)
cat > ecr-push.json <<EOF
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"ecr:GetAuthorizationToken","Resource":"*"},
{"Effect":"Allow","Action":["ecr:BatchCheckLayerAvailability","ecr:InitiateLayerUpload","ecr:UploadLayerPart",
"ecr:CompleteLayerUpload","ecr:PutImage","ecr:BatchGetImage","ecr:DescribeImages","ecr:DescribeImageScanFindings"],
"Resource":"arn:aws:ecr:$AWS_REGION:$ACCOUNT_ID:repository/myapp"}]}
EOF
aws iam put-role-policy --role-name gitlab-myapp-dev-deploy --policy-name ecr-push --policy-document file://ecr-push.json
Lab 3: CI pushes sha- tags and reads scan results (about 7 minutes)
ecr-push.json part..gitlab-ci.yml keep the .aws-oidc template, delete the whoami-* job, add the build-push, then push to main.
git add .gitlab-ci.yml && git commit -m "ci: build and push to ECR" && git push glab ci trace build-push
Login Succeeded #12 pushing layers 2.1s done sha-3f2a9c1: digest: sha256:4d1c…e9a2 size: 1789 IMAGE_URI=111122223333.dkr.ecr.ca-central-1.amazonaws.com/myapp@sha256:4d1c…e9a2 Uploading artifacts... build.env: found 1 matching artifact files and directories Job succeeded
tag sha-3f2a9c1 already exists → reuse sha256:…, not a push failure.aws ecr wait image-scan-complete --repository-name myapp --image-id imageTag=sha-3f2a9c1 aws ecr describe-image-scan-findings --repository-name myapp --image-id imageTag=sha-3f2a9c1 \ --query 'imageScanFindings.findingSeverityCounts'
{
"MEDIUM": 3,
"LOW": 7
}aws ecr describe-images --repository-name myapp --query 'imageDetails[].imageTags' You should see sha- tag; the GitLab project's Deploy → Container Registry page also shows the same tag.Case 1: the “Retry” button fails the release pipeline
Problem: After switching to IMMUTABLE, when the on-call engineer re-runs a failed deploy job, the build job is re-run as well and fails with “tag already exists”, so the whole pipeline gets stuck. Fix: The build job first describe-images, and if the tag exists, reuse its digest (the approach used in this lesson); or split it into a job that builds only when the tag does not exist.
Case 2: ECR storage costs quietly grow
Problem: Every MR builds and pushes, so after a year the repository holds tens of thousands of images. Fix: Use a lifecycle policy to clean up untagged images and overly old sha- images. MR pipelines only build and do not push to ECR; they push to the GitLab Container Registry and use its cleanup policy instead.
Case 3: a base image vulnerability blocks a release
Problem: A scan on push finds a CRITICAL vulnerability, and the security team requires the release to be blocked. Fix: Add a scan-gate job after the build job: wait for the scan to complete, and if CRITICAL > 0, then exit 1; also enable enhanced scanning (Inspector) to continuously scan pushed images. More complete supply chain scanning is covered in Lesson 5.
Common errors and fixes
tag invalid: The image tag 'sha-3f2a9c1' already exists in the 'myapp' repository and cannot be overwritten because the repository is immutable.
Cause: Expected behavior: an immutable repository rejects overwrites. Fix: Before building, check whether the tag exists; if it does, reuse the digest.
denied: User: arn:aws:sts::111122223333:assumed-role/gitlab-myapp-dev-deploy/… is not authorized to perform: ecr:InitiateLayerUpload on resource: arn:aws:ecr:ca-central-1:111122223333:repository/myapp
Cause: The CI role lacks push permission, or the region or repository name in the resource ARN is wrong. Fix: Following the ecr-push.json part of the “Commands” tab to fill in what is missing.
name unknown: The repository with name 'myapp' does not exist in the registry with id '111122223333'
Cause: The repository does not exist, or the push went to the wrong region or account. Fix:aws ecr describe-repositories --region ca-central-1.
error during connect: … dial tcp: lookup docker on …: no such host / Cannot connect to the Docker daemon at tcp://docker:2375
Cause: Missing services: [docker:29-dind], or the TLS configuration does not match (the client uses 2375, but dind only listens on 2376). Fix: Use the DOCKER_TLS_CERTDIR: "/certs" approach from this lesson; self-managed Runners must enable privileged = true.
no basic auth credentials
Cause: The current job is not logged in to ECR (login state is not shared across jobs), or it logged in to a different registry address. Fix: In the same job that pushes or pulls, run get-login-password | docker login.
1. Query the digest and push time of the tag sha-3f2a9c1.
aws ecr describe-images --repository-name myapp --image-ids imageTag=sha-3f2a9c1 \ --query 'imageDetails[0].[imageDigest,imagePushedAt]' --output text
2. Write a job that fails when the scan finds a CRITICAL vulnerability.
scan-gate:
stage: build
extends: .aws-oidc
needs: [build-push]
script:
- DIGEST=${IMAGE_URI#*@}
- aws ecr wait image-scan-complete --repository-name myapp --image-id imageDigest=$DIGEST
- |
CRIT=$(aws ecr describe-image-scan-findings --repository-name myapp --image-id imageDigest=$DIGEST \
--query 'imageScanFindings.findingSeverityCounts.CRITICAL' --output text)
[ "$CRIT" = "None" ] || [ "$CRIT" -eq 0 ] || { echo "CRITICAL=$CRIT"; exit 1; }The team wants to save effort: switch ECR back to MUTABLE and always deploy using latest. List at least three risks.
① You cannot tell which version is running in production, so auditing and rollback become hard; ② when scaling out or restarting tasks, you may pull a newer latest, leaving mixed versions in the same service; ③ overwritten old images become untagged and may be deleted by the lifecycle policy, so rollback fails completely; ④ scan results no longer match what is deployed. Alternative: immutable sha- tags + deploy by digest + idempotent builds.
Verified teaching videos
No verified video on “GitLab CI + ECR immutable tags” was found; please refer to the documents and storyboard below.
Official documentation
- ECR: Image tag mutability
- ECR: Private registry authentication
- ECR: Image scanning
- GitLab Docs: Use Docker to build Docker images
Video storyboard (about 60 seconds)
Screen: the latest tag is torn off like a sticky note and stuck onto a new image; the old image turns gray.
Narration: a mutable tag is overwritten every time, so yesterday's version can never be recovered.
Screen: the tag sha-3f2a9c1 is welded onto one image; a second push is blocked by a red cross, then a branch arrow for “check first, then build” appears.
Narration: an immutable tag guarantees that one name maps to one piece of content. Check before building, and a re-run will not fail.
Screen: the build.env file flies from the build job to the deploy job, containing myapp@sha256.
Narration: a dotenv artifact hands the digest to the deploy job; the task definition uses the digest, so scaling and rollbacks pull the same content.
Module 4 · Deploy to ECS on Fargate
- Use the CLI to create a Fargate service with deployment circuit breaker enabled
myapp-dev(port 5000, container health check/healthz). - Write a GitLab deploy job: use the digest passed via dotenv to
IMAGE_URIrender the task definition, register it, update the service,aws ecs wait services-stable, then use a Verify step to confirm that the PRIMARY revision is the one just registered. - Use
environment(includingdeployment_tier) to record deployment history, and useresource_groupto serialize deployments to the same environment, and understand GitLab's “re-deploying an old job = rollback”. - Write the minimal ECS permissions for the CI role, with
iam:PassedToServiceconditionsiam:PassRole.
IMAGE_URI. Importance:★★★★★What: what an ECS deployment calls
| Step | API | CI role permission | Description |
|---|---|---|---|
| Render | (locally sed/jq) | None | Replace the __IMAGE_URI__ with …/myapp@sha256:… |
| Register | RegisterTaskDefinition | ecs:RegisterTaskDefinition (Resource *) + the iam:PassRole | permission; creates a new revision myapp:7 |
| Deploy | UpdateService | ecs:UpdateService (service ARN) | Triggers a rolling deployment (or blue/green, depending on the service configuration) |
| Wait | DescribeServices Poll | ecs:DescribeServices | aws ecs wait services-stable: every 15 seconds, up to 40 times (about 10 minutes); exits with a non-zero code on timeout |
| Verify | DescribeServices | (same as above) | PRIMARY deployment's taskDefinition task definition equals the just-registered ARN,rolloutState and whether COMPLETED |
Why: why a Verify step is essential
With the circuit breaker enabled, rollback=true if tasks of the new revision keep failing to start, ECS marks the deployment as FAILED and automatically rolls back to the last successful revision. Once the rollback finishes, the service is “stable” again,wait services-stable so the wait may return success right away. Without Verify, the pipeline would be green while the old version is still running in production. Verify separates “stable” from “stable on my revision”.
How: circuit breaker thresholds (verified)
ECS docs: the default threshold type is percentage, value 50. The failure threshold = desired task count × 50%, clamped to a minimum of 3 and a maximum of 200. In the lab the desired count is 1, so at least 3 new tasks must fail before it triggers. By default, only consecutive failures are counted (resetOnHealthyTask=true, resetting when any task is healthy); you can now also use thresholdConfiguration={type=COUNT,value=5} and resetOnHealthyTask=false to customize them. Once triggered, the deployment status is set to FAILED,rolloutStateReason stating the reason.
The GitLab-side trio
| Keyword | Purpose | Use in this lesson |
|---|---|---|
environment: name / deployment_tier / url | In Operate → Environments , record each deployment (which commit, which job, who triggered it) | dev / development; production production / production |
resource_group | jobs in the same resource group run one at a time, to prevent two pipelines from running update-service | aws-dev,aws-production |
| Re-deploy / Rollback | On the environment page, clicking “Re-deploy” on an old deployment re-runs the deploy job from that time | The old job reads from that pipeline's dotenv artifact IMAGE_URI → registers a new revision whose content is the old digest |
Note: re-running an old job depends on the artifacts from that time not having expired yet. GitLab.com by default keeps the artifacts of the most recent successful pipeline for each ref, and older ones are deleted when they expire. In production, you can roll back on the ECS side (update-service --task-definition myapp:6), which does not depend on GitLab artifacts.
When: rolling or blue/green?
- Rolling (default ECS deployment controller):
minimumHealthyPercent=100, maximumPercent=200Start new tasks before stopping old ones; configure the circuit breaker and you are done. This is the main path in this lesson. - ECS native blue/green: requires an ALB and two target groups; old and new revisions run at the same time; after validation, traffic is switched, and during the bake period you can roll back within seconds; the deploy job is still
update-service, and CodeDeploy is not needed.
update-service Success means the deployment succeeded”—it only starts the deployment, and returns quickly. ② “A successful wait means the new version is live”—after a circuit-breaker rollback the service also becomes stable, so Verify is required. ③ “The CI role has to have iam:* to deploy”—it only needs iam:PassRole permissions for the execution role (and task role), and use iam:PassedToService=ecs-tasks.amazonaws.com to tighten them. ④ “If the job is canceled, the deployment stops”—the ECS deployment continues on the AWS side regardless of the job.Interaction between the deploy job and ECS
Interactive: rolling deployment and circuit breaker
The “good version” shows a normal rolling replacement; the “bad version” shows new tasks repeatedly exiting → circuit breaker triggers → automatic rollback → Verify fails the job.
Task definition template ecs/taskdef.json (committed to the repository)
{
"family": "myapp",
"networkMode": "awsvpc",
"requiresCompatibilities": ["FARGATE"],
"cpu": "256",
"memory": "512",
"executionRoleArn": "arn:aws:iam::111122223333:role/myappTaskExecutionRole",
"containerDefinitions": [{
"name": "web",
"image": "__IMAGE_URI__",
"essential": true,
"portMappings": [{ "containerPort": 5000, "protocol": "tcp" }],
"healthCheck": {
"command": ["CMD-SHELL", "python -c \"import urllib.request; urllib.request.urlopen('http://localhost:5000/healthz')\" || exit 1"],
"interval": 15, "timeout": 5, "retries": 3, "startPeriod": 20
},
"logConfiguration": {
"logDriver": "awslogs",
"options": { "awslogs-group": "/ecs/myapp", "awslogs-region": "ca-central-1", "awslogs-stream-prefix": "web" }
}
}]
}
The myapp image is based on Python and may not include curl, so the health check uses the Python standard library.
One-time: create the service (run by an administrator)
source ~/gitlab-part4.env
IMG=$(aws ecr describe-images --repository-name myapp --query 'sort_by(imageDetails,&imagePushedAt)[-1].imageDigest' --output text)
sed "s#__IMAGE_URI__#$ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com/myapp@$IMG#; s#111122223333#$ACCOUNT_ID#" ecs/taskdef.json > /tmp/td.json
aws ecs register-task-definition --cli-input-json file:///tmp/td.json --query taskDefinition.revision
aws ecs create-service --cluster myapp-lab --service-name myapp-dev --task-definition myapp \
--desired-count 1 --launch-type FARGATE \
--network-configuration "awsvpcConfiguration={subnets=[$SUBNETS],securityGroups=[$TASK_SG],assignPublicIp=ENABLED}" \
--deployment-configuration "deploymentCircuitBreaker={enable=true,rollback=true},maximumPercent=200,minimumHealthyPercent=100" \
--tags key=course,value=gitlab-part4 --query 'service.[serviceName,status]' --output text
1 myapp-dev ACTIVE
Deploy job
deploy-dev:
stage: deploy
extends: .aws-oidc
needs: [build-push]
environment:
name: dev
deployment_tier: development
resource_group: aws-dev
rules:
- if: $CI_COMMIT_BRANCH == "main"
variables:
CLUSTER: myapp-lab
SERVICE: myapp-dev
script:
- sed "s#__IMAGE_URI__#${IMAGE_URI}#" ecs/taskdef.json > td.json
- TD_ARN=$(aws ecs register-task-definition --cli-input-json file://td.json --query taskDefinition.taskDefinitionArn --output text)
- echo "registered $TD_ARN"
- aws ecs update-service --cluster $CLUSTER --service $SERVICE --task-definition "$TD_ARN" --query 'service.deployments[0].id' --output text
- aws ecs wait services-stable --cluster $CLUSTER --services $SERVICE
- |
OUT=$(aws ecs describe-services --cluster $CLUSTER --services $SERVICE \
--query 'services[0].deployments[?status==`PRIMARY`]|[0].[taskDefinition,rolloutState]' --output text)
GOT=$(echo "$OUT" | cut -f1); STATE=$(echo "$OUT" | cut -f2)
echo "Verify: want=${TD_ARN##*/} got=${GOT##*/} state=$STATE"
[ "$GOT" = "$TD_ARN" ] && [ "$STATE" = "COMPLETED" ]
ECS permissions for the CI role
cat > ecs-deploy.json <<EOF
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":["ecs:RegisterTaskDefinition","ecs:DescribeTaskDefinition"],"Resource":"*"},
{"Effect":"Allow","Action":["ecs:UpdateService","ecs:DescribeServices"],
"Resource":"arn:aws:ecs:$AWS_REGION:$ACCOUNT_ID:service/myapp-lab/myapp-dev"},
{"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 gitlab-myapp-dev-deploy --policy-name ecs-deploy --policy-document file://ecs-deploy.json
| Command | Purpose |
|---|---|
aws ecs describe-services --query 'services[0].events[:5].message' | Last 5 service events (check this first if it is stuck) |
aws ecs list-tasks --desired-status STOPPED + describe-tasks --query 'tasks[].stoppedReason' | Reasons for stopped tasks |
aws logs tail /ecs/myapp --since 10m | Container logs |
aws ecs update-service --task-definition myapp:6 | Manually roll back to an old revision |
Lab 4: deploy myapp-dev through the pipeline and rehearse a circuit-breaker rollback (about 8 minutes)
ecs/taskdef.json account ID in it to yours, submit it; run the “Create service” and “ECS permissions” parts of the “Commands” tab.deploy-dev job and push
git add ecs/taskdef.json .gitlab-ci.yml && git commit -m "ci: deploy to ECS dev" && git push glab ci trace deploy-dev
registered arn:aws:ecs:ca-central-1:111122223333:task-definition/myapp:2 ecs-svc/1234567890123456789 Verify: want=myapp:2 got=myapp:2 state=COMPLETED Job succeeded
TASK=$(aws ecs list-tasks --cluster myapp-lab --service-name myapp-dev --query 'taskArns[0]' --output text) ENI=$(aws ecs describe-tasks --cluster myapp-lab --tasks $TASK --query "tasks[0].attachments[0].details[?name=='networkInterfaceId'].value" --output text) IP=$(aws ec2 describe-network-interfaces --network-interface-ids $ENI --query 'NetworkInterfaces[0].Association.PublicIp' --output text) curl -s http://$IP:5000/healthz
ok
CMD ["sh","-c","exit 1"] and push. Watch the job log: after a few minutes the service rolls back and stabilizes, and Verify prints want=myapp:3 got=myapp:2, and the job fails. Then git revert revert the change.
aws ecs describe-services --cluster myapp-lab --services myapp-dev \ --query 'services[0].deployments[].[status,taskDefinition,rolloutState,rolloutStateReason]' --output table
Case 1: the pipeline is all green, but production is still on the old version
Problem: The new version is missing an environment variable, so tasks exit as soon as they start; after the circuit breaker rolls back wait services-stable the wait succeeds, the pipeline is green, and the team assumes it has shipped. Fix: Add a Verify step (the approach used in this lesson) that fails when PRIMARY does not match, and configure EventBridge → notification for ECS deployment failure events.
Case 2: two pipelines deploy the same service at the same time
Problem: Two MRs are merged one after another, so the deploy jobs of the two main pipelines run at almost the same time; the Verify of whichever finishes later finds that PRIMARY is not its own revision and fails, and the result is misread as “the deployment is broken”. Fix:resource_group: aws-dev Run deployments to the same environment serially. GitLab's “Prevent outdated deployment jobs” setting keeps an older pipeline from overwriting a newer deployment.
Case 3: the rollback button does not work
Problem: You want to re-deploy a version from two months ago on the environment page, but the job reports IMAGE_URI as empty. Root cause: The dotenv artifact of that pipeline has expired and been cleaned up. Fix: For rollbacks, prefer the ECS side update-service --task-definition myapp:N (the revision records the digest); or, in the deploy job, write the digest into the environment's url/ deployment notes, so it can be found again later.
Common errors and fixes
An error occurred (AccessDeniedException) when calling the RegisterTaskDefinition operation: User: arn:aws:sts::…:assumed-role/gitlab-myapp-dev-deploy/… is not authorized to perform: iam:PassRole on resource: arn:aws:iam::…:role/myappTaskExecutionRole
Cause: The CI role lacks PassRole on the execution role. Fix: Add it following the “Commands” tab; pay attention to how iam:PassedToService is written ecs-tasks.amazonaws.com.
An error occurred (ServiceNotFoundException) when calling the UpdateService operation: Service not found.
Cause: The service has not been created yet, or the cluster, region, or service name is wrong (the AWS_DEFAULT_REGION is ca-central-1). The deploy job does not create the service automatically.
Waiter ServicesStable failed: Max attempts exceeded
Cause: The service did not stabilize within 10 minutes: new tasks cannot pull the image, health checks fail, containers exit, or the deployment configuration does not allow starting new tasks.
aws ecs describe-services --cluster myapp-lab --services myapp-dev --query 'services[0].events[:5].message' aws ecs describe-tasks --cluster myapp-lab --tasks $(aws ecs list-tasks --cluster myapp-lab --desired-status STOPPED --query 'taskArns[0]' --output text) --query 'tasks[0].stoppedReason'
CannotPullContainerError: … not found / ResourceInitializationError: unable to pull secrets or registry auth
Cause: Wrong image URI or digest; the execution role lacks AmazonECSTaskExecutionRolePolicy; the subnet the tasks are in cannot reach ECR (no public IP, no NAT, no VPC endpoint).
Verify: want=myapp:8 got=myapp:6 state=COMPLETED → ERROR: Job failed: exit code 1
Cause: This means Verify is working correctly: the circuit breaker has rolled back. Check rolloutStateReason and the reasons for stopped tasks, fix the problem, then re-deploy.
1. Manually roll myapp-dev back to revision 6 and wait for it to stabilize.
aws ecs update-service --cluster myapp-lab --service myapp-dev --task-definition myapp:6 >/dev/null aws ecs wait services-stable --cluster myapp-lab --services myapp-dev
2. Check the status and reason of all deployments of the service.
aws ecs describe-services --cluster myapp-lab --services myapp-dev \ --query 'services[0].deployments[].[status,taskDefinition,rolloutState,rolloutStateReason]' --output table
Your deploy job, at wait services-stable was manually canceled. What happened on the ECS side? What will the GitLab environment page show? What should you do next?
The ECS deployment is unaffected and keeps rolling out until it completes or the circuit breaker rolls it back. GitLab has only stopped waiting, and the deployment shows as “canceled” on the environment page. Next step: use describe-services to check the PRIMARY revision and rolloutState. If it has finished, re-run the job so Verify can confirm (or accept the current state); if it failed, follow the troubleshooting steps. In production, restrict who can cancel deploy jobs, and use resource_group to prevent the next pipeline from jumping in at this point.
Verified teaching videos
No verified video on “GitLab CI + ECS circuit breaker” was found.
Official documentation
- ECS: Deployment circuit breaker
- ECS: Task execution IAM role
- GitLab Docs: Environments
- GitLab Docs: Resource groups
Video storyboard (about 60 seconds)
Screen: two new task blocks grow beside two old task blocks; once the green light comes on, the old blocks fade out.
Narration: rolling deployment starts the new tasks first, and stops the old tasks only after health checks pass.
Screen: new tasks turn red one after another, the counter shows 1, 2, 3, the fuse blows, and the needle returns to the old revision.
Narration: when the new version keeps failing, the circuit breaker marks the deployment as failed and rolls it back automatically.
Screen: in the GitLab job log, a Verify line reads want 8 got 6, and the job turns red.
Narration: after the rollback the service is still stable, so you must check whether production is running your revision.
Module 5 · Deploy to EKS and Lambda
- Explain GitLab agent for Kubernetes the CI/CD workflow: agentk actively connects to KAS, and jobs in authorized projects get a kubecontext named
<agent project path>:<agent name>kubecontext. - Know how to write the
ci_accessin the agent configuration, and know thataccess_as: ci_joband features such as impersonation require Premium. - Use EKS access entries +
AmazonEKSEditPolicy(namespace-scoped) to authorize the CI role, and distinguishUnauthorizedfromForbidden. - In a GitLab job, update the Lambda code and publish a version, then use the alias's additional version weight for a 10% canary, with rollback within seconds.
What: two ways to deploy to EKS
| A: GitLab agent for Kubernetes | B: OIDC role + EKS access entries | |
|---|---|---|
| Connection direction | In-cluster agentk actively connects to GitLab's KAS (on GitLab.com, it is kas.gitlab.com), and the API server does not need to be exposed publicly | The Runner directly accesses the EKS API endpoint (public, or a private endpoint reachable over a connected network) |
| Credentials needed by the job | No AWS credentials; GitLab injects a kubeconfig for jobs in authorized projects ($KUBECONFIG) | OIDC → STS temporary credentials,aws eks update-kubeconfig + aws eks get-token |
| where authorization is configured | agent configuration file .gitlab/agents/<name>/config.yaml under the ci_access (projects or groups, up to 500 each) | EKS access entry + access policy (or RBAC) |
| In-cluster identity | By default, operations run as the agent's service account; starting with Premium, it can access_as: ci_job impersonate as gitlab:ci_job:<job ID>, then use RBAC to tighten | users mapped from IAM role ARNs; access policies limited to namespaces |
| level | agent and CI/CD workflow: Free; impersonation: Premium/Ultimate | AWS-native, no GitLab tier requirement |
| Suitable for | platform teams that centrally manage cluster access, private clusters, and GitOps (the agent also supports Flux) | clusters without an agent, or where you want all permissions audited in AWS IAM |
Both paths only solve “how the deploy job accesses the Kubernetes API”. Nodes pull images from ECR is a separate matter: the EKS node role (or Auto Mode nodes) needs ECR read-only permissions; it is unrelated to CI.
The two gates on path B
| Layer | Who decides | What CI needs | Error when it fails |
|---|---|---|---|
| AWS API | IAM | eks:DescribeCluster (update-kubeconfig used to get the endpoint and CA) | AccessDeniedException … eks:DescribeCluster |
| Kubernetes API | EKS authentication (IAM identity → access entry) + authorization (access policy / RBAC) | Create an access entry for the CI role, associated with AmazonEKSEditPolicy (namespace-scoped) | You must be logged in to the server (Unauthorized) or Forbidden |
aws eks get-token use the current temporary credentials to generate a presigned STS GetCallerIdentity request as a bearer token; EKS maps the assumed-role session back to the role ARN—so the access entry uses the role ARN, not the session ARN. The cluster authentication mode must be API or API_AND_CONFIG_MAP.
What: Lambda versions and aliases
- $LATEST: a mutable “working copy”,
UpdateFunctionCodewhich is what you edit. - Version:
PublishVersion(or--publish) generated immutable snapshots, numbered 1, 2, 3…. - Alias: a pointer to a version (for example
live), which can be setAdditionalVersionWeightsto send part of the traffic to a second version—Lambda's native canary. Additional weights can only point to published versions. - Deployment package: zip (direct upload, ≤ 50 MB) or a container image (must be in ECR, up to 10 GB). To run a Flask app like myapp as a container image on Lambda, you need to adapt it to the Lambda runtime interface (for example with an extension such as the AWS Lambda Web Adapter; follow that project's documentation). This lesson's lab uses a minimal zip function to demonstrate the release mechanism.
access_as: ci_job (Premium) + RBAC, or deploy agents with different permissions for different teams on the Free tier. ② “The EKS creator can access it, so the CI role can too”—every other identity must have an access entry created explicitly. ③ “A Lambda alias weight can point to $LATEST”—it can only point to published versions. ④ “Pods access AWS using the CI role”—pods should use a runtime role through EKS Pod Identity or IRSA.Comparison of the two paths
Lambda: versions and aliases
Interactive: Lambda alias weighted traffic shifting
Drag the weight slider, then click “Send 50 requests” to see how requests are split between version 6 and version 7. Version 7 can be switched to “defective” to see how the error rate changes with the weight, then practice rolling back.
Path A: GitLab agent for Kubernetes
| Step | Command / location | Description |
|---|---|---|
| Register agent | Project → Operate → Kubernetes clusters → Connect a cluster (agent) | Enter a name eks-lab, “Create and register”, copy the token and installation command |
| Install agentk | helm upgrade --install … gitlab/gitlab-agent | Helm repository https://charts.gitlab.io; config.kasAddress follow the command generated by the UI |
| Authorize projects | .gitlab/agents/eks-lab/config.yaml under the ci_access | projects and groups must be under the same top-level group as the agent project |
| CLI bootstrap (optional) | glab cluster agent bootstrap eks-lab | Works with Flux for one-step registration and installation |
# Run by the cluster administrator (the cluster reuses eks-lab from K8s Lesson 7, and kubectl already points to it) helm repo add gitlab https://charts.gitlab.io && helm repo update helm upgrade --install eks-lab gitlab/gitlab-agent \ --namespace gitlab-agent-eks-lab --create-namespace \ --set config.token="$AGENT_TOKEN" \ --set config.kasAddress=wss://kas.gitlab.com # ← the value generated in the GitLab UI takes precedence kubectl -n gitlab-agent-eks-lab get pods
NAME READY STATUS RESTARTS AGE eks-lab-gitlab-agent-v2-6f9c7d8b5-k2xvz 1/1 Running 0 40s
ci_access:
projects:
- id: mygroup-lab/myapp
# Starting with Premium, you can impersonate per job, then use RBAC to restrict the permissions of the gitlab:ci_job group:
# access_as:
# ci_job: {}
deploy-eks:
stage: deploy
image: alpine/k8s:1.37.2 # includes kubectl and helm (see the image documentation)
needs: [build-push]
environment:
name: dev-eks
deployment_tier: development
resource_group: eks-dev
rules:
- if: $CI_COMMIT_BRANCH == "main"
script:
- kubectl config get-contexts
- kubectl config use-context mygroup-lab/myapp:eks-lab
- kubectl -n myapp set image deployment/myapp web="$IMAGE_URI"
- kubectl -n myapp rollout status deployment/myapp --timeout=180s
# Helm 4: --rollback-on-failure is the new name for Helm 3's --atomic
# - helm upgrade --install myapp ./chart -n myapp --set image.ref="$IMAGE_URI" --rollback-on-failure --timeout 5m
Path B: OIDC role + EKS access entry
| Command | Purpose | Description |
|---|---|---|
aws eks describe-cluster --query cluster.accessConfig | Check the authentication mode | Requires API or API_AND_CONFIG_MAP |
aws eks create-access-entry --principal-arn ROLE_ARN | Create an access entry for the CI role | --type STANDARD (default) |
aws eks associate-access-policy --access-scope type=namespace,namespaces=myapp | Associate an access policy | CI only gets the application namespace |
aws eks update-kubeconfig --name eks-lab | Generate kubeconfig | Requires eks:DescribeCluster |
ROLE_ARN=arn:aws:iam::$ACCOUNT_ID:role/gitlab-myapp-dev-deploy
aws eks create-access-entry --cluster-name eks-lab --principal-arn $ROLE_ARN --type STANDARD
aws eks associate-access-policy --cluster-name eks-lab --principal-arn $ROLE_ARN \
--policy-arn arn:aws:eks::aws:cluster-access-policy/AmazonEKSEditPolicy \
--access-scope type=namespace,namespaces=myapp
aws iam put-role-policy --role-name gitlab-myapp-dev-deploy --policy-name eks-describe --policy-document \
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"eks:DescribeCluster\",\"Resource\":\"arn:aws:eks:$AWS_REGION:$ACCOUNT_ID:cluster/eks-lab\"}]}"
deploy-eks-iam:
stage: deploy
extends: .aws-oidc
image:
name: alpine/k8s:1.37.2 # needs both the aws CLI and kubectl
entrypoint: [""]
needs: [build-push]
environment: { name: dev-eks, deployment_tier: development }
script:
- aws eks update-kubeconfig --name eks-lab
- kubectl auth can-i patch deployments -n myapp
- kubectl -n myapp set image deployment/myapp web="$IMAGE_URI"
- kubectl -n myapp rollout status deployment/myapp --timeout=180s
Lambda: publish a version and weighted aliases
| Command | Purpose |
|---|---|
aws lambda update-function-code --function-name F --zip-file fileb://fn.zip --publish | Update code and publish a version (for container images, use --image-uri …@sha256:…) |
aws lambda wait function-updated-v2 --function-name F | Wait for the update to finish before switching the alias |
aws lambda update-alias … --function-version 6 --routing-config '{"AdditionalVersionWeights":{"7":0.1}}' | v6 90% / v7 10% |
aws lambda update-alias … --function-version 7 --routing-config '{"AdditionalVersionWeights":{}}' | Shift all to v7 |
package-lambda:
stage: build
image: python:3.13-alpine
script:
- cd lambda && python -m zipfile -c ../fn.zip handler.py
artifacts:
paths: [fn.zip]
expire_in: 1 day
deploy-lambda:
stage: deploy
extends: .aws-oidc
needs: [package-lambda]
environment: { name: dev-lambda, deployment_tier: development }
resource_group: lambda-dev
script:
- NEW=$(aws lambda update-function-code --function-name myapp-fn --zip-file fileb://fn.zip --publish --query Version --output text)
- aws lambda wait function-updated-v2 --function-name myapp-fn
- OLD=$(aws lambda get-alias --function-name myapp-fn --name live --query FunctionVersion --output text)
- echo "canary v$NEW 10% (stable v$OLD)"
- aws lambda update-alias --function-name myapp-fn --name live --function-version "$OLD" --routing-config "{\"AdditionalVersionWeights\":{\"$NEW\":0.1}}"
The CI role needs lambda:UpdateFunctionCode,PublishVersion,GetFunctionConfiguration,GetAlias,UpdateAlias (resources scoped to the function ARN and function ARN:*).
Lab 5 (optional, about 6 minutes): Lambda alias 10% canary
The EKS part reuses the cluster from K8s Lesson 7; just read the “Commands” tab (a running EKS cluster costs money every hour). The Lambda lab is almost free, within the free tier.
mkdir -p lambda && cat > lambda/handler.py <<'EOF'
def handler(event, context):
return {"statusCode": 200, "body": f"myapp-fn version {context.function_version}"}
EOF
(cd lambda && python3 -m zipfile -c ../fn.zip handler.py)
aws iam create-role --role-name myapp-fn-exec --assume-role-policy-document \
'{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"lambda.amazonaws.com"},"Action":"sts:AssumeRole"}]}'
aws iam attach-role-policy --role-name myapp-fn-exec --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
sleep 10
aws lambda create-function --function-name myapp-fn --runtime python3.13 --handler handler.handler \
--zip-file fileb://fn.zip --role arn:aws:iam::$ACCOUNT_ID:role/myapp-fn-exec --publish --query Version --output text
aws lambda create-alias --function-name myapp-fn --name live --function-version 1
1
{ "AliasArn": "arn:aws:lambda:ca-central-1:111122223333:function:myapp-fn:live", "FunctionVersion": "1", … }aws iam put-role-policy --role-name gitlab-myapp-dev-deploy --policy-name lambda-deploy --policy-document "{
\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[
\"lambda:GetFunctionConfiguration\",\"lambda:UpdateFunctionCode\",\"lambda:PublishVersion\",
\"lambda:GetAlias\",\"lambda:UpdateAlias\"],
\"Resource\":[\"arn:aws:lambda:$AWS_REGION:$ACCOUNT_ID:function:myapp-fn\",\"arn:aws:lambda:$AWS_REGION:$ACCOUNT_ID:function:myapp-fn:*\"]}]}"for i in $(seq 1 20); do aws lambda invoke --function-name myapp-fn:live --query ExecutedVersion --output text /tmp/out.json; done | sort | uniq -c aws lambda get-alias --function-name myapp-fn --name live --query '[FunctionVersion,RoutingConfig]'
18 1
2 2
["1", {"AdditionalVersionWeights": {"2": 0.1}}]when: manual two jobs)
aws lambda update-alias --function-name myapp-fn --name live --function-version 2 --routing-config '{"AdditionalVersionWeights":{}}' # full rollout
aws lambda update-alias --function-name myapp-fn --name live --function-version 1 --routing-config '{"AdditionalVersionWeights":{}}' # rollbackCase 1: private EKS cluster, hosted Runner cannot reach the API
Problem: Security requires that EKS expose only a private endpoint. GitLab.com hosted Runners cannot reach it, so the deploy job times out. Fix: Install the GitLab agent in the cluster (it only needs outbound access to kas.gitlab.com), and have jobs use the kubecontext injected by the agent; or run a self-managed Runner inside the VPC. Benefit: The API server is not exposed, and CI no longer needs AWS credentials.
Case 2: one agent gave cluster-admin to every project
Problem: The platform team, at the group level, ci_access authorized the entire top-level group, and the agent uses the default high-privilege service account, so jobs in any project can delete kube-system. Fix: Authorize only the projects that need it; under Premium, enable access_as: ci_job and use RBAC to grant only the gitlab:ci_job group edit access to the app namespace. On the Free tier, deploy several agents with different permissions, one per team.
Case 3: Lambda canary exposes a problem; rollback within seconds
Problem: The new version mis-parses a certain type of event. Fix: The alias gives only 10%. After a CloudWatch error-rate alarm, the on-call engineer clicks rollback-lambda (when: manual) job to run update-alias update-alias to point back to the old version. For further automation, CodeDeploy's Lambda deployment configurations can automate “observe, then roll back”.
Common errors and fixes
error: no context exists with the name: "mygroup-lab/myapp:eks-lab"
Cause: The project is not in the agent's ci_access authorization list; the agent configuration file path or agent name does not match; the agent is not connected (pod not running); or the context name is wrong (format: <agent config project path>:<agent name>). Diagnosis: In the job, first run kubectl config get-contexts; in Operate → Kubernetes clusters check the agent connection status.
error: You must be logged in to the server (Unauthorized)
Cause (path B): The CI role has no EKS access entry (or the cluster is still in CONFIG_MAP mode and aws-auth has no mapping), or the kubeconfig points to a different cluster or region.
aws sts get-caller-identity aws eks list-access-entries --cluster-name eks-lab aws eks describe-cluster --name eks-lab --query cluster.accessConfig.authenticationMode
Error from server (Forbidden): deployments.apps "myapp" is forbidden: User "…" cannot patch resource "deployments" in API group "apps" in the namespace "myapp"
Cause: Path B: the access entry has no associated policy, or its scope does not include the namespace. Path A: enabled access_as: ci_job but did not grant RBAC to the gitlab:ci_job group. Fix:aws eks list-associated-access-policies … or add a RoleBinding.
An error occurred (ResourceConflictException) when calling the UpdateAlias operation: The operation cannot be performed at this time. An update is in progress for resource
Cause: The previous update has not finished. Fix:aws lambda wait function-updated-v2 --function-name F Once it finishes, operate again; in the deploy job, add resource_group.
1. In a job, list all kubecontexts injected by the GitLab agent.
kubectl config get-contexts -o name
2. Set the live alias to v3 80% / v4 20%.
aws lambda update-alias --function-name myapp-fn --name live --function-version 3 \
--routing-config '{"AdditionalVersionWeights":{"4":0.2}}'The platform team does not want each application pipeline to access the Kubernetes API directly. How would you design the GitLab-to-EKS deployment?
Use GitOps: the application pipeline only builds and pushes images (OIDC → ECR), then commits or opens an MR to the deployment configuration repository to update the image digest. Inside the cluster, Flux (the GitLab agent supports Flux workflows) or Argo CD pulls and syncs. CI needs no Kubernetes permissions at all, and no agent's ci_access; approval is enforced through protected branches and approval rules on the configuration repository.
Verified teaching videos
No verified video on “GitLab agent for Kubernetes + EKS” was found; please refer to the documents and storyboard below.
Official documentation
- GitLab Docs: Using GitLab CI/CD with a Kubernetes cluster (agent)
- GitLab Docs: Installing the agent for Kubernetes
- EKS: Grant IAM users access to Kubernetes with EKS access entries
- Lambda: weighted alias
Video storyboard (about 60 seconds)
Screen: the agentk robot inside the cluster pulls a tunnel out to GitLab's KAS, and the job sends kubectl commands into the cluster through the tunnel.
Narration: the GitLab agent connects out from inside the cluster; jobs need no AWS credentials, and the API server does not need to be exposed publicly.
Screen: the other path, two gates: the first is labeled IAM, the second is labeled Access Entry.
Narration: without an agent, IAM only lets you obtain the cluster address; access entries decide what you can do inside Kubernetes.
Screen: the Lambda traffic bar shows 90/10, an error red dot appears, and the pointer instantly returns to the old version.
Narration: Lambda first gives the new version 10% of the traffic; if something goes wrong, the alias is pointed back, and the rollback completes in seconds.
Module 6 · Multi-account and environment promotion
- Design a dev / prod multi-account structure: the OIDC provider goes in each account, one per account; GitLab uses environment-scoped variables
AWS_ROLE_ARNto let the same script assume different roles in different environments. - Write the trust policy for the prod role: trust only this project (
project_id) and only its protected (ref_protected)v*tags. - Explain the GitLab-side controls and their tiers: protected branches/tags (Free),
when: manual(Free), protected environments and deployment approvals (Premium/Ultimate). - Implement “build once, promote the same digest”, pull the ECR image across accounts, and verify in the job that the credentials belong to the expected account.
rules and variable precedence. Importance:★★★★★What: the mapping between accounts, roles, and environments
| GitLab environment | AWS account | Role (in each account) | Trust condition (gitlab.com:*) | GitLab-side controls |
|---|---|---|---|---|
dev (tier development) | dev 111122223333 | gitlab-myapp-dev-deploy | sub = project_path:mygroup-lab/myapp:ref_type:branch:ref:main (if a tag pipeline needs to push to the shared ECR, also add a protected v* tag; see the Commands tab); project_id | main is a protected branch; push = deploy |
production (tier production) | prod 444455556666 | gitlab-myapp-prod-deploy | sub StringLike project_path:mygroup-lab/myapp:ref_type:tag:ref:v*; ref_protected = "true"; project_id | v* is a protected tag (only Maintainers can create it); the deploy job when: manual; Premium: protected environments + deployment approvals |
Why: why both sides need a gate
- Relying only on GitLab:
rules,when: manualwritten in.gitlab-ci.yml, and anyone with Developer permissions can defeat it by editing it on their own branch. AWS must itself judge whether this token came from a protected release tag. - Relying only on AWS: AWS cannot see who approved. The approvals of protected environments and the list of who can deploy exist only in GitLab.
- Combined: who can create
v*tag (GitLab protected tag) → the token'sref_protected=trueand sub is tag-shaped (AWS condition) → who can click deploy / approve (GitLab protected environment).
How: environment-scoped variables
In Settings → CI/CD → Variables add the variable twice AWS_ROLE_ARN: environment scope dev with the dev role ARN as its value, and scope production with the prod role ARN as its value. The job's environment:name determines which one it gets; the Module 2 .aws-oidc template needs no changes at all.. Jobs without environment cannot get scoped variables. You can also add another AWS_ACCOUNT_ID variable scoped to the same environment, used to validate and build the ECR address.
How: build once, promote the same digest
- Pipeline on main:
build-pushpushsha-3f2a9c1to the shared ECR (this lesson puts it in the dev account; in production a separate tooling account is common) →deploy-devautomatic deployment. - A Maintainer tags the same commit
v1.1: in the tag pipeline,build-pushfindssha-3f2a9c1already exists → reuse the digest (no rebuild);promote-taguseput-imageto add a readable tag to the same digest1.1. deploy-production(manually / after approval) use the sameIMAGE_URI=…@sha256:…to update the ECS service in the prod account; the prod task execution role pulls via the ECR repository policy across accounts.
Tiers and alternatives (verified)
| Capability | Tier | Free-tier alternative |
|---|---|---|
| Protected branches, protected tags | Free | — |
environments,deployment_tier,resource_group environment-scoped variables | Free | — |
| Protected environments (restrict who can deploy) | Premium / Ultimate | Protected tags restrict who can trigger + AWS-side ref_protected conditions |
| Deployment approvals (manual run still needed after approval) | Premium / Ultimate | when: manual (only a “confirm” button, not an approval); or an Ultimate trial |
Org-level trust and advanced options
- Group-level read-only role:
gitlab.com:namespace_id = 87654321+ref_protected = true, so protected branches in all projects within the group can read shared parameters (do not use for write operations). - Only allow GitLab hosted Runners:
gitlab.com:runner_environment = gitlab-hosted, to prevent anyone from registering a Runner on their own machine to run production jobs (decide based on your needs). - Put environment information into sub: starting with GitLab 18.7, the project API's
ci_id_token_sub_claim_componentslets sub includeref_protected, as well as theenvironment_protected,deployment_tier. Confirm the exact component names and concatenation format by printing them with a whoami job before writing them into the trust policy (this lesson has not verified the format in a real account).
ref:main is enough as long as the deploy job is set to manual”—anyone's pipeline on main gets the same sub, and the manual button can be bypassed by editing the YAML (for example, by changing the job to automatic); whereas the permission to create protected tags lives in GitLab settings, so editing YAML cannot change it. ② “One OIDC provider can serve all accounts”—the provider must be with its role in the same account. ③ “Rebuilding in prod during promotion”—that is no longer the image that was tested. ④ “Using environment to set AWS conditions”—it is not in the list of GitLab.com condition keys that AWS supports.Promotion pipeline and trust boundaries
Interactive: trust matrix evaluator
Choose the “requesting job” and the “target role”, and see how STS evaluates the conditions one by one; click “Show full matrix” to see all combinations. Ideal state: each role can be assumed only by the expected jobs.
prod account: provider and role
# Use the admin profile of the prod account
export AWS_PROFILE=prod PROD_ID=444455556666
aws iam create-open-id-connect-provider --url https://gitlab.com --client-id-list sts.amazonaws.com
cat > trust-prod.json <<EOF
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": { "Federated": "arn:aws:iam::$PROD_ID:oidc-provider/gitlab.com" },
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"gitlab.com:aud": "sts.amazonaws.com",
"gitlab.com:project_id": "$PROJECT_ID",
"gitlab.com:ref_protected": "true"
},
"StringLike": {
"gitlab.com:sub": "project_path:mygroup-lab/myapp:ref_type:tag:ref:v*"
}
}
}]
}
EOF
aws iam create-role --role-name gitlab-myapp-prod-deploy --assume-role-policy-document file://trust-prod.json \
--max-session-duration 3600 --query Role.Arn --output text
dev account: ECR repository policy allows prod to pull
export AWS_PROFILE=dev
aws ecr set-repository-policy --repository-name myapp --policy-text "{
\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"ProdPull\",\"Effect\":\"Allow\",
\"Principal\":{\"AWS\":\"arn:aws:iam::$PROD_ID:root\"},
\"Action\":[\"ecr:BatchGetImage\",\"ecr:GetDownloadUrlForLayer\",\"ecr:BatchCheckLayerAvailability\"]}]}"
The repository policy grants permissions to the prod account, but the prod account's execution role still needs its own IAM permissions (AmazonECSTaskExecutionRolePolicy already includes the ECR pull actions).
GitLab: protected tags and environment-scoped variables
# Protected tag v*: only Maintainers can create glab api -X POST "projects/:id/protected_tags" -f name='v*' -f create_access_level=40 # Environment-scoped variable (AWS_ROLE_ARN takes different values in the two environments) glab variable delete AWS_ROLE_ARN # delete the entry with scope * from Module 2 glab variable set AWS_ROLE_ARN --scope dev --value arn:aws:iam::111122223333:role/gitlab-myapp-dev-deploy glab variable set AWS_ROLE_ARN --scope production --value arn:aws:iam::444455556666:role/gitlab-myapp-prod-deploy glab variable set AWS_ACCOUNT_ID --scope dev --value 111122223333 glab variable set AWS_ACCOUNT_ID --scope production --value 444455556666
glab api in the :id will be replaced by the project for the current repository. Protected environments and approval rules (Premium) are configured in Settings → CI/CD → Protected environments in: select production, set “Allowed to deploy” to Maintainers, and choose one user or group as “Approvers”.
dev role: accepts both main and protected v* tags
in the tag pipeline, the build-push,promote-tag that operate the shared ECR (in the dev account) assume the dev role, and since sub is tag-shaped, the dev role's trust policy must also include the protected v* tags as well (or create a separate gitlab-myapp-ecr-push role with only ECR permissions, which is cleaner).
export AWS_PROFILE=dev
cat > trust-dev3.json <<EOF
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Principal":{"Federated":"arn:aws:iam::$ACCOUNT_ID:oidc-provider/gitlab.com"},
"Action":"sts:AssumeRoleWithWebIdentity",
"Condition":{
"StringEquals":{"gitlab.com:aud":"sts.amazonaws.com","gitlab.com:project_id":"$PROJECT_ID","gitlab.com:ref_protected":"true"},
"StringLike":{"gitlab.com:sub":[
"project_path:mygroup-lab/myapp:ref_type:branch:ref:main",
"project_path:mygroup-lab/myapp:ref_type:tag:ref:v*"]}}}]}
EOF
aws iam update-assume-role-policy --role-name gitlab-myapp-dev-deploy --policy-document file://trust-dev3.json
Promotion-related jobs
After switching to environment-scoped variables,without environment jobs cannot get AWS_ROLE_ARN. So Module 3's build-push needs one more line: environment: { name: dev, action: prepare } (prepare indicates that it only borrows the environment's variables, and is not counted as a deployment).
.verify-account: &verify-account
- test "$(aws sts get-caller-identity --query Account --output text)" = "$AWS_ACCOUNT_ID"
promote-tag:
stage: deploy
extends: .aws-oidc
needs: [build-push]
environment: { name: dev, action: prepare } # use the dev role to operate the shared ECR; not recorded as a deployment
rules:
- if: $CI_COMMIT_TAG =~ /^v\d+\.\d+/
script:
- MANIFEST=$(aws ecr batch-get-image --repository-name myapp --image-ids imageDigest=${IMAGE_URI#*@} --query 'images[0].imageManifest' --output text)
- aws ecr put-image --repository-name myapp --image-tag "${CI_COMMIT_TAG#v}" --image-manifest "$MANIFEST" || echo "tag already exists"
deploy-production:
stage: deploy
extends: .aws-oidc
needs: [build-push, promote-tag]
environment:
name: production
deployment_tier: production
resource_group: aws-production
rules:
- if: $CI_COMMIT_TAG =~ /^v\d+\.\d+/
when: manual
variables: { CLUSTER: myapp-prod, SERVICE: myapp-prod }
script:
- *verify-account
- sed "s#__IMAGE_URI__#${IMAGE_URI}#; s#111122223333:role#${AWS_ACCOUNT_ID}:role#" ecs/taskdef.json > td.json
- TD_ARN=$(aws ecs register-task-definition --cli-input-json file://td.json --query taskDefinition.taskDefinitionArn --output text)
- aws ecs update-service --cluster $CLUSTER --service $SERVICE --task-definition "$TD_ARN" >/dev/null
- aws ecs wait services-stable --cluster $CLUSTER --services $SERVICE
.verify-account Reuse a one-line check via a YAML anchor: fail if the credential's account doesn't match the environment variable, to prevent “wrong variable → deploy to the wrong account”. ${CI_COMMIT_TAG#v} Change v1.1 to 1.1, matching the image tag convention used across the series. The prod Verify step is the same as in Module 4 (omitted for brevity).
Lab 6: The prod role trusts only protected tags (about 8 minutes, single-account simulation)
You can do this without a second account: create another gitlab-myapp-prod-deploy role and myapp-prod service,AWS_ACCOUNT_ID using the same value for both scopes. Reading the cross-account parts (repository policy, second provider) is sufficient.
trust-prod.json (PROD_ID use the current account), and attach the same ecs-deploy (change the service ARN to myapp-prod) and ecr-push inline policy.myapp-lab, service name myapp-prod (in the job, change CLUSTER accordingly to myapp-lab).v9*) and push an unprotected tag v0.0-test, then manually run deploy-production:
An error occurred (AccessDenied) when calling the AssumeRoleWithWebIdentity operation: Not authorized to perform sts:AssumeRoleWithWebIdentity ERROR: Job failed: exit code 254
The sub format is correct (…:ref_type:tag:ref:v0.0-test), but ref_protected is false. Delete this tag and restore the protection rule.
v1.1:
glab release create v1.1 --ref main --notes "first prod release" glab ci view
In the pipeline, build-push reuse the digest,promote-tag add the 1.1 tag,deploy-production wait for the manual run (on Premium, it shows as pending approval). After it runs, the deployment record is visible in Operate → Environments → production .
aws ecr describe-images --repository-name myapp --image-ids imageTag=1.1 --query 'imageDetails[0].imageTags' Both include sha-… and 1.1; the myapp-dev and myapp-prod task definitions reference the same digest.Case 1: A developer “approved” a production deployment themselves
Problem: The prod role trusts ref:main, and the deploy job when: manual. In an MR, a developer changed deploy-production to run automatically, and after merge it went straight to production. Fix: Change the prod role to trust only protected v* tags (ref_protected + tag-form sub); on Premium, configure a protected environment and approvals for production; .gitlab-ci.yml add CODEOWNERS approval.
Case 2: The prod account never created the OIDC provider
Problem: Dev works fine, but the first production release fails with No OpenIDConnect provider found in your account for https://gitlab.com. Fix: Use Terraform/StackSets to create the provider and role consistently in every target account, as part of the “account baseline.”
Case 3: Wrong variable scope deployed to the dev account
Problem: The environment name changed from prod to production, but the variable scope was still prod; the job picked up the old dev ARN scoped to * and the “production release” actually updated the dev service. Fix: Delete * variable scoped to AWS_ROLE_ARN (a job that fails right away when a variable is missing is better than one that uses the wrong value); add a .verify-account check.
Common errors and fixes
deploy-production: Not authorized to perform sts:AssumeRoleWithWebIdentity (deploy-dev works)
Troubleshooting order:① Was the pipeline triggered by a tag (is the sub in tag form)? ② Is the tag protected (ref_protected)? ③ Is AWS_ROLE_ARN the prod role (does the scope match the environment name)? ④ Are project_id and the path in the prod trust policy correct?
Parameter validation failed: Invalid length for parameter RoleArn, value: 0, valid min length: 20
Cause:AWS_ROLE_ARN is an empty string (the AWS CLI rejects it during local parameter validation): the job did not set environment, or the environment name does not match the variable scope (prod vs production). Diagnosis: At the start of before_script, add echo "env=$CI_ENVIRONMENT_NAME role=${AWS_ROLE_ARN:-<empty>}".
CannotPullContainerError: … 111122223333.dkr.ecr.ca-central-1.amazonaws.com/myapp@sha256:… : not authorized
Cause: The prod execution role pulls across accounts, but the ECR repository policy in the dev account does not grant access to the prod account; or the image is encrypted with KMS and prod has no decrypt permission.
This job is waiting for approval / This job is blocked
Note: Deployment approvals on Premium are in effect. Approvers go to Operate → Environments → production to approve; after approval, the job still needs to be run manually.
1. List all environment-scoped variables in the project.
glab variable list glab api "projects/:id/variables" | jq -r '.[] | [.key, .environment_scope] | @tsv'
2. Add the tag 1.1 to an existing digest in ECR without pushing again.
MANIFEST=$(aws ecr batch-get-image --repository-name myapp --image-ids imageTag=sha-3f2a9c1 --query 'images[0].imageManifest' --output text) aws ecr put-image --repository-name myapp --image-tag 1.1 --image-manifest "$MANIFEST"
Your company only has GitLab Free, but requires “production deployments must be confirmed by someone, and developers cannot publish on their own.” How would you design this?
① Protected tags v*: only Maintainers (release owners) can create them; ② the prod role trusts a sub of …:ref_type:tag:ref:v* and gitlab.com:ref_protected = true and a matching project_id — developers cannot obtain prod credentials no matter how they change the YAML on a branch; ③ deploy-production Set when: manual as the confirmation step; ④ protect .gitlab-ci.yml. This satisfies “developers cannot publish on their own.” If you need a formal record of “second-person approval,” you need Premium deployment approvals (you can request a trial first).
Verified instructional videos
No verified video on “GitLab multi-account promotion” was found.
Official documentation
- GitLab Docs: Protected environments (Premium)
- GitLab Docs: Deployment approvals (Premium)
- GitLab Docs: Protected tags
- ECR: Repository policies
Video storyboard (about 60 seconds)
Visual: an image digest travels like a package from the dev account to the prod account, with the seal on the package unchanged.
Narration: Build once, promote the same digest, and what you tested is what goes live.
Visual: three gates open in sequence: protected tags, AWS trust conditions, protected environment approval.
Narration: GitLab decides who can push a release tag; AWS decides whether the token came from a protected tag; the protected environment decides who can click deploy.
Visual: a developer edits the YAML to bypass the manual button, and the STS shield lights up red.
Narration: Editing the YAML cannot change the claims in the token, so AWS's check cannot be bypassed.
Module 7 · Troubleshooting Cloud Deployments
- Classify any cloud deployment failure into one of the four layers, and know the “first diagnostic command” for each layer.
- Know the three typical STS errors by heart:
Incorrect token audience(aud),Not authorized to perform sts:AssumeRoleWithWebIdentity(trust conditions),No OpenIDConnect provider found(provider). - Use CloudTrail, token claim decoding, and
iam simulate-principal-policyto locate problems, and distinguish IAM denials from explicit SCP denials.
What: the four-layer model
| Layer | Where it fails | Typical errors | First diagnostic step |
|---|---|---|---|
| ① GitLab token layer | Before STS is called | argument --web-identity-token: expected one argument; Invalid length for parameter RoleArn; ID token issuance is disabled … | Does the job have id_tokens? Do the variable scope and environment name match? Decode the claims |
| ② STS trust layer | assume-role-with-web-identity | InvalidIdentityToken: Incorrect token audience; No OpenIDConnect provider found …; AccessDenied: Not authorized to perform sts:AssumeRoleWithWebIdentity; Couldn't retrieve verification key … | Compare token claims with the trust policy; list-open-id-connect-providers |
| ③ IAM permissions layer | AWS calls after getting credentials | … is not authorized to perform: ecr:… / ecs:… / iam:PassRole; … with an explicit deny in a service control policy | aws iam simulate-principal-policy; check the assumed-role name in the error |
| ④ Service layer | AWS accepted the request, but the result is wrong | ECS tasks stopping, circuit-breaker rollbacks,Unauthorized/Forbidden (EKS), Lambda update conflicts | describe-services events,stoppedReason and aws logs tail |
Why: classify the layer before acting
The most common waste is “fixing at the wrong layer”: when you see Not authorized to perform sts:AssumeRoleWithWebIdentity add AdministratorAccess to the role. That does nothing, because permission policies only take effect once the trust policy passes. Conversely,is not authorized to perform: ecs:UpdateService means STS has already passed, so editing the trust policy is equally useless.
How: three diagnostic tools
- Decode the claims: the whoami-claims job from Module 2. Compare
aud,sub,project_idandref_protectedmust match the trust policy character for character (mind case and the/). - CloudTrail:
AssumeRoleWithWebIdentityevents (both successful and failed), and afterward, with session namegitlab-<project>-<pipeline>-<job>for every call initiated. Note that CloudTrail events usually lag by a few minutes. - Policy simulation:
aws iam simulate-principal-policy --policy-source-arn ROLE --action-names …; it evaluates identity policies,which may not cover every combination of organization SCPs, session policies, and resource policies. If the raw error contains “service control policy,” go to your organization administrator.
When: GitLab-specific pitfalls
- MR pipelines: the ref in sub is the source branch; MR pipelines from a fork run in the fork project by default,
project_path/project_idso the subs point at the fork — a good thing, since it cannot get your credentials. - Renaming or transferring the project: the value in the sub
project_pathchanges accordingly; project_id stays the same. If the trust policy uses both, update the sub. - Variables not reaching: environment-scoped variables only apply to jobs with a matching
environmentjob; protected variables are only available in pipelines for protected branches or tags. extendsvs.!referencedifferences:!reference [.aws-oidc, before_script]Only reuses scripts; does not bring overid_tokens.
InvalidIdentityToken: Incorrect token audience, raised before trust evaluation. ② “A wrong thumbprint causes failure” — for gitlab.com, AWS validates using trusted root CAs, so the thumbprint is not the issue; for self-managed instances, first check whether the endpoint is reachable from the public internet. ③ “No failure record in CloudTrail means STS was never called” — it may just be a delay, or you may be looking in the wrong region or account.Locate the layer by failure step
Interactive: diagnosis challenge (6 levels)
Each level shows a realistic job log; after you pick the root cause, it shows the layer and the fix.
Diagnostic command cheat sheet
| Layer | Command | What to look at |
|---|---|---|
| ① | whoami-claims job (decode payload) | aud, sub, project_id, ref_protected |
| ① | echo "env=$CI_ENVIRONMENT_NAME role=${AWS_ROLE_ARN:-<empty>}" | Whether variables are passed through |
| ② | aws iam list-open-id-connect-providers | Whether the role's account has the gitlab.com |
| ② | aws iam get-open-id-connect-provider --query ClientIDList | audience list |
| ② | aws iam get-role --query Role.AssumeRolePolicyDocument | trust conditions |
| ②③ | aws cloudtrail lookup-events --lookup-attributes AttributeKey=EventName,AttributeValue=AssumeRoleWithWebIdentity | errorCode, errorMessage |
| ③ | aws iam simulate-principal-policy | allowed / implicitDeny / explicitDeny |
| ④ | aws ecs describe-services … events,describe-tasks … stoppedReason,aws logs tail | Service behavior |
# ② Check the error from the most recent failed AssumeRoleWithWebIdentity aws cloudtrail lookup-events --region ca-central-1 \ --lookup-attributes AttributeKey=EventName,AttributeValue=AssumeRoleWithWebIdentity --max-results 5 \ --query 'Events[].CloudTrailEvent' --output text | jq -r 'select(.errorCode) | [.eventTime, .errorCode, .errorMessage] | @tsv' # ③ Simulate whether the CI role can PassRole and UpdateService aws iam simulate-principal-policy \ --policy-source-arn arn:aws:iam::$ACCOUNT_ID:role/gitlab-myapp-dev-deploy \ --action-names iam:PassRole ecs:UpdateService \ --resource-arns arn:aws:iam::$ACCOUNT_ID:role/myappTaskExecutionRole \ --query 'EvaluationResults[].[EvalActionName,EvalDecision]' --output table
2026-11-16T10:21:07Z AccessDenied Not authorized to perform sts:AssumeRoleWithWebIdentity ------------------------------------ | SimulatePrincipalPolicy | +-------------------+--------------+ | iam:PassRole | allowed | | ecs:UpdateService| implicitDeny| +-------------------+--------------+
The second line shows implicitDeny because --resource-arns you only supplied the execution role, and the resource for UpdateService (the service ARN) doesn't match. When simulating, give each action its own resource, or run two separate calls.
Lab 7: Deliberately create three failures and fix them (about 8 minutes)
.aws-oidc , change aud to https://gitlab.com and push.
An error occurred (InvalidIdentityToken) when calling the AssumeRoleWithWebIdentity operation: Incorrect token audience ERROR: Job failed: exit code 254
Layer ② (provider audience). Fix: change back to sts.amazonaws.com. Think about it: if you chose to add https://gitlab.com to the provider audience, which trust condition would you run into? (Answer: gitlab.com:aud, it becomes Not authorized.)
ref:main to ref:master:
sed 's/ref:main/ref:master/' trust-dev.json > /tmp/bad.json aws iam update-assume-role-policy --role-name gitlab-myapp-dev-deploy --policy-document file:///tmp/bad.json
Rerun the job → AccessDenied … Not authorized to perform sts:AssumeRoleWithWebIdentity. After confirming with the CloudTrail command, restore the original trust-dev.json (or the one from Module 6 trust-dev3.json).
ecs-deploy the PassRole statement in the inline policy, then rerun deploy-dev:
An error occurred (AccessDeniedException) when calling the RegisterTaskDefinition operation: User: arn:aws:sts::111122223333:assumed-role/gitlab-myapp-dev-deploy/gitlab-12345678-… is not authorized to perform: iam:PassRole on resource: arn:aws:iam::111122223333:role/myappTaskExecutionRole …
Layer ③. Note that the earlier get-caller-identity succeeded — that is the evidence that layer ② passed. Restore the policy.
Case 1: All deployments fail after the project is moved to a new group
Problem: The project moved from mygroup-lab/myapp to platform/myapp, and deployments fail with Not authorized. Root cause: The project_path in the sub changed; project_id did not. Fix: Update the sub condition; the long-term fix is to customize the sub claim to begin with project_id (ci_id_token_sub_claim_components), so path changes no longer affect trust.
Case 2: SCP denies regions other than ca-central-1
Problem: The same role shows allowed in local simulation, but ECR calls in the job fail with … with an explicit deny in a service control policy. Root cause: The job image sets AWS_DEFAULT_REGION=us-east-1 (which overrides the project variable), and the organization SCP allows only ca-central-1. Fix: Consistently define it in .gitlab-ci.yml at the top level as AWS_DEFAULT_REGION: ca-central-1, and check variable precedence.
Case 3: After self-managed GitLab moved to a private network, all OIDC failed
Problem: The self-managed instance was moved to a private network, and all jobs fail with Couldn't retrieve verification key from your identity provider. Root cause: STS cannot reach /.well-known/openid-configuration and JWKS. Fix: Following the GitLab docs, publish the discovery document and JWKS to a tightly protected public location, set a custom issuer URL, and run ci:validate_id_token_configuration the Rake task to verify; also update all cloud provider URLs and the condition key prefixes.
Interactive troubleshooting tree
Start with “which step failed,” choose step by step, until you get the diagnostic and fix commands.
Additional: GitLab-side errors
ID token issuance is disabled in CI because a project path in the sub claim was previously used by a different project.
Cause: The project path used in the sub previously belonged to another project, so GitLab refuses to issue tokens to prevent “inheriting” the old project's cloud trust. Fix: Use the project API to change ci_id_token_sub_claim_components to begin with project_id (e.g., ["project_id","ref_type","ref"]), and update the sub in all cloud trust policies.
This job could not start because it could not retrieve the needed artifacts (IMAGE_URI is empty)
Cause: The deploy job depends on the build-push artifact has expired, or needs the pipeline does not include build-push. Fix: Rerun the whole pipeline, or roll back to a previous revision on the ECS side.
1. List the audiences currently allowed by the gitlab.com OIDC provider.
aws iam get-open-id-connect-provider \ --open-id-connect-provider-arn arn:aws:iam::$ACCOUNT_ID:oidc-provider/gitlab.com --query ClientIDList
2. Check the stop reason for the most recently stopped myapp-dev task.
T=$(aws ecs list-tasks --cluster myapp-lab --service-name myapp-dev --desired-status STOPPED --query 'taskArns[0]' --output text) aws ecs describe-tasks --cluster myapp-lab --tasks $T --query 'tasks[0].[stoppedReason,containers[0].exitCode]'
Job log: aws sts get-caller-identity Successfully outputs the dev role; then aws ecs update-service fails with ServiceNotFoundException. In what order would you troubleshoot?
Layer ② has passed (the identity is correct), and layer ③ shows no AccessDenied, so the problem is the “call target”: ① the job's region (AWS_DEFAULT_REGION) is ca-central-1; ② are the cluster and service name variables correct; ③ is the credential's account the expected one (in a multi-account setup, is the variable scope misconfigured); ④ has the service been deleted or not yet created (deploy jobs do not create services).
Instructional video
No “GitLab → AWS OIDC troubleshooting” video verified via oEmbed was found. The talk below covers token claims and trust conditions and can help you understand layer ②.
Official documentation
- GitLab Docs: AWS OIDC (including Troubleshooting)
- GitLab Docs: ID tokens (including Troubleshooting)
- IAM: Troubleshoot IAM roles
- ECS: Stopped task error codes
Video storyboard (about 60 seconds)
Visual: a four-story building, each floor with a sign: token, trust, permissions, service.
Narration: When a cloud deployment fails, first ask: which step failed?
Visual: in the log, “Incorrect token audience” points to the “audience” window on the second floor, and “Not authorized” points to the “trust conditions” window on the second floor.
Narration: A wrong audience means the token is invalid, and unmet conditions mean you are not allowed to assume the role; both are at the STS layer, so adding permissions won't help.
Visual: the green light for a successful get-caller-identity turns on, and an arrow points to PassRole on the third floor.
Narration: If it fails after identity is confirmed, go to the permissions layer; if the API succeeds but the result is wrong, go to the service layer and check events and logs.
Module 8 · Cost, Cleanup, and Self-Check
- Describe the cost components of this lesson's lab (Fargate, public IPv4, ECR storage, logs, optional ALB/EKS) and the compute minutes for GitLab-hosted runners.
- Run the cleanup script in dependency order, and know which deletions will fail with
DependencyViolation/DeleteConflictand why. - Reclaim identity-related resources: IAM roles, OIDC providers (lab account only), GitLab CI/CD variables, protected tag rules, environments, agents and their tokens.
What: this lesson's cost components
| Item | Billing model | Scale in this lesson | How to stop billing |
|---|---|---|---|
| Fargate task | vCPU-seconds + GB-seconds (per second, 1-minute minimum) | 0.25 vCPU / 0.5 GB × 1–2 tasks, a few cents per hour | Delete the service (or set desiredCount=0) |
| Public IPv4 address | Billed hourly per address | One per task | Released after the task stops |
| ECR storage | Per GB-month | myapp image about 100–200 MB | Delete the repository / lifecycle policy |
| CloudWatch Logs | Ingestion + storage | Very little (3-day retention) | Delete the log group |
| ALB (created by Express Mode) | Hourly fee + LCU | Zero if not created | Delete the Express service / ALB |
| EKS cluster (optional) | Cluster hourly fee + nodes | This lesson is read-only, nothing created | Clean up per K8s Lesson 7 |
| IAM, STS, OIDC providers | Free | 0 | but delete them to remove the attack surface |
| GitLab-hosted runners | Compute minutes (Free tier has a monthly quota; see Lesson 2) | A few minutes per pipeline (DinD builds take the longest) | Disable pipelines/scheduled jobs when not needed |
Why: cleanup order matters
AWS resources depend on each other: a service holds tasks → tasks hold ENIs → ENIs hold security groups; a role has policies attached → before deleting the role, delete inline policies and detach managed policies. Doing it in the wrong order fails with DependencyViolation or DeleteConflict. Identity resources (roles, providers, GitLab variables) cost nothing, but they are the most dangerous leftovers: a deploy role you forgot to delete, combined with a mutable path condition, could be exploited years later by someone who re-registers the same path.
How: recommended order
- Stop billing: ECS service → cluster; Lambda function; (optional) Express service, EKS resources.
- Delete data: ECR repository (
--force), log groups. - Delete networking: security groups (wait for ENIs to be released).
- Reclaim identities: EKS access entries / agent; IAM roles (policies first, then roles); OIDC providers (lab account only).
- GitLab: delete
AWS_ROLE_ARN/AWS_ACCOUNT_IDvariables, protected tag rules, stop and delete environments, delete the agent (its tokens are revoked along with it), delete test tags and releases.
No OpenIDConnect provider found. ③ “Setting desiredCount to 0 stops all charges” — task costs stop, but ECR, logs, and the ALB (if any) keep billing.Cleanup dependency graph
Interactive: cost estimator (order-of-magnitude estimate)
Unit prices are illustrative values near ca-central-1, for order-of-magnitude judgment only; the AWS Pricing Calculator is authoritative.
Cleanup commands
| Command | Notes |
|---|---|
aws ecs delete-service --cluster C --service S --force | No need to scale desired count to 0 first |
aws ecs wait services-inactive | Wait for the service to be fully deleted before deleting the cluster |
aws ecr delete-repository --repository-name myapp --force | Delete together with the images |
aws iam list-role-policies / list-attached-role-policies | List the policies before deleting the role |
aws iam delete-open-id-connect-provider | Lab account only |
aws resourcegroupstaggingapi get-resources --tag-filters Key=course,Values=gitlab-part4 | Find leftovers by tag |
glab variable delete KEY --scope ENV | Delete scoped variables |
Lab 8: One-command cleanup script (about 5 minutes)
source ~/gitlab-part4.env
set -x
for S in myapp-dev myapp-prod; do aws ecs delete-service --cluster myapp-lab --service $S --force >/dev/null 2>&1; done
aws ecs wait services-inactive --cluster myapp-lab --services myapp-dev myapp-prod 2>/dev/null
aws ecs delete-cluster --cluster myapp-lab >/dev/null
for TD in $(aws ecs list-task-definitions --family-prefix myapp --query 'taskDefinitionArns[]' --output text); do
aws ecs deregister-task-definition --task-definition $TD >/dev/null; done
aws lambda delete-function --function-name myapp-fn 2>/dev/null
aws ecr delete-repository --repository-name myapp --force >/dev/null
aws logs delete-log-group --log-group-name /ecs/myapp
aws logs delete-log-group --log-group-name /aws/lambda/myapp-fn 2>/dev/null
sleep 30; aws ec2 delete-security-group --group-id $TASK_SG
for R in gitlab-myapp-dev-deploy gitlab-myapp-prod-deploy myappTaskExecutionRole myapp-fn-exec; do
for P in $(aws iam list-role-policies --role-name $R --query 'PolicyNames[]' --output text 2>/dev/null); do
aws iam delete-role-policy --role-name $R --policy-name $P; done
for A in $(aws iam list-attached-role-policies --role-name $R --query 'AttachedPolicies[].PolicyArn' --output text 2>/dev/null); do
aws iam detach-role-policy --role-name $R --policy-arn $A; done
aws iam delete-role --role-name $R 2>/dev/null
done
# Lab account only, and only after confirming no other role trusts it:
aws iam delete-open-id-connect-provider --open-id-connect-provider-arn arn:aws:iam::$ACCOUNT_ID:oidc-provider/gitlab.com
set +x
aws resourcegroupstaggingapi get-resources --tag-filters Key=course,Values=gitlab-part4 --query 'ResourceTagMappingList[].ResourceARN'
[]
The security group fails with DependencyViolation , which means the task ENI has not been released yet. Wait a moment, then run the final delete again. The tagging API may have a short delay for deleted resources.
glab variable delete AWS_ROLE_ARN --scope dev
glab variable delete AWS_ROLE_ARN --scope production
glab variable delete AWS_ACCOUNT_ID --scope dev
glab variable delete AWS_ACCOUNT_ID --scope production
glab api -X DELETE "projects/:id/protected_tags/v%2A"
# An environment must be stopped before it can be deleted
for E in $(glab api "projects/:id/environments" | jq -r '.[] | select(.name|test("^(dev|production|dev-eks|dev-lambda)$")) | .id'); do
glab api -X POST "projects/:id/environments/$E/stop" >/dev/null
glab api -X DELETE "projects/:id/environments/$E"
done
glab release delete v1.1 --with-tag --yes
If you installed the GitLab agent: first helm uninstall eks-lab -n gitlab-agent-eks-lab, then, in Operate → Kubernetes clusters delete the agent (its token is invalidated along with it), and delete the .gitlab/agents/eks-lab/ directory.
aws iam list-roles --query "Roles[?starts_with(RoleName,'gitlab-myapp')]" is empty; the project CI/CD variables no longer contain any AWS-related entries.Case 1: The lab account's bill three months later
Problem: After the course ended, only the ECS service was deleted; the ALB created by the Express Mode lab kept running, and three months later the bill showed unexpected charges. Fix: Tag all lab resources consistently with course tags, use the tagging API after the course to find leftovers, and set up budget alerts before the lab.
Case 2: Deleted an “unused” OIDC provider
Problem: Someone deleted the gitlab.com provider while cleaning up a shared account, and deployments for more than a dozen teams failed at once with No OpenIDConnect provider found. Fix: The provider is managed by the platform team with IaC, and an IAM deny policy is added to prevent accidental deletion; application teams manage only their own roles.
Case 3: A former employee's personal project can still deploy
Problem: An audit found a role that trusts a project in a former employee's personal namespace; the employee has left, but the role remains. Fix: Regularly use IAM Access Analyzer and CloudTrail to find “roles unused for 90 days” and clean them up; deploy roles should trust only projects under an organization group (add a namespace_id condition).
Common errors and fixes
An error occurred (DeleteConflict) when calling the DeleteRole operation: Cannot delete entity, must delete policies first.
Fix: First remove delete-role-policy (inline) and detach-role-policy (managed), see the cleanup script.
An error occurred (DependencyViolation) when calling the DeleteSecurityGroup operation: resource sg-… has a dependent object
Cause: The task ENI has not been released yet. Fix: Wait for the service to be fully deleted, then retry; aws ec2 describe-network-interfaces --filters Name=group-id,Values=$TASK_SG check what is holding it.
An error occurred (ClusterContainsServicesException) when calling the DeleteCluster operation
Cause: The cluster still has services (including ones in DRAINING state). Fix:aws ecs wait services-inactive before deleting the cluster.
Environment cannot be deleted: Environment must be stopped before it can be deleted
Fix: First call the environment stop API (or click “Stop” in the UI), then delete it.
1. Find all resources in the account tagged with course=gitlab-part4.
aws resourcegroupstaggingapi get-resources --tag-filters Key=course,Values=gitlab-part4 \ --query 'ResourceTagMappingList[].ResourceARN' --output text
2. List all roles that trust the gitlab.com provider.
aws iam list-roles --query "Roles[?contains(to_string(AssumeRolePolicyDocument), 'oidc-provider/gitlab.com')].RoleName" --output text
The platform team wants to roll out this lesson's approach to 50 projects. Which resources should be centrally managed, and which should be handed to project teams?
Centrally managed (platform IaC): the OIDC provider in each account, role naming conventions and permissions boundaries, shared ECR and repository policies, GitLab-side CI/CD components (encapsulating .aws-oidc and deployment logic), protected environment rule templates, cost tags and budgets. Project teams: their own deploy roles (within the permissions boundary; the trust policy must include project_id), task definition templates, environment-scoped variables. Regularly audit unused roles and overly broad wildcard trust.
Instructional video
No verified video on “cleaning up AWS lab resources” was found; please refer to the documentation and storyboard below.
Official documentation
- AWS Fargate Pricing
- Amazon VPC Pricing (public IPv4)
- AWS Pricing Calculator
- GitLab Docs: Environments (stopping and deleting)
Video storyboard (about 45 seconds)
Visual: a meter is spinning; the ECS task, public IP, and ECR icons flash.
Narration: Labs are cheap; forgetting to clean up is what gets expensive.
Visual: icons turn off in order: service, cluster, repository, logs, security group.
Narration: Stop billing first, then delete in dependency order.
Visual: the role, provider, and GitLab variables are removed one by one from a key ring.
Narration: Reclaim identities last. A role that costs nothing is the most dangerous leftover.
Command cheat sheet
aws iam create-open-id-connect-provider --url https://gitlab.com --client-id-list sts.amazonaws.com aws iam get-open-id-connect-provider --open-id-connect-provider-arn arn:aws:iam::ACCT:oidc-provider/gitlab.com aws iam add-client-id-to-open-id-connect-provider --open-id-connect-provider-arn ARN --client-id AUD aws iam create-role --role-name R --assume-role-policy-document file://trust.json --max-session-duration 3600 aws iam update-assume-role-policy --role-name R --policy-document file://trust.json
id_tokens:
GITLAB_OIDC_TOKEN:
aud: sts.amazonaws.com
# Form A
aws_sts_output=$(aws sts assume-role-with-web-identity --role-arn "$AWS_ROLE_ARN"
--role-session-name "gitlab-$CI_PROJECT_ID-$CI_PIPELINE_ID-$CI_JOB_ID"
--web-identity-token "$GITLAB_OIDC_TOKEN" --duration-seconds 3600
--query 'Credentials.[AccessKeyId,SecretAccessKey,SessionToken]' --output text)
# Form B
echo "$GITLAB_OIDC_TOKEN" > /tmp/t; export AWS_WEB_IDENTITY_TOKEN_FILE=/tmp/t"StringEquals": {
"gitlab.com:aud": "sts.amazonaws.com",
"gitlab.com:project_id": "12345678",
"gitlab.com:ref_protected": "true"
},
"StringLike": {
"gitlab.com:sub": "project_path:mygroup-lab/myapp:ref_type:tag:ref:v*"
}
Self-managed / Dedicated: only supports <host>:sub and <host>:aud.
aws ecr create-repository --repository-name myapp --image-tag-mutability IMMUTABLE \ --image-scanning-configuration scanOnPush=true aws ecr get-login-password | docker login --username AWS --password-stdin ACCT.dkr.ecr.ca-central-1.amazonaws.com aws ecr describe-images --repository-name myapp --image-ids imageTag=TAG --query 'imageDetails[0].imageDigest' aws ecr wait image-scan-complete --repository-name myapp --image-id imageTag=TAG aws ecr put-image --repository-name myapp --image-tag 1.1 --image-manifest "$MANIFEST"
aws ecs register-task-definition --cli-input-json file://td.json --query taskDefinition.taskDefinitionArn aws ecs update-service --cluster C --service S --task-definition ARN aws ecs wait services-stable --cluster C --services S aws ecs describe-services --cluster C --services S \ --query 'services[0].deployments[?status==`PRIMARY`]|[0].[taskDefinition,rolloutState]' aws ecs update-service --cluster C --service S --task-definition myapp:6 # rollback
# GitLab agent kubectl config use-context mygroup-lab/myapp:eks-lab # access entry aws eks create-access-entry --cluster-name X --principal-arn ROLE_ARN aws eks associate-access-policy --cluster-name X --principal-arn ROLE_ARN \ --policy-arn arn:aws:eks::aws:cluster-access-policy/AmazonEKSEditPolicy \ --access-scope type=namespace,namespaces=myapp aws eks update-kubeconfig --name X
aws lambda update-function-code --function-name F --zip-file fileb://fn.zip --publish --query Version
aws lambda wait function-updated-v2 --function-name F
aws lambda update-alias --function-name F --name live --function-version 6 \
--routing-config '{"AdditionalVersionWeights":{"7":0.1}}'environment: { name: production, deployment_tier: production }
environment: { name: dev, action: prepare } # only borrows variables, does not record a deployment
resource_group: aws-production
artifacts: { reports: { dotenv: build.env } }
before_script: [ !reference [.aws-oidc, before_script] ] # does not include id_tokens!
glab variable set AWS_ROLE_ARN --scope production --value ARN glab api -X POST "projects/:id/protected_tags" -f name='v*' -f create_access_level=40 glab ci trace JOB
Error → layer → fix
| Error | Layer | Fix |
|---|---|---|
argument --web-identity-token: expected one argument | ① Token | Add id_tokens; do not use CI_JOB_JWT_V2 |
Invalid length for parameter RoleArn, value: 0 | ① Token/variables | Environment name matches variable scope |
InvalidIdentityToken: Incorrect token audience | ② STS | id_tokens aud ∈ provider audience list |
InvalidIdentityToken: No OpenIDConnect provider found in your account for https://gitlab.com | ② STS | Create the provider in the role's account |
AccessDenied: Not authorized to perform sts:AssumeRoleWithWebIdentity | ② STS | sub / project_id / ref_protected / aud conditions match the claims |
InvalidIdentityToken: Couldn't retrieve verification key … | ② STS | For self-managed instances, the discovery endpoint and JWKS must be publicly reachable |
is not authorized to perform: iam:PassRole | ③ IAM | Add PassRole + iam:PassedToService |
Waiter ServicesStable failed / Verify mismatch | ④ Service | Check service events, stoppedReason, logs |
You must be logged in to the server (Unauthorized) | ④ EKS | access entries / agent context |
Capstone lab + final quiz
You are a platform engineer for mygroup-lab. Your task is to move myapp's release process from “storing access keys in the pipeline and manually running docker push” to: in GitLab CI/CD,store no AWS keys; merges to main auto-deploy to dev; only protected tags pushed by a Maintainer v* can deploy to production, and must use the exact same image digest as dev; a failed deployment must turn the pipeline red.
https://gitlab.com (audience sts.amazonaws.com); gitlab-myapp-dev-deploy (trust trust-dev3.json) and gitlab-myapp-prod-deploy (trust trust-prod.json), each attaching ecr-push and ecs-deploy (service ARNs are for myapp-dev and myapp-prod, respectively).v* (Maintainer); environment-scoped variables AWS_ROLE_ARN,AWS_ACCOUNT_ID (dev / production); (optional on Premium) protected production environment + 1 approver.myapp-dev and myapp-prod two services (the same cluster is fine), each with circuit-breaker rollback enabled..gitlab-ci.yml and ecs/taskdef.json:
stages: [build, deploy]
variables:
AWS_DEFAULT_REGION: ca-central-1
IMAGE_TAG: sha-$CI_COMMIT_SHORT_SHA
.aws-oidc:
image: { name: amazon/aws-cli:2.40.4, entrypoint: [""] }
id_tokens:
GITLAB_OIDC_TOKEN:
aud: sts.amazonaws.com
before_script:
- >
aws_sts_output=$(aws sts assume-role-with-web-identity
--role-arn "${AWS_ROLE_ARN}"
--role-session-name "gitlab-${CI_PROJECT_ID}-${CI_PIPELINE_ID}-${CI_JOB_ID}"
--web-identity-token "${GITLAB_OIDC_TOKEN}"
--duration-seconds 3600
--query 'Credentials.[AccessKeyId,SecretAccessKey,SessionToken]'
--output text)
- export $(printf "AWS_ACCESS_KEY_ID=%s AWS_SECRET_ACCESS_KEY=%s AWS_SESSION_TOKEN=%s" $aws_sts_output)
- test "$(aws sts get-caller-identity --query Account --output text)" = "$AWS_ACCOUNT_ID"
- export ECR_REGISTRY="${ECR_ACCOUNT_ID:-$AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com"
.ecs-deploy:
extends: .aws-oidc
script:
- sed "s#__IMAGE_URI__#${IMAGE_URI}#; s#111122223333:role#${AWS_ACCOUNT_ID}:role#" ecs/taskdef.json > td.json
- TD_ARN=$(aws ecs register-task-definition --cli-input-json file://td.json --query taskDefinition.taskDefinitionArn --output text)
- aws ecs update-service --cluster $CLUSTER --service $SERVICE --task-definition "$TD_ARN" >/dev/null
- aws ecs wait services-stable --cluster $CLUSTER --services $SERVICE
- |
OUT=$(aws ecs describe-services --cluster $CLUSTER --services $SERVICE \
--query 'services[0].deployments[?status==`PRIMARY`]|[0].[taskDefinition,rolloutState]' --output text)
echo "Verify: want=${TD_ARN##*/} got=$(echo "$OUT" | cut -f1 | sed 's#.*/##') state=$(echo "$OUT" | cut -f2)"
[ "$(echo "$OUT" | cut -f1)" = "$TD_ARN" ] && [ "$(echo "$OUT" | cut -f2)" = "COMPLETED" ]
build-push:
stage: build
extends: .aws-oidc
image: docker:29
services: [docker:29-dind]
variables: { DOCKER_TLS_CERTDIR: "/certs" }
environment: { name: dev, action: prepare }
rules:
- if: $CI_COMMIT_BRANCH == "main" || $CI_COMMIT_TAG =~ /^v\d+\.\d+/
before_script:
- apk add --no-cache aws-cli >/dev/null
- !reference [.aws-oidc, before_script]
script:
- aws ecr get-login-password | docker login --username AWS --password-stdin "$ECR_REGISTRY"
- |
if DIGEST=$(aws ecr describe-images --repository-name myapp --image-ids imageTag=$IMAGE_TAG \
--query 'imageDetails[0].imageDigest' --output text 2>/dev/null); then
echo "reuse $DIGEST"
else
docker build --pull -t "$ECR_REGISTRY/myapp:$IMAGE_TAG" .
docker push "$ECR_REGISTRY/myapp:$IMAGE_TAG"
DIGEST=$(aws ecr describe-images --repository-name myapp --image-ids imageTag=$IMAGE_TAG \
--query 'imageDetails[0].imageDigest' --output text)
fi
- echo "IMAGE_URI=$ECR_REGISTRY/myapp@$DIGEST" >> build.env
artifacts: { reports: { dotenv: build.env } }
deploy-dev:
stage: deploy
extends: .ecs-deploy
needs: [build-push]
environment: { name: dev, deployment_tier: development }
resource_group: aws-dev
variables: { CLUSTER: myapp-lab, SERVICE: myapp-dev }
rules:
- if: $CI_COMMIT_BRANCH == "main"
deploy-production:
stage: deploy
extends: .ecs-deploy
needs: [build-push]
environment: { name: production, deployment_tier: production }
resource_group: aws-production
variables: { CLUSTER: myapp-lab, SERVICE: myapp-prod }
rules:
- if: $CI_COMMIT_TAG =~ /^v\d+\.\d+/
when: manual
In single-account simulation, the AWS_ACCOUNT_ID is the same; in a real multi-account setup, add a variable for the production scope ECR_ACCOUNT_ID=111122223333 (the account hosting the shared ECR), and configure the Module 6 repository policy. For brevity, pushing to the GitLab Container Registry and promote-tag (see Modules 3 and 6).
curl http://<task public IP>:5000/healthz returns ok.v0.0-test and manually runs deploy-production → Not authorized (delete that tag); a Maintainer publishes v1.1 → manually run deploy-production → green; confirm that the myapp-prod and myapp-dev task definitions reference the same digest.Open-ended self-check (6 questions)
1. Explain in your own words: why can't GitLab's prod trust policy use “environment:production” the way GitHub does? What do you use instead?
GitLab's default sub does not include the environment name, and environment the claim is not an AWS-supported condition key. Alternative: protected v* tag (sub in tag form) + gitlab.com:ref_protected = true + project_id, plus a protected environment and approvals on the GitLab side (Premium). For advanced use, you can customize the sub to include deployment_tier/environment_protected (18.7+; print it first to confirm the format).
2. For aud, do you use sts.amazonaws.com or https://gitlab.com? Which three places must you keep consistent for each?
Either works; the key is that the three places match: id_tokens 's aud, the IAM provider's audience list (client ID), and the trust policy's gitlab.com:aud. This lesson uses sts.amazonaws.com, because the GitLab docs suggest that aud represents “the service that validates the token.”
3. Form A vs. Form B (AWS_WEB_IDENTITY_TOKEN_FILE) — which scenarios suit each?
A is transparent and easy to troubleshoot, suited for teaching and short jobs; B is concise, and the SDK can automatically renew credentials using a still-valid ID token when they are about to expire, suited for long jobs and tools like Terraform.
4. Why does a deploy job need a Verify step? Give an example of what goes wrong without it.
After circuit-breaker rollback, the service is “stable” on the old revision, so the wait services-stable succeeds, the pipeline turns green, but the new version never went live. Verify compares the PRIMARY taskDefinition with the ARN registered in this run and requires COMPLETED.
5. With a private EKS cluster and GitLab.com-hosted runners, how would you deploy?
Install the GitLab agent in the cluster (it only needs outbound access to kas.gitlab.com), and use ci_access to authorize the project; the job runs kubectl config use-context path:agent; or use GitOps (Flux), where the cluster pulls. Neither requires exposing an API endpoint, nor does CI need to hold AWS credentials to access Kubernetes.
6. After the course, which “free” resources must still be deleted? Why?
IAM deploy roles, OIDC providers (lab account), and the GitLab AWS_ROLE_ARN variables, protected tag rules, agents and their tokens. They cost nothing, but they form an attack surface: trust based on a mutable path can be exploited after the path is re-registered.
Sources and version notes
Source
| Topic | Source | Verified on | Facts used in this lesson |
|---|---|---|---|
| GitLab → AWS OIDC | docs.gitlab.com/ci/cloud_services/aws | 2026-11-16 | The provider URL is the instance address and must be publicly reachable; id_tokens + assume-role-with-web-identity examples (step-by-step, with guaranteed exit codes); GitLab.com condition keys (sub, aud, namespace_id, project_id, user_*, ref_protected, pipeline_source, runner_environment); self-managed/Dedicated supports only sub and aud; three types of troubleshooting; the S3 alternative for non-public instances and security warnings |
| ID tokens | docs.gitlab.com/ci/secrets/id_token_authentication | 2026-11-16 | claims list; default sub format; default aud is the instance domain; tokens expire after the job timeout (or 5 minutes); RS256; since 18.7, sub can include ref_protected / environment_protected / deployment_tier; troubleshooting “ID token issuance is disabled” |
| sub customization and deprecation | docs.gitlab.com/ci/cloud_services | 2026-11-16 | ci_id_token_sub_claim_components; CI_JOB_JWT/CI_JOB_JWT_V2 removed in 17.0 |
| IAM condition keys | IAM: Available keys for AWS OIDC federation | 2026-11-16 | GitLab.com tab: gitlab.com:namespace_id,gitlab.com:project_id etc. are only for GitLab.com SaaS; paths can be re-registered, so it is recommended to add a stable ID |
| GitLab agent | CI/CD workflow · Install | 2026-11-16 | context name <path>:<agent>; $KUBECONFIG; ci_access 500 each for projects/groups; access_as simulation requires Premium; KAS kas.gitlab.com; Helm repository charts.gitlab.io, chart gitlab/gitlab-agent; glab cluster agent bootstrap |
| Environments and approvals | Environments · Protected environments · Deployment approvals | 2026-11-16 | deployment_tier values; protected environments and deployment approvals are Premium/Ultimate; the job still needs to be run manually after approval |
| GitLab version | docs.gitlab.com/releases | 2026-11-16 | GitLab 19 series; the latest release is 19.5 (patch 19.5.6, 2026-11-16); 19.6 has not been released yet |
| ECS / ECR / Express Mode / App Runner | AWS official documentation (circuit breaker, Express Mode getting started, ECR authentication and tag immutability, App Runner availability change) | 2026-11-16 | circuit breaker threshold (50%, minimum 3, maximum 200, customizable); Express Mode CLI parameters; App Runner is not accepting new customers |
| Tool versions | Docker Hub (docker, amazon/aws-cli, alpine/k8s tags), dl.k8s.io/release/stable.txt, helm/helm releases | 2026-11-16 | docker:29/29-dind,amazon/aws-cli:2.40.4,alpine/k8s:1.37.2, Kubernetes v1.37.2, Helm v4.3.2 |
| Corresponding courses | GitHub Lesson 4 · Azure DevOps Lesson 4 | — | How the same topic is handled in GitHub Actions / Azure Pipelines |
Video verification notes
All listed videos had their title and channel verified on 2026-11-16 via YouTube oEmbed (https://www.youtube.com/oembed?url=…&format=json), confirming the title and channel:
- GitLab at AWS re:Inforce 2023 - Secure GitLab CD pipelines to AWS w/ Open ID Federation, OIDC & JWT — GitLab Unfiltered (referenced in the GitLab AWS OIDC docs)
- GitLab CI CD Tutorial for Beginners [Crash Course] — TechWorld with Nana
- Deploying a Modern Application Stack to AWS Fargate with Amazon ECS - AWS Online Tech Talks — AWS Developers
- Serverless for container fans via Amazon ECS and AWS Lambda — Bret Fisher
- AWS EKS - Create Kubernetes cluster on Amazon EKS | the easy way — TechWorld with Nana
- EKS Pod Identity vs IRSA | Securely Connect Kubernetes Pods to AWS Services — Containers from the Couch
- Amazon EKS Auto Mode | Fully Automated Kubernetes Clusters — AWS Developers
No verified videos were found for the topics (ECR immutable tags + GitLab, ECS circuit breaker + GitLab, GitLab agent + EKS, multi-account promotion, cleanup), so storyboards are provided instead. Older recorded videos use CI_JOB_JWT_V2 or long-term keys; this lesson takes precedence.
Audio notes
The “Audio” tab uses the browser's built-in Web Speech API: Chinese narration uses a zh-CN voice, and English terms use an en-US voice. Without a Chinese voice pack, the narration script can still be read directly or passed to another TTS tool.
Known limitations
- When this lesson was written, we did not run these commands and pipelines in a real AWS account or GitLab.com project; all outputs are “examples” built from the official docs, and account numbers, project IDs, digests, and IPs are placeholder values.
- Starting with GitLab 18.7, sub can include
ref_protected,environment_protected, anddeployment_tier: the docs do not give complete concatenation examples for these components. This lesson covers them only as an advanced option and requires printing the claims before writing the trust policy. ref_protectedIn the docs' example payload, it appears as a string"false", while the table describes it as a boolean; this lesson writes the condition as a string"true"; check the actual output of the whoami job.- In the agent Helm installation,
config.kasAddress(wss://orgrpcs://kas.gitlab.com) follow the command generated by the GitLab UI; for the agent chart's default RBAC permissions, refer to the chart values. glabSubcommand output formats change between versions, so example output is for reference only. ECS Express Mode is a newer API, and its parameters are defined byaws ecs create-express-gateway-service help.- The cost estimator uses illustrative unit prices, for order-of-magnitude judgment only. For GitLab-hosted runner compute-minute quotas and free-tier verification requirements, see Lesson 2.