GitLab Hour 4: Moving to the Cloud (AWS)

Store no AWS access keys in GitLab; jobs use 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
GitLab.com · GitLab 19.xid_tokens · GITLAB_OIDC_TOKENAWS CLI v2Region ca-central-1Verified against official docs · 2026-11-16
Overall learning goals
  • 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’s id_tokens: GITLAB_OIDC_TOKEN: aud: sts.amazonaws.com, and the trust policy’s gitlab.com:aud,gitlab.com:sub,gitlab.com:project_id conditions.
  • Write working aws sts assume-role-with-web-identity snippets (variables AWS_ROLE_ARN), and also use the AWS SDK’s native AWS_WEB_IDENTITY_TOKEN_FILE way, 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 found and similar typical errors.

1-hour time allocation table

#TimeModuleCore contentAnimation / interactionLab (AWS account · ca-central-1)
0Before classWarm-up and AWS setupAWS CLI v2, lab identity, budget alerts, getting the GitLab project ID and group IDOIDC prerequisite self-checkaws sts get-caller-identity,glab api projects/:id
100–05AWS deployment architecture selectionECS Fargate / Express Mode / EKS / Lambda; current App Runner status; CI role ≠ runtime roleDecision toolclusters, log groups, execution roles
205–13OIDC federation: GitLab → IAMOIDC providers,id_tokens and aud,gitlab.com:sub formats, ID-type condition keys, two ways to exchange for credentialsCore animation: id_token → STS token exchange (including failure scenarios)Create the provider and role; the job prints claims and identity
313–21Build and push to ECRDinD,get-login-password, IMMUTABLE, scan on push, digest, lifecycle policiesTag vs digest push simulationCI push sha- tag
421–29Deploy to ECS on FargateRegister task definition, update service,wait services-stable, circuit-breaker rollback, Verify step,environment and resource_grouprolling deployment + circuit-breaker state machinePipeline deploys myapp-dev
529–37Deploy to EKS and LambdaGitLab agent (ci_access, kubecontext) vs EKS access entries; Lambda version and alias weightingLambda alias traffic shifting(optional) Lambda alias 10% canary
637–45Multi-account and environment promotionone provider per account, one role per environment, environment scope AWS_ROLE_ARN, protected tags + ref_protected, deployment approvalsTrust matrix evaluatorProd role trusts only protected tags
745–54Troubleshooting cloud deployments in practiceFour-layer model: token → STS trust → IAM permissions → service behavior; CloudTrailDiagnostic challenges + interactive troubleshooting treeIntentionally cause aud / sub errors and fix them
854–60Cost, cleanup and self-checkCost breakdown, cleanup order, reclaiming roles / providers / variables / agent tokensCost estimatorOne-click cleanup script
—After classCheat sheet · Capstone labid_tokens → STS → ECR (immutable) → ECS (dev automatic / prod tag + manual) → rollback → cleanupFinal quiz (12 questions)Capstone lab

Knowledge Coverage Matrix

Target skillsM1M2M3M4M5M6M7M8Key commands / keywordsLab
Choosing AWS compute services by scenario✓··✓✓··✓Decision tableM1
Keyless: id_tokens → STS temporary credentials·✓✓✓✓✓✓·id_tokens,aws sts assume-role-with-web-identityM2
write a minimal working trust policy (aud / sub / project_id)·✓···✓✓·aws iam create-roleM2 / M6
push immutable images and reference them by digest··✓✓✓✓✓·aws ecr get-login-password,docker pushM3
ECS deployment, waiting for stability, circuit-breaker rollback···✓·✓✓·aws ecs update-service,aws ecs wait services-stableM4 / capstone
EKS: GitLab agent or access entries····✓·✓·ci_access,aws eks create-access-entryM5 (reading)
Lambda versions / progressive alias rollout✓···✓···aws lambda update-alias --routing-configM5 (optional)
multi-account, environments and promotion·✓·✓·✓··environment:, environment-scoped variables, protected tagsCapstone
Locating cloud deployment faults·✓✓✓✓·✓·CloudTrail,describe-servicesM7
cost control and complete cleanup··✓····✓aws ecs delete-service --forceM8

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

TopicWhy it is not in this hourWhere to learn it
Dockerfile, multi-stage builds, ECS task definition fields and ALB detailsContainers are already covered in depth in the Docker course; this hour only covers how GitLab drives themDocker lesson 4 (AWS ECS / ECR / EKS)
EKS cluster creation, VPC CNI, Pod IdentityBelongs to Kubernetes platform operationsK8s lesson 7 (EKS)
Manage OIDC providers, roles and ECS resources with TerraformThis hour uses the CLI so every step is “visible”; production should use IaC insteadTerraform lesson 4 (AWS)
Pipeline syntax basics (rules,needs,extends, variables)Covered in lesson 2Lesson 2
Azure federated credentials (Entra workload identity)Covered in the previous lesson; this hour maps to it one-to-oneLesson 3 (Azure)
How the same topic is written in GitHub Actions / Azure PipelinesThis hour covers GitLab only; compare the others as neededGitHub lesson 4 (AWS) · Azure DevOps lesson 4
CI/CD components, security scanning, supply chain hardeningBelongs to the “production-grade GitLab CI” topicLesson 5

How to use this course material

10 pages per module
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.
Learning progress
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).
Chinese audio
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.
Cost and safety notes The labs in this hour incur small AWS charges (Fargate tasks, ECR storage, CloudWatch logs, public IPv4 addresses). With the minimum configuration in this hour (1–2 tasks of 0.25 vCPU / 0.5 GB, no ALB), running for 1 hour costs roughly USD 0.1; on the GitLab side, hosted runner compute minutes are used (see lesson 2 for the monthly Free tier quota). Forgetting to clean up is the real risk: please set a budget alert inBefore-class setupfirst, and after class run themodule 8 cleanup script. Prices should be checked against AWS Pricing Calculator as the authoritative source.
Version notes (verified 2026-11-16) GitLab.com runs GitLab 19.x (the latest released version is 19.5, patch 19.5.6; the 19.6 release notes page is labeled Upcoming); 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)

Prepare an AWS account you can experiment in safely, a lab identity and a budget alert, and get the numeric IDs of your GitLab project and group
Before class ≈ 10 minAWS CLI v2 · glab
Prerequisites
  • Completedlesson 2(pipelines, jobs,rules,extends, CI/CD variables, hosted runners) andlesson 3(id_tokens the 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 branch main). /healthz The app does not depend on Redis, and this hour does not deploy it, so seeing hits=N/A on 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 identityIAM rolecloud identity that a GitLab job “assumes”
Federated credential (issuer + subject + audience)IAM OIDC identity provider + role trust policy conditionsAWS splits “who to trust” into two layers: an account-level provider + role-level conditions
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://AzureADTokenExchangeaud 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_IDAWS_ROLE_ARN (+ AWS_DEFAULT_REGION)are not secrets, so CI/CD variables are fine for them
ACR / Container Apps / AKSECR / ECS Fargate / EKSImage 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"
}
What does sub look like? By default it is 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.

Environment self-check list

Module 1 · AWS deployment architecture selection

00:00 – 05:00 · First decide “how much the team is willing to operate”, then decide which set of APIs a GitLab job must call
5 minECS Fargate · Express ModeApp Runner no longer accepts new customers★★★★
Learning objectives
  • 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.
Prerequisite knowledge: The ECS object model from Docker lesson 4 (clusters, task definitions, services). Importance:★★★★

What: four main landing points

ECS on FargateECS Express ModeEKSLambda
What you deliverImage + task definition JSON + service configImage + two IAM roles (one API call)Image + Kubernetes manifests / Helm chartZip package or container image + function configuration
What AWS manages for youServers, scheduling, rolling deploymentsOn top of ECS, automatically creates an ALB (with TLS), auto scaling, networking, and loggingControl plane (Auto Mode also manages nodes)All servers and scaling; billed per request
How to deploy from a GitLab jobaws ecs register-task-definition + update-service + wait services-stableaws ecs create-express-gateway-service / update the service with the same namekubecontext injected by the GitLab agent, or aws eks update-kubeconfig + kubectl/helmaws lambda update-function-code --publish + update-alias
Core permissions the CI role needsecs:RegisterTaskDefinition,ecs:UpdateService,ecs:DescribeServices,iam:PassRoleCreate/update Express services + iam:PassRoleWith the agent: No AWS permissions needed; with access entries: eks:DescribeCluster + access entrieslambda:UpdateFunctionCode,PublishVersion,UpdateAlias
Typical starting costBilled per task vCPU / memory-secondExpress Mode itself is free; you pay only for the underlying resources (Fargate, ALB, etc.)Cluster hourly fee + nodes / FargateRequests + GB-seconds, with a free tier

Why: why the 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

RoleWho assumes itPurposeName in this hour
CI deploy roleGitLab job (via OIDC)Push images, register task definitions, update servicesgitlab-myapp-dev-deploy
Task execution roleECS agentPull ECR images, write CloudWatch logsmyappTaskExecutionRole
Task role / Pod Identity / Lambda execution roleYour application codeApp accesses S3, DynamoDB, etc.(not needed in this hour)
Common misconceptions① “Deploying to EKS only needs IAM permissions”: IAM only lets you call eks:DescribeCluster; whether you can kubectl apply depends on EKS access entries, or 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

StepGitLab (this hour)GitHub ActionsAzure Pipelines
Request OIDC tokenid_tokens: + audpermissions: id-token: writeService connection (workload identity federation)
Exchange for AWS credentialsaws sts assume-role-with-web-identityconfigure-aws-credentials ActionAWS Toolkit task / service connection
Seethis hourGitHub lesson 4Azure DevOps lesson 4

Architecture diagram: one identity chain, four landing points

GitLab CI/CD job id_tokens: GITLAB_OIDC_TOKENaud: sts.amazonaws.comHosted runner (DinD)Build → push → deploy JWT AWS STS AssumeRoleWithWebIdentityVerify iss / aud / sub→ temporary credentials (1h by default) ECRGetAuthorizationToken · push ECS (Fargate / Express)RegisterTaskDefinition · UpdateService EKSAccess entries or GitLab agent LambdaUpdateFunctionCode · UpdateAlias App RunnerNo longer accepting new customers → Express Mode Runtime identity (a separate matter) ECS: task execution role(pull images, write logs)ECS: task role (application)EKS: Pod Identity / IRSALambda: execution roleCI only needs iam:PassRole The CI role handles “deployment”; the runtime role handles “application access to AWS” Separating the two is key to least privilege; CI hands over the runtime role via iam:PassRole GitLab agent path: job → KAS → in-cluster agentk → K8s API (no AWS credentials or access entries needed)
Figure 1-1: the job talks to STS only once; after that, all deployment APIs use the same temporary credentials

Decision flow

Event-driven,≤ 15 minutes? Lambda Yes No Needs KubernetesAPI / CRD ecosystem? EKS + agent Yes No Want “one call to buildALB + TLS + scaling”? ECS Express Mode Yes No ECS on FargateTask definition + service (this hour’s main path) For new projects, do not choose App Runner (it no longer accepts new customers); migrate existing App Runner services to Express Mode following the official guide
Figure 1-2: simplified decision flow (real selection must also consider team skills, compliance and existing platforms)

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.

Start from the first question.
# Recommendation will appear here

Core commands: survey the “foundation” of your account

CommandPurposeNotes
aws ec2 describe-vpcs --filters Name=is-default,Values=trueFind the default VPCThis hour’s labs use the public subnets of the default VPC, which avoids NAT gateway costs
aws ecs create-cluster --cluster-name myapp-labCreate an ECS clusterThe cluster itself is free; the first use automatically creates the ECS service-linked role
aws service-quotas get-service-quota --service-code fargate --quota-code L-3032A538Check the Fargate On-Demand vCPU quotaNew accounts may have a low quota
aws apprunner list-servicesCheck whether this is an existing App Runner customerNew accounts are refused when creating services (see the official notice)
aws ecs create-express-gateway-service …Express Mode creates the full stack in one stepRequires 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)

Create the cluster and log group
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.

Create the task security group (allow port 5000 only from your IP)
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).

Create the task execution role (the ECS agent uses it to pull ECR images and write CloudWatch logs)
cat > ecs-tasks-trust.json <<'EOF'
{ "Version": "2012-10-17",
  "Statement": [{ "Effect": "Allow", "Principal": {"Service": "ecs-tasks.amazonaws.com"}, "Action": "sts:AssumeRole" }] }
EOF
aws iam create-role --role-name myappTaskExecutionRole --assume-role-policy-document file://ecs-tasks-trust.json
aws iam attach-role-policy --role-name myappTaskExecutionRole \
  --policy-arn arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy
Record variables, used in later modules and the capstone lab:
cat > ~/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.

Verifyaws 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.

Command-line tasks
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
Scenario analysis
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

▶
Deploying a Modern Application Stack to AWS Fargate with Amazon ECS - AWS Online Tech Talks — AWS Developers
English · overall architecture of Fargate and ECS, background for modules 1 and 4
▶
Serverless for container fans via Amazon ECS and AWS Lambda — Bret Fisher
English · comparing ECS and Lambda for running containers

Official docs

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.

Shot 1 · 0–15s
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.
Shot 2 · 15–35s
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.
Shot 3 · 35–60s
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.
or score ≥ 70% in the quiz

Module 2 · OIDC federation: GitLab → IAM

05:00 – 13:00 · an account-level “I trust the gitlab.com issuer”, plus a role-level “trust only this branch or tag of this project”
8 minid_tokens · GITLAB_OIDC_TOKENCI_JOB_JWT_V2 was removed in 17.0★★★★★
Learning objectives
  • Create an IAM OIDC identity provider (URL https://gitlab.com, audience sts.amazonaws.com), and explain why GitLab.com does not require a manually maintained thumbprint, and what a self-managed instance must meet.
  • Use id_tokens to request GITLAB_OIDC_TOKEN, so that aud matches the audience list of the IAM provider and the trust policy’s gitlab.com:aud condition: all three must agree.
  • Write a minimal trust policy with gitlab.com:sub (project_path:…:ref_type:…:ref:…) and gitlab.com:project_id conditions, 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-native AWS_ROLE_ARN + AWS_WEB_IDENTITY_TOKEN_FILE.
Prerequisites: lesson 3 id_tokens concepts; an IAM role = trust policy + permission policy. Importance:★★★★★ (all later modules in this hour depend on it)

What: three things

ObjectLocationPurposeKey value
IAM OIDC identity providerOne per AWS account (the same URL can only be created once within an account)Tells STS: “JWTs signed by this issuer can be trusted by roles in this account”URL https://gitlab.com; audience (client ID) sts.amazonaws.com; ARN arn:aws:iam::111122223333:oidc-provider/gitlab.com
IAM role + trust policyOne per project / environment (least privilege)Specifies which tokens may assume this rolePrincipal.Federated = provider ARN; Action = sts:AssumeRoleWithWebIdentity; Condition checks aud, sub, project_id
In the job, the id_tokens.gitlab-ci.yml job-level keywordmakes GitLab issue a JWT for the job and place it in a same-named variableGITLAB_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 AssumeRoleWithWebIdentity event records the token’s subject; the role session name is set to gitlab-<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

  1. The job declares id_tokens, and GitLab issues a JWT (RS256) at job start, as the CI/CD variable GITLAB_OIDC_TOKEN passed to the Runner. No declaration, no token.
  2. The token includes iss=https://gitlab.com,aud=sts.amazonaws.com (the value you wrote in id_tokens ),sub=project_path:mygroup-lab/myapp:ref_type:branch:ref:main plus project_id,namespace_id,ref_protected,environment,runner_environment and other claims.
  3. The script calls STS AssumeRoleWithWebIdentity (this call itself needs no AWS credentials), passing the RoleArn (variable AWS_ROLE_ARN), the token, a session name, and a duration.
  4. STS uses iss to find the account holding the role with an OIDC provider whose URL is https://gitlab.com , and fetches https://gitlab.com/.well-known/openid-configuration and the JWKS to verify the signature and validity period.
  5. STS checks aud whether it is in the provider’s audience (client ID) list.
  6. STS evaluates the trust policy conditions: gitlab.com:aud,gitlab.com:sub, and GitLab.com-only gitlab.com:project_id,gitlab.com:namespace_id and so on.
  7. After passing, it returns temporary credentials (ASIA… beginning with AccessKeyId, SecretAccessKey, SessionToken and Expiration). The script exports them as environment variables, and afterwards aws the 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)

Triggersub exampleNotes
Push to branch mainproject_path:mygroup-lab/myapp:ref_type:branch:ref:mainfor dev deployment
Push tag v1.1project_path:mygroup-lab/myapp:ref_type:tag:ref:v1.1for prod release (module 6)
Merge request pipeline (source branch feature/login)project_path:mygroup-lab/myapp:ref_type:branch:ref:feature/loginref 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:mainvia 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
The biggest difference from GitHub GitLab default sub does not include the environment name: when a job specifies 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 keyFrom claimPurpose
gitlab.com:aud / gitlab.com:subStandard claimSupported by all GitLab instances (self-managed uses <your hostname>:sub)
gitlab.com:project_idproject_idRecommended: unchanged on project rename or transfer, and IDs are never reused
gitlab.com:namespace_idnamespace_idLock to group (organization-level trust)
gitlab.com:ref_protectedref_protectedTrust only jobs from protected branches / tags
gitlab.com:user_id,:user_login,:user_email,:user_access_levelTriggering userRestrict by person (use sparingly; people change)
gitlab.com:pipeline_source,:runner_environmentPipeline source, runner typee.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 byGitLabAWS STS
LifetimeUntil 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 credentialsreports ExpiredToken; with the AWS_WEB_IDENTITY_TOKEN_FILE method, the SDK automatically renews using the still-valid ID token
Common misconceptions① “Once the OIDC provider is created, it is secure”: the provider only “trusts tokens issued by gitlab.com”, and on GitLab.com,any project can obtain such a token; the real boundary is the sub and project_id conditions in the role trust policy. ② “Matching sub with 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

GitLab.com (issuer) Job on Runner AWS STS + IAM ECR / ECS API ① job payload includes GITLAB_OIDC_TOKEN (id_tokens) ② AssumeRoleWithWebIdentity(RoleArn=$AWS_ROLE_ARN,WebIdentityToken, RoleSessionName, DurationSeconds) ③ GET https://gitlab.com/.well-known/openid-configuration → jwks_uri (cached) ④ find this account’s URL=gitlab.comprovider · verify signature · exp⑤ aud ∈ audience list?⑥ trust policy: aud / sub /project_id conditions ⑦ Credentials {ASIA…, SessionToken, Expiration} ⑧ SigV4-signed calls: ecr:GetAuthorizationToken, ecs:UpdateService … CloudTrail: the STS side records AssumeRoleWithWebIdentity; the service side records calls made as assumed-role/ROLE/gitlab-PROJ-PIPE-JOB
Figure 2-1: the token is issued by GitLab along with the job and flows only between the Runner and STS; business APIs are called only after the temporary credentials are obtained

Trust policy anatomy

"Principal": {"Federated": "arn:aws:iam::111122223333:oidc-provider/gitlab.com"} "Action": "sts:AssumeRoleWithWebIdentity" "Condition": {"StringEquals": { "gitlab.com:aud": "sts.amazonaws.com", "gitlab.com:sub": "project_path:mygroup-lab/ myapp:ref_type:branch:ref:main", "gitlab.com:project_id": "12345678" }} Issuer: the already-registeredOIDC provider gitlab.com Intended for: aud = sts.amazonaws.com(= aud in id_tokens = provider audience) Who: sub = the project path of(which branch/tag) Anti-hijacking: project_id does not change on rename,and is never reused (GitLab.com only)
Figure 2-2: four questions about the trust policy: who issues it, who it is for, who the subject is, and whether it is still “the original” project

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.

GitLabid_tokens issuanceGITLAB_OIDC_TOKEN Job scriptaws sts assume-role-with-web-identity AWS STSProvider · JWKS signature checkaud audience list Role trust policygitlab.com:subgitlab.com:project_id ECR / ECSSigV4 call
Choose a scenario to start.
$ # job log

Core commands and keywords

Command / keywordPurposeKey parameters / notes
aws iam create-open-id-connect-providerCreate 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-providerAdd an audience to the providerUsed when changing aud
aws iam create-role --assume-role-policy-documentCreate the CI role--max-session-duration 3600 (seconds, 1–12 hours)
aws iam update-assume-role-policyModify the trust policyTakes effect within seconds
id_tokens: NAME: aud:Job requests an ID tokenOne aud per token; it can be used in script,before_script,after_script .
aws sts assume-role-with-web-identityExchange an ID token for temporary credentials--role-arn --role-session-name --web-identity-token --duration-seconds
AWS_ROLE_ARN + AWS_WEB_IDENTITY_TOKEN_FILESDK/CLI native web identity credential providerAutomatically calls AssumeRoleWithWebIdentity when both are present; optional AWS_ROLE_SESSION_NAME
glab variable set AWS_ROLE_ARNWrite 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)

First print the real claims: in the myapp project root’s .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).

Create the dev role based on the printed sub and project_id
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 *.
Add the .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 succeeded
Negative test: create a new branch feature/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.
Acceptance CloudTrail → Event history → Event name 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.

Command-line tasks
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.json
2. 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
Scenario analysis
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

▶
GitLab at AWS re:Inforce 2023 - Secure GitLab CD pipelines to AWS w/ Open ID Federation, OIDC & JWT — GitLab Unfiltered
English · a talk cited in GitLab’s official AWS OIDC docs; recorded in 2023, so CI_JOB_JWT_V2 and other legacy syntax; this hour’s id_tokens takes precedence

Official docs

Video storyboard (about 90 seconds)

Shot 1 · 0–20s
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.
Shot 2 · 20–45s
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.
Shot 3 · 45–70s
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.
Shot 4 · 70–90s
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.
or score ≥ 70% on the quiz

Module 3 · Build and push to ECR

13:00 – 21:00 · Build on a hosted Runner using Docker-in-Docker, push once to ECR (immutable tags) and to the GitLab Container Registry, and output the digest for the later deploy jobs
8 minutesdocker:29 + docker:29-dindIMMUTABLE · scan on push★★★★
Learning objectives
  • 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 login to log in, using !reference Reuse the OIDC snippet from Module 2.
  • Write an idempotent build job: if the tag already exists, reuse its digest; use artifacts:reports:dotenv to pass IMAGE_URI=…@sha256:… to the deploy job.
  • Write the minimum ECR permissions for the CI role (GetAuthorizationToken only Resource: "*").
Prerequisites: Docker images, tags and digests; Lesson 2's services,artifacts. Importance:★★★★

What: the four things involved in an ECR push

StepAWS API / CommandDescription
Log inecr:GetAuthorizationToken → aws ecr get-login-passwordDocker password validity 12 hours; the username is fixed as AWS; this API does not support resource-level permissions
Upload layersBatchCheckLayerAvailability,InitiateLayerUpload,UploadLayerPart,CompleteLayerUploadlayers that already exist are skipped
Write manifestPutImagein an IMMUTABLE repository, rejected here if the tag already exists
Scanbasic 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): latest Overwritten every time, so you cannot tell which image ran yesterday, and a rollback cannot recover the original content.
  • Immutable tag (IMMUTABLE): sha-3f2a9c1 Once 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

ApproachKey pointsThis lesson
Docker-in-Dockerimage: docker:29 + services: [docker:29-dind],DOCKER_TLS_CERTDIR: "/certs"; hosted Linux Runners run in privileged mode and support DinDUses
BuildKit rootless / Buildahdoes not need privileges, suitable for self-managed Kubernetes RunnersNote
Kanikothe upstream project is archived and no longer maintained; not recommended for new pipelinesNot 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.

Common misconceptions① “GetAuthorizationToken can also be scoped to a repository ARN”—no, it only accepts 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

build-push job image: docker:29service: docker:29-dind① STS → temporary credentials② describe-images (already exists?)③ docker build / push④ write build.envIMAGE_URI=…@sha256:… SigV4 ECR: myapp (IMMUTABLE)111122223333.dkr.ecr.ca-central-1.amazonaws.com/myapp:sha-3f2a9c1scan on push → findings (async) CI_JOB_TOKEN GitLab Container Registryregistry.gitlab.com/mygroup-lab/myapp deploy-* jobs (needs: build-push)automatically gets $IMAGE_URI (dotenv)task definition image = …@sha256:…execution role pulls from ECR ECR lifecycle policy:untagged images expire after 1 day; only the latest 20 sha- images are kept
Figure 3-1 One build, two pushes; the deploy job gets the digest through the dotenv artifact

Tags, digests and immutability

MUTABLElatest → sha256:aaa (Monday)latest → sha256:bbb (Tuesday, overwrites)sha256:aaa becomes untaggedRoll back to “Monday's latest”? Not possible IMMUTABLEsha-3f2a9c1 → sha256:aaaPushing sha-3f2a9c1 again: rejected→ run describe-images before buildingif it exists, reuse the digest Deploy by digestimage: …/myapp@sha256:aaaScaling and restarts pull the same contentPromote to prod using the same digestRollback = redeploy the old revision
Figure 3-2 Tags make things easy to remember; digests make them certain

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.

ECR repository myapp
ECS service tasks
Choose an action.
$ # CI log

Core commands

CommandPurposeNotes
aws ecr create-repository --image-tag-mutability IMMUTABLE --image-scanning-configuration scanOnPush=trueCreate repositoryEncrypted with AES256 by default; KMS can be used
aws ecr get-login-password | docker login --username AWS --password-stdin REGISTRYLog inPassword valid for 12 hours
aws ecr describe-images --image-ids imageTag=TAGCheck whether a tag exists and get its digestreturns when not found ImageNotFoundException (non-zero exit)
aws ecr wait image-scan-completeWait for scan to completethen describe-image-scan-findings
aws ecr put-lifecycle-policyAutomatically clean up old imagesControl storage costs
artifacts:reports:dotenvPass runtime variables to later jobsLater 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)

Create repository and lifecycle policy: run the first part of the “Commands” tab.
Add ECR permissions to the dev role: run the “Commands” tab's ecr-push.json part.
Submit the pipeline: in .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
Verify idempotency: in the GitLab UI, click on the same pipeline Retry to re-run build-push; the log should show tag sha-3f2a9c1 already exists → reuse sha256:…, not a push failure.
Read scan results (locally)
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
}
Acceptanceaws 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.

Command-line exercise
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; }
Scenario analysis
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

▶
GitLab CI CD Tutorial for Beginners [Crash Course] — TechWorld with Nana
English · A complete demo of GitLab CI building a Docker image and pushing it. The video uses long-lived credentials; this lesson uses OIDC instead.

No verified video on “GitLab CI + ECR immutable tags” was found; please refer to the documents and storyboard below.

Official documentation

Video storyboard (about 60 seconds)

Shot 1 · 0–20s
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.
Shot 2 · 20–40s
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.
Shot 3 · 40–60s
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.
or score ≥ 70% on the quiz

Module 4 · Deploy to ECS on Fargate

21:00 – 29:00 · Register task definition → update service → wait for stability → verify the PRIMARY revision; use GitLab environments to record each deployment and resource_group to prevent concurrent deployments
8 minutesregister-task-definition · update-serviceCircuit breaker rollback=true★★★★★
Learning objectives
  • 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_URI render 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 (including deployment_tier) to record deployment history, and use resource_group to 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:PassedToService conditions iam:PassRole.
Prerequisites: Docker Lesson 4 on task definitions and services; Module 3's IMAGE_URI. Importance:★★★★★

What: what an ECS deployment calls

StepAPICI role permissionDescription
Render(locally sed/jq)NoneReplace the __IMAGE_URI__ with …/myapp@sha256:…
RegisterRegisterTaskDefinitionecs:RegisterTaskDefinition (Resource *) + the iam:PassRolepermission; creates a new revision myapp:7
DeployUpdateServiceecs:UpdateService (service ARN)Triggers a rolling deployment (or blue/green, depending on the service configuration)
WaitDescribeServices Pollecs:DescribeServicesaws ecs wait services-stable: every 15 seconds, up to 40 times (about 10 minutes); exits with a non-zero code on timeout
VerifyDescribeServices(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

KeywordPurposeUse in this lesson
environment: name / deployment_tier / urlIn Operate → Environments , record each deployment (which commit, which job, who triggered it)dev / development; production production / production
resource_groupjobs in the same resource group run one at a time, to prevent two pipelines from running update-serviceaws-dev,aws-production
Re-deploy / RollbackOn the environment page, clicking “Re-deploy” on an old deployment re-runs the deploy job from that timeThe 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=200 Start 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.
Common misconceptions① “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

deploy-dev job environment: devresource_group: aws-dev① sed renders td.json② register → myapp:7③ update-service④ wait services-stable⑤ Verify PRIMARY= myapp:7 ∧ COMPLETEDotherwise exit 1 ECS service myapp-dev (Fargate) PRIMARY :7IN_PROGRESS ACTIVE :6draining minimumHealthyPercent=100maximumPercent=200 Circuit breaker: failures ≥ max(3, ⌈desired×0.5⌉)→ FAILED → automatic rollback to :6 Execution role pulls …@sha256:… from ECRContainer health check /healthz:5000Logs → /ecs/myapp GitLab environment devDeployment #12 sha-3f2a9c1 ✓Deployment #11 sha-9e1b77d ✓Deployment #10 sha-1c0d2aa ✗“Re-deploy” old entry= re-run the job from that time
Figure 4-1: the job starts the deployment and verifies it, ECS handles rolling updates and the circuit breaker, and the GitLab environment records each deployment

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.

Tasks
Service deployment status

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
CommandPurpose
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 10mContainer logs
aws ecs update-service --task-definition myapp:6Manually roll back to an old revision

Lab 4: deploy myapp-dev through the pipeline and rehearse a circuit-breaker rollback (about 8 minutes)

Submit the task definition template and create the service: change the ecs/taskdef.json account ID in it to yours, submit it; run the “Create service” and “ECS permissions” parts of the “Commands” tab.
Add 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
Access the app (the task has a public IP)
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
Rehearse the circuit breaker: temporarily change the startup command at the end of the Dockerfile to 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
View the environment in GitLab: Operate → Environments → dev, where you can see the commit and job for each deployment; a successful deployment has a “Re-deploy” button next to it.
Acceptance The good-version job is green and the bad-version job is red, and after the bad version the service still serves traffic on the old revision.

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.

Command-line exercise
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
Scenario analysis
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

▶
Deploying a Modern Application Stack to AWS Fargate with Amazon ECS - AWS Online Tech Talks — AWS Developers
English · Task definitions, services, and Fargate networking

No verified video on “GitLab CI + ECS circuit breaker” was found.

Official documentation

Video storyboard (about 60 seconds)

Shot 1 · 0–20s
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.
Shot 2 · 20–40s
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.
Shot 3 · 40–60s
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.
or score ≥ 70% on the quiz

Module 5 · Deploy to EKS and Lambda

29:00 – 37:00 · Two ways to reach EKS: the GitLab agent (the cluster connects out, so jobs need no AWS credentials) or EKS access entries (IAM identity → Kubernetes permissions); for Lambda, canary with versions and weighted aliases
8 minutesGitLab agent · ci_accessEKS access entries★★★★
Learning objectives
  • 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_access in the agent configuration, and know that access_as: ci_job and features such as impersonation require Premium.
  • Use EKS access entries + AmazonEKSEditPolicy (namespace-scoped) to authorize the CI role, and distinguish Unauthorized from Forbidden.
  • 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.
Prerequisites: K8s Lesson 7 (EKS, access entries); Lambda basics. Importance:★★★★

What: two ways to deploy to EKS

A: GitLab agent for KubernetesB: OIDC role + EKS access entries
Connection directionIn-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 publiclyThe Runner directly accesses the EKS API endpoint (public, or a private endpoint reachable over a connected network)
Credentials needed by the jobNo 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 configuredagent 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 identityBy 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 tightenusers mapped from IAM role ARNs; access policies limited to namespaces
levelagent and CI/CD workflow: Free; impersonation: Premium/UltimateAWS-native, no GitLab tier requirement
Suitable forplatform 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

LayerWho decidesWhat CI needsError when it fails
AWS APIIAMeks:DescribeCluster (update-kubeconfig used to get the endpoint and CA)AccessDeniedException … eks:DescribeCluster
Kubernetes APIEKS 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”,UpdateFunctionCode which 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 set AdditionalVersionWeights to 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.
Common misconceptions① “Once you use the agent, CI automatically gets least privilege”—agents installed with Helm have broad permissions by default (see the chart's RBAC values), and they operate as the agent's own identity by default. To narrow permissions per job, you need 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

A: GitLab agent deploy-eks jobuse-contextmygroup-lab/myapp:eks-lab KASkas.gitlab.comValidate ci_access Tunnel agentk (in-cluster)Connects out; no inboundProxies K8s API requests EKS API serveragent SA or ci_jobImpersonated identity + RBAC B: OIDC + access entry deploy-eks job.aws-oidc → temporary credentialsupdate-kubeconfig aws eks get-tokenPresigned STSGetCallerIdentity EKS API serverAuthentication: role ARN → access entry?Authorization: AmazonEKSEditPolicy @ myapp No entry → Unauthorized Wrong scope → Forbidden A needs no AWS credentials and no public API endpoint; all of B's permissions are auditable on the AWS side
Figure 5-1 GitLab agent vs. EKS access entries: who connects to whom, and where permissions are configured

Lambda: versions and aliases

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

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.

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

Path A: GitLab agent for Kubernetes

StepCommand / locationDescription
Register agentProject → Operate → Kubernetes clusters → Connect a cluster (agent)Enter a name eks-lab, “Create and register”, copy the token and installation command
Install agentkhelm upgrade --install … gitlab/gitlab-agentHelm 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_accessprojects and groups must be under the same top-level group as the agent project
CLI bootstrap (optional)glab cluster agent bootstrap eks-labWorks 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

CommandPurposeDescription
aws eks describe-cluster --query cluster.accessConfigCheck the authentication modeRequires API or API_AND_CONFIG_MAP
aws eks create-access-entry --principal-arn ROLE_ARNCreate an access entry for the CI role--type STANDARD (default)
aws eks associate-access-policy --access-scope type=namespace,namespaces=myappAssociate an access policyCI only gets the application namespace
aws eks update-kubeconfig --name eks-labGenerate kubeconfigRequires 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

CommandPurpose
aws lambda update-function-code --function-name F --zip-file fileb://fn.zip --publishUpdate code and publish a version (for container images, use --image-uri …@sha256:…)
aws lambda wait function-updated-v2 --function-name FWait for the update to finish before 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.

Admin creates the function and execution role
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", … }
Add Lambda permissions to the dev role
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:*\"]}]}"
Submit lambda/handler.py and the package-lambda and deploy-lambda jobs, change the text returned by the handler, and push; the pipeline publishes version 2 and gives it 10%.
for i in $(seq 1 20); do aws lambda invoke --function-name myapp-fn:live --query ExecutedVersion --output text /tmp/out.json; done | sort | uniq -c
aws lambda get-alias --function-name myapp-fn --name live --query '[FunctionVersion,RoutingConfig]'
     18 1
      2 2
["1", {"AdditionalVersionWeights": {"2": 0.1}}]
Full rollout or rollback (can be split into 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":{}}'   # rollback

Case 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.

Command-line exercise
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}}'
Scenario analysis
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

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

No verified video on “GitLab agent for Kubernetes + EKS” was found; please refer to the documents and storyboard below.

Official documentation

Video storyboard (about 60 seconds)

Shot 1 · 0–20s
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.
Shot 2 · 20–40s
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.
Shot 3 · 40–60s
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.
or score ≥ 70% on the quiz

Module 6 · Multi-account and environment promotion

37:00 – 45:00 · Build once, promote by digest; one OIDC provider per account and one role per environment; on the AWS side, sub + ref_protected act as the gate; on the GitLab side, protected tags and protected environments act as the gate
8 minutesEnvironment-scoped variables · protected tagsProtected environments / deployment approvals: Premium★★★★★
Learning objectives
  • Design a dev / prod multi-account structure: the OIDC provider goes in each account, one per account; GitLab uses environment-scoped variables AWS_ROLE_ARN to 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.
Prerequisites: The sub format from Module 2; Lesson 2's rules and variable precedence. Importance:★★★★★

What: the mapping between accounts, roles, and environments

GitLab environmentAWS accountRole (in each account)Trust condition (gitlab.com:*)GitLab-side controls
dev (tier development)dev 111122223333gitlab-myapp-dev-deploysub = 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_idmain is a protected branch; push = deploy
production (tier production)prod 444455556666gitlab-myapp-prod-deploysub StringLike project_path:mygroup-lab/myapp:ref_type:tag:ref:v*; ref_protected = "true"; project_idv* 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: manual written 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's ref_protected=true and 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

  1. Pipeline on main: build-push push sha-3f2a9c1 to the shared ECR (this lesson puts it in the dev account; in production a separate tooling account is common) → deploy-dev automatic deployment.
  2. A Maintainer tags the same commit v1.1: in the tag pipeline, build-push finds sha-3f2a9c1 already exists → reuse the digest (no rebuild); promote-tag use put-image to add a readable tag to the same digest 1.1.
  3. deploy-production (manually / after approval) use the same IMAGE_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)

CapabilityTierFree-tier alternative
Protected branches, protected tagsFree—
environments,deployment_tier,resource_group environment-scoped variablesFree—
Protected environments (restrict who can deploy)Premium / UltimateProtected tags restrict who can trigger + AWS-side ref_protected conditions
Deployment approvals (manual run still needed after approval)Premium / Ultimatewhen: 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_components lets sub include ref_protected, as well as the environment_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).
Common misconceptions① “Trusting the prod role 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

main pipelinebuild-push → sha-3f2a9c1deploy-dev (automatic)sub …:branch:ref:mainAWS_ROLE_ARN[dev] Tag v1.1 pipelineOnly Maintainers can create (protected tags)build-push: reuse digestdeploy-production (manual / approval)sub …:tag:ref:v1.1 · ref_protected dev account 111122223333OIDC provider gitlab.comgitlab-myapp-dev-deployECR myapp (shared)ECS myapp-dev prod account 444455556666OIDC provider gitlab.com (one per account)gitlab-myapp-prod-deployECS myapp-prodExecution role pulls from ECR across accounts same digest Three gates ① Who can create v* tagsGitLab protected tags (Free) ② Does the token come from a protected tagAWS: sub tag:v* ∧ ref_protected∧ project_id ③ Who can click deploy / approveProtected environments + deployment approvals(Premium / Ultimate) None of these gates can be bypassed by“editing .gitlab-ci.yml”
Figure 6-1 The same digest is promoted from dev to prod; GitLab and AWS each guard one gate

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.

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

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.

Create the prod role: using the Commands tab's 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.
Create the myapp-prod service: repeat Module 4's “Create service” step, setting the cluster to myapp-lab, service name myapp-prod (in the job, change CLUSTER accordingly to myapp-lab).
Set up protected tags and environment-scoped variables: run the glab section of the Commands tab.
Negative test: as a Developer (or temporarily change the protected tag to 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.

Positive test: a Maintainer tags the latest commit on main with 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 .

Acceptanceaws 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.

Command-line exercises
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"
Scenario analysis
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

▶
GitLab at AWS re:Inforce 2023 - Secure GitLab CD pipelines to AWS w/ Open ID Federation, OIDC & JWT — GitLab Unfiltered
English · The idea of constraining the CD pipeline with declarations; for specific condition keys, the IAM docs verified for this lesson are authoritative.

No verified video on “GitLab multi-account promotion” was found.

Official documentation

Video storyboard (about 60 seconds)

Shot 1 · 0–20s
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.
Shot 2 · 20–40s
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.
Shot 3 · 40–60s
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.
or score ≥ 70% on the quiz

Module 7 · Troubleshooting Cloud Deployments

45:00 – 54:00 · Four-layer model: GitLab token → STS trust → IAM permissions → service behavior. Start by checking “which step failed,” and you can tell which layer it is in
9 minCloudTrail · simulate-principal-policyInteractive troubleshooting tree★★★★★
Learning objectives
  • 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-policy to locate problems, and distinguish IAM denials from explicit SCP denials.
Prerequisites: Modules 2–6. Importance:★★★★★

What: the four-layer model

LayerWhere it failsTypical errorsFirst diagnostic step
① GitLab token layerBefore STS is calledargument --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 layerassume-role-with-web-identityInvalidIdentityToken: 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 layerAWS calls after getting credentials… is not authorized to perform: ecr:… / ecs:… / iam:PassRole; … with an explicit deny in a service control policyaws iam simulate-principal-policy; check the assumed-role name in the error
④ Service layerAWS accepted the request, but the result is wrongECS tasks stopping, circuit-breaker rollbacks,Unauthorized/Forbidden (EKS), Lambda update conflictsdescribe-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_id and ref_protected must match the trust policy character for character (mind case and the /).
  • CloudTrail: AssumeRoleWithWebIdentity events (both successful and failed), and afterward, with session name gitlab-<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_id so 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_path changes 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 environment job; protected variables are only available in pipelines for protected branches or tags.
  • extends vs. !reference differences: !reference [.aws-oidc, before_script] Only reuses scripts; does not bring over id_tokens.
Common misconceptions① “A wrong aud produces Not authorized” — no. When aud is not in the provider's audience list, the error is 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

① GitLab token layerid_tokens / audVariable scopesub customization / token issuance disabled ② STS trust layerProvider in this account?aud ∈ audience list?sub / project_id conditions? ③ IAM permissions layerPermission policy · PassRoleResource policy (ECR repository)Explicit SCP deny ④ Service layerECS tasks / circuit breakerEKS access entries / agentLambda state Fails before the STS callassume-role-with-web-identity failsget-caller-identity succeeds,later calls get AccessDeniedAPI succeeds, result is wrong Rule: fix only at the layer where it fails; the further right you go, the more you should check AWS-side events and logs rather than the job log
Figure 7-1: the “last successful command” in the job log is the basis for locating the layer

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

LayerCommandWhat 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-providersWhether the role's account has the gitlab.com
②aws iam get-open-id-connect-provider --query ClientIDListaudience list
②aws iam get-role --query Role.AssumeRolePolicyDocumenttrust conditions
②③aws cloudtrail lookup-events --lookup-attributes AttributeKey=EventName,AttributeValue=AssumeRoleWithWebIdentityerrorCode, errorMessage
③aws iam simulate-principal-policyallowed / implicitDeny / explicitDeny
④aws ecs describe-services … events,describe-tasks … stoppedReason,aws logs tailService 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)

Failure 1: aud mismatch. In .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.)

Failure 2: sub mismatch. In the trust policy, change 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).

Failure 3: missing PassRole. Temporarily delete 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.

Review with the troubleshooting tree: open the interactive troubleshooting tree on the “Troubleshooting” tab and walk through the path for the three failures above.

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.

Command-line exercises
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]'
Scenario analysis
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 ②.

▶
GitLab at AWS re:Inforce 2023 - Secure GitLab CD pipelines to AWS w/ Open ID Federation, OIDC & JWT — GitLab Unfiltered
English · Recorded in 2023

Official documentation

Video storyboard (about 60 seconds)

Shot 1 · 0–15s
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?
Shot 2 · 15–40s
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.
Shot 3 · 40–60s
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.
or score ≥ 70% on the quiz

Module 8 · Cost, Cleanup, and Self-Check

54:00 – 60:00 · Stop billable resources first, then delete in dependency order, and finally reclaim identities: IAM roles, OIDC providers, GitLab variables, agents and tokens
6 minCost estimatorAn OIDC provider is an account-level shared resource★★★★
Learning objectives
  • 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/DeleteConflict and why.
  • Reclaim identity-related resources: IAM roles, OIDC providers (lab account only), GitLab CI/CD variables, protected tag rules, environments, agents and their tokens.
Prerequisites: Modules 1–7. Importance:★★★★

What: this lesson's cost components

ItemBilling modelScale in this lessonHow to stop billing
Fargate taskvCPU-seconds + GB-seconds (per second, 1-minute minimum)0.25 vCPU / 0.5 GB × 1–2 tasks, a few cents per hourDelete the service (or set desiredCount=0)
Public IPv4 addressBilled hourly per addressOne per taskReleased after the task stops
ECR storagePer GB-monthmyapp image about 100–200 MBDelete the repository / lifecycle policy
CloudWatch LogsIngestion + storageVery little (3-day retention)Delete the log group
ALB (created by Express Mode)Hourly fee + LCUZero if not createdDelete the Express service / ALB
EKS cluster (optional)Cluster hourly fee + nodesThis lesson is read-only, nothing createdClean up per K8s Lesson 7
IAM, STS, OIDC providersFree0but delete them to remove the attack surface
GitLab-hosted runnersCompute 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

  1. Stop billing: ECS service → cluster; Lambda function; (optional) Express service, EKS resources.
  2. Delete data: ECR repository (--force), log groups.
  3. Delete networking: security groups (wait for ENIs to be released).
  4. Reclaim identities: EKS access entries / agent; IAM roles (policies first, then roles); OIDC providers (lab account only).
  5. GitLab: delete AWS_ROLE_ARN/AWS_ACCOUNT_ID variables, protected tag rules, stop and delete environments, delete the agent (its tokens are revoked along with it), delete test tags and releases.
Common misconceptions① “Deleting the GitLab project makes the AWS role useless” — the role still exists; if the trust policy is based only on the path, someone who registers the same path later could satisfy the condition (this is exactly why project_id must be added). ② “OIDC providers can be deleted freely” — it is an account-level shared resource, and other teams' roles may depend on it; deleting it makes them fail with 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

ECS servicedelete-service --force Tasks / ENI releasewait services-inactive Cluster · security groupsdelete-cluster / -sg ECR · log groups--force / delete Lambda · aliasdelete-function IAM roleFirst delete-role-policy / detach, then delete-role OIDC provider gitlab.comlab account only, after confirming nothing depends on it GitLab sideVariables · environments · agent · tags Left: stop billing first; right: reclaim identities last. The OIDC provider is always considered last
Figure 8-1: cleanup dependencies and order

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.

Fargate task count: 2
vCPU per task: Memory GB:
Running hours: 2 h
ECR storage GB: 1

Cleanup commands

CommandNotes
aws ecs delete-service --cluster C --service S --forceNo need to scale desired count to 0 first
aws ecs wait services-inactiveWait for the service to be fully deleted before deleting the cluster
aws ecr delete-repository --repository-name myapp --forceDelete together with the images
aws iam list-role-policies / list-attached-role-policiesList the policies before deleting the role
aws iam delete-open-id-connect-providerLab account only
aws resourcegroupstaggingapi get-resources --tag-filters Key=course,Values=gitlab-part4Find leftovers by tag
glab variable delete KEY --scope ENVDelete scoped variables

Lab 8: One-command cleanup script (about 5 minutes)

AWS side (lab account; clean up the EKS part per K8s Lesson 7)
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.

GitLab side
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.

Acceptance Tag query returns empty; 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.

Command-line exercises
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
Scenario analysis
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

Video storyboard (about 45 seconds)

Shot 1 · 0–15s
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.
Shot 2 · 15–30s
Visual: icons turn off in order: service, cluster, repository, logs, security group.
Narration: Stop billing first, then delete in dependency order.
Shot 3 · 30–45s
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.
or score ≥ 70% on the quiz

Command cheat sheet

GitLab CI/CD → AWS: OIDC, ECR, ECS, EKS, Lambda, multi-account, troubleshooting and cleanup
Post-lesson reviewCopy-ready
OIDC (AWS side)
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
OIDC (GitLab side)
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
Trust policy conditions (GitLab.com)
"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.

ECR
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"
ECS
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
EKS
# 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
Lambda
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}}'
GitLab keywords and glab
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

ErrorLayerFix
argument --web-identity-token: expected one argument① TokenAdd id_tokens; do not use CI_JOB_JWT_V2
Invalid length for parameter RoleArn, value: 0① Token/variablesEnvironment name matches variable scope
InvalidIdentityToken: Incorrect token audience② STSid_tokens aud ∈ provider audience list
InvalidIdentityToken: No OpenIDConnect provider found in your account for https://gitlab.com② STSCreate the provider in the role's account
AccessDenied: Not authorized to perform sts:AssumeRoleWithWebIdentity② STSsub / project_id / ref_protected / aud conditions match the claims
InvalidIdentityToken: Couldn't retrieve verification key …② STSFor self-managed instances, the discovery endpoint and JWKS must be publicly reachable
is not authorized to perform: iam:PassRole③ IAMAdd PassRole + iam:PassedToService
Waiter ServicesStable failed / Verify mismatch④ ServiceCheck service events, stoppedReason, logs
You must be logged in to the server (Unauthorized)④ EKSaccess entries / agent context

Capstone lab + final quiz

Build from scratch: id_tokens → STS → ECR (immutable) → ECS dev auto-deploy → protected tag v1.1 → prod manual deploy → circuit-breaker rollback drill → cleanup
About 45 minutesCan be completed in a single accountIncurs small charges
Scenario

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.

1. Infrastructure: complete the Module 1 lab (cluster, log group, security group, execution role) and the Module 3 ECR repository + lifecycle policy.
2. Identity: OIDC provider 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).
3. GitLab settings: protected tag v* (Maintainer); environment-scoped variables AWS_ROLE_ARN,AWS_ACCOUNT_ID (dev / production); (optional on Premium) protected production environment + 1 approver.
4. Services: create per Module 4 myapp-dev and myapp-prod two services (the same cluster is fine), each with circuit-breaker rollback enabled.
5. Pipeline: commit the complete .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).

6. dev verification: push to main → build-push and deploy-dev go green; curl http://<task public IP>:5000/healthz returns ok.
7. Release and negative tests: a Developer pushes an unprotected tag 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.
8. Rollback drill and cleanup: commit a version that exits on startup to main, confirm deploy-dev turns red because Verify fails and the service stays on the old revision; after reverting, run the Module 8 cleanup script.
Acceptance checklist

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

All facts were verified against official documentation on 2026-11-16; for commands that cannot be run in a real account, the output is labeled “example”
Verified 2026-11-16

Source

TopicSourceVerified onFacts used in this lesson
GitLab → AWS OIDCdocs.gitlab.com/ci/cloud_services/aws2026-11-16The 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 tokensdocs.gitlab.com/ci/secrets/id_token_authentication2026-11-16claims 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 deprecationdocs.gitlab.com/ci/cloud_services2026-11-16ci_id_token_sub_claim_components; CI_JOB_JWT/CI_JOB_JWT_V2 removed in 17.0
IAM condition keysIAM: Available keys for AWS OIDC federation2026-11-16GitLab.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 agentCI/CD workflow · Install2026-11-16context 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 approvalsEnvironments · Protected environments · Deployment approvals2026-11-16deployment_tier values; protected environments and deployment approvals are Premium/Ultimate; the job still needs to be run manually after approval
GitLab versiondocs.gitlab.com/releases2026-11-16GitLab 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 RunnerAWS official documentation (circuit breaker, Express Mode getting started, ECR authentication and tag immutability, App Runner availability change)2026-11-16circuit breaker threshold (50%, minimum 3, maximum 200, customizable); Express Mode CLI parameters; App Runner is not accepting new customers
Tool versionsDocker Hub (docker, amazon/aws-cli, alpine/k8s tags), dl.k8s.io/release/stable.txt, helm/helm releases2026-11-16docker:29/29-dind,amazon/aws-cli:2.40.4,alpine/k8s:1.37.2, Kubernetes v1.37.2, Helm v4.3.2
Corresponding coursesGitHub 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:

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, and deployment_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_protected In 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:// or grpcs://kas.gitlab.com) follow the command generated by the GitLab UI; for the agent chart's default RBAC permissions, refer to the chart values.
  • glab Subcommand output formats change between versions, so example output is for reference only. ECS Express Mode is a newer API, and its parameters are defined by aws 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.