Jenkins Hour 4: Moving to the Cloud Platform (AWS)

Take myapp (Flask, port 5000) from Jenkins to ca-central-1. First explain thoroughly “how Jenkins gets an AWS identity” (access keys → instance profile → EKS Pod Identity / IRSA → Jenkins self-signed OIDC), then push to ECR, deploy to ECS Fargate / EKS / Lambda, and finally move the agent itself to AWS
Jenkins 2.580.2 LTSAWS Credentials 265OpenID Connect Provider 234EC2 Fleet 4.5.2Region ca-central-1Verified against official docs · 2026-11-16
Overall learning goals
  • Based on “what the team has to operate,” choose among ECS on Fargate / ECS Express Mode / EKS / Lambda and know that App Runner is no longer accepting new customers.
  • Explain the four ways Jenkins gets an AWS identity, and each one decides who actually requests credentials from STS (controller or agent): AWS Credentials plugin access keys + AssumeRole, EC2 instance profiles, EKS Pod Identity / IRSA, and id tokens issued by the OpenID Connect Provider plugin + AssumeRoleWithWebIdentity.
  • Be honest about when long-term keys are still unavoidable: a local Jenkins, a controller without public HTTPS, and cross-cloud scenarios; and how to shrink this key’s permissions down to only sts:AssumeRole.
  • In the Jenkinsfile, use aws ecr get-login-password to push to immutable tags in the ECR repository myapp, and deploy by digest .
  • Use the AWS CLI to implement ECS Fargate’s “register task definition → update service → wait for stability → circuit-breaker rollback,” use an EKS access entry + kubectl to deploy to EKS, and use versions + aliases to deploy Lambda.
  • Use the EC2 Fleet plugin (auto scaling group) and the Kubernetes plugin (EKS pods) to run one-off agents on AWS, and be able to troubleshoot independently Unable to locate credentials,AccessDenied ... sts:AssumeRole,no basic auth credentials and other typical errors.

1-hour time allocation table

#TimeModuleCore contentAnimation / interactionLab (AWS account · ca-central-1)
0Before classWarm-up & AWS setupAWS CLI v2, budget alerts, install the AWS CLI on agent1, install plugins, variables filePrerequisite self-checkaws sts get-caller-identity
100–05Choosing a deployment architecture on AWSECS Fargate / Express Mode / EKS / Lambda; App Runner status; Jenkins has no “official deployment plugin,” so it relies on the AWS CLIDeployment target selectorCreate ECS cluster, log group, security group
205–13Jenkins identity on AWSAccess keys + AssumeRole, instance profiles, Pod Identity / IRSA, OIDC Provider plugin; controller-side vs. agent-side resolutionCore animation: how credentials reach AWS (5 paths)Create deployment role jenkins-myapp-deployer, pipeline prints identity
313–21Build and push to ECRECR login token lasts 12 hours, IMMUTABLE, scan on push, digest, lifecycle policy; why not registry-credsECR API sequence of docker pushPipeline push myapp:1.1-<sha>
421–29Deploy to ECS on FargateTask definition rendering, update-service, services-stable, deployment circuit breaker, iam:PassRoleRolling deployment + circuit-breaker state machinePipeline deploys the myapp service
529–37Deploy to EKS and LambdaEKS access entries,aws eks get-token, kubectl; Lambda container image + Web Adapter, versions and aliaseskubectl → IAM → K8s RBAC authentication chain; weighted aliases(Optional) Lambda function URL
637–45Jenkins agents on AWSEC2 Fleet plugin + auto scaling group + instance profile; Kubernetes plugin pod agent on EKS + Pod IdentityQueue-driven scaling simulation(Optional) ASG agent, without access keys
745–54Troubleshooting cloud deploymentsCredential chain, AssumeRole denials, IMDS hop count, ECR login, ECS stuck, EKS Unauthorized, Lambda multi-architecture manifestFault reproduction simulatorDeliberately break PassRole and fix it
854–60Cost, cleanup & self-checkCost breakdown, cleanup order, revoking keys and roles; interactive troubleshooting treeCost estimatorOne-click cleanup script
—After classCheat sheet · Capstone labJenkins (no long-term keys) → ECR (immutable) → ECS (circuit-breaker rollback) → cleanupFinal quiz (12 questions)Capstone lab

Knowledge Coverage Matrix

Target skillsM1M2M3M4M5M6M7M8Key commands / pluginsLab
Choosing an AWS compute service by scenario✓··✓✓··✓Decision tableM1
Choosing an identity method for Jenkins → AWS·✓✓·✓✓✓✓AWS Credentials, OpenID Connect ProviderM2 / M6
Least-privilege deployment role + trust policy·✓✓✓·✓✓·aws iam create-role,iam:PassRoleM2
Push immutable images and reference them by digest··✓✓✓·✓·aws ecr get-login-passwordM3
ECS deployment, waiting for stability, circuit-breaker rollback···✓··✓·aws ecs update-service,wait services-stableM4 / Capstone
EKS access entries and kubectl deployment····✓✓✓·aws eks create-access-entryM5 (reading / optional)
Lambda container images, versions and aliases✓···✓·✓·aws lambda update-aliasM5 (optional)
Dynamic agents on AWS·✓···✓✓✓EC2 Fleet, Kubernetes pluginM6 (optional)
Locating cloud deployment failures·✓✓✓✓✓✓✓CloudTrail,describe-servicesM7
Cost control & complete cleanup··✓··✓·✓aws ecs delete-service --forceM8

What this course does not cover (and where to learn it)

TopicWhy it is not in this courseWhere to learn
Deploying to AWS with OIDC from GitHub Actions (configure-aws-credentials, ECS Action)This course covers only Jenkins’ approach; compare, don’t repeatGitHub Course 4 (AWS)
AWS service connections and OIDC in Azure PipelinesSame as aboveAzure DevOps Course 4 (AWS)
Dockerfile, multi-stage builds, ECS task definition fields and ALB detailsContainers themselves are covered in the Docker courseDocker Course 4 (AWS)
EKS cluster creation, VPC CNI, Karpenter, Auto ModeBelongs to Kubernetes platform operationsK8s Course 7 (EKS)
Managing roles, ECR and ECS with TerraformThis course uses the CLI so that every step is “visible”; production should use IaC insteadTerraform Course 4 (AWS)
Jenkins Helm chart, JCasC declaring the cloud and credentialsCourse 5 topicsJenkins Course 5
Azure managed identity, workload identity and ACRCovered in the previous course; this course maps to it one-to-oneJenkins Course 3 (Azure)

How to use this courseware

10 pages per module
Principle · diagrams · animation · commands · labs · production cases · troubleshooting · quiz · voice · video. Read “Principle” and “Animation” first, then do the “Lab.” The “how credentials reach AWS” animation in Module 2 is the core of the course.
Learning progress
A quiz score of ≥ 70%, or clicking “Mark this module complete,” counts toward progress, saved in this browser (cleared on refresh if local storage is disabled).
Chinese voice
The “Voice” page reads the narration script aloud using the browser’s Web Speech API (en-US); without a Chinese voice pack, the narration script is still readable.
Cost and safety notes The main lab (ECR + one 0.25 vCPU / 0.5 GB Fargate task, no ALB) running continuously for 1 hour costs on the order of US$0.1; an EKS cluster (from US$0.10 per hour, plus nodes) and the EC2 agent are optional labs, and delete them immediately when done. The only long-term key in this course’s labs (IAM user jenkins-lab-bootstrap) may only be allowed sts:AssumeRole to one role, and deleted in Module 8. Prices are based on AWS Pricing Calculator .
Version notes (verified 2026-11-16) Jenkins LTS 2.580.2 (2026-10-28, requires Java 21+; Java 17 is no longer supported from 2.555.1); AWS Credentials plugin 265.v8422a_f384cd9; Pipeline: AWS Steps 767.v48d5c10b_1899 (requires core 2.541.1+); OpenID Connect Provider 234.vca_b_26b_f4b_dda_ (requires core 2.568.1+); EC2 Fleet 4.5.2.571.v0932f9cd1039; Amazon EC2 2068.vd80935072db_b_; Kubernetes 4560.vc25b_83890c34; Amazon ECR plugin 1.175.ve233e80e56fd (looking for a maintainer, not required by this course). Plugin versions change quickly; plugins.jenkins.io is the authority.
Prerequisite courses This course followsCourse 1andCourse 2local environment ~/jenkinslab (controller jenkins, agent agent1 (label linux docker), Gitea repository lab/myapp), inCourse 3 (Azure)mirrors its structure one-to-one.

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

Prepare an AWS account you can safely experiment in, set budget alerts, let agent1 run the AWS CLI, and install the Jenkins plugins this course needs
Before class ≈ 15 minutesAWS CLI v2 · Jenkins 2.580.2
Prerequisites
  • Completed Courses 1 and 2: ~/jenkinslab under compose.yaml started jenkins (127.0.0.1:8080),agent1 (label linux docker, able to run docker build),gitea (127.0.0.1:3000, repository lab/myapp, credential ID gitea-myapp).
  • myapp: Flask + gunicorn, listening on 5000,/healthz does not depend on Redis (this course does not deploy Redis, so a page showing Redis unavailable is normal); the Dockerfile and Jenkinsfile are in the repository root.
  • One lab-only AWS account, plus an administrator identity with IAM, ECR, ECS, EC2 and CloudWatch Logs permissions (an IAM Identity Center user is recommended, used on your own computer with aws sso login).
  • Local machine: AWS CLI v2,jq, Docker Engine,curl.

Mapping to the previous course (Azure)

Course 3 (Azure)This course (AWS)Notes
Service principal + client secret (Azure Credentials plugin)IAM user access keys (AWS Credentials plugin)Both are “long-term keys,” suitable only for labs or when there is no other option
VM managed identity (IMDS)EC2 instance profile (IMDSv2)The agent runs on a cloud VM; the SDK automatically fetches temporary credentials from the metadata service
AKS workload identityEKS Pod Identity / IRSAKubernetes pod agent exchanges a service account for a cloud identity
Entra federated credential + Jenkins OIDC tokenIAM OIDC identity provider + AssumeRoleWithWebIdentityboth depend on the OpenID Connect Provider plugin; the issuer must be reachable by the cloud vendor
ACR / Container Apps / AKSECR / ECS Fargate / EKSImage registry / managed containers / Kubernetes

Step 1: confirm your AWS identity and region on your own computer

aws --version
export AWS_REGION=ca-central-1
aws configure set region $AWS_REGION          # or set the region in the SSO profile
aws sts get-caller-identity
export ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
export REGISTRY=$ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com
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"
}

This course uses an example account number throughout 111122223333 (the AWS documentation’s conventional example value); replace it with your $ACCOUNT_ID. Your administrator identity is used only on this machine, never put it into Jenkins.

Step 2: set a budget alert (strongly recommended)

cat > budget.json <<'EOF'
{ "BudgetName": "jenkins-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

Step 3: let agent1 run the AWS CLI

Shell steps in the pipeline run sh 'aws …' in agent , so the AWS CLI must be installed inside agent1 (the controller does not need it). The cleanest approach is a custom image for agent1; in the lab you can also install it directly in the container (it is lost when the container is rebuilt):

cd ~/jenkinslab
docker compose exec -u root agent1 bash -c '
  apt-get update && apt-get install -y unzip curl jq &&
  curl -sSL "https://awscli.amazonaws.com/awscli-exe-linux-$(uname -m).zip" -o /tmp/awscliv2.zip &&
  cd /tmp && unzip -q awscliv2.zip && ./aws/install && aws --version'
aws-cli/2.x.x Python/3.x Linux/6.x exe/x86_64.debian.12
Production practice Bake the AWS CLI, jq and kubectl into the agent image (the Pod template in Course 5 works the same way), and pin versions; do not download and install them in every build.

Step 4: install the plugins this course uses

Manage Jenkins → Plugins → Available plugins Search for and install: AWS Credentials (required),Pipeline: AWS Steps (optional, for comparison),OpenID Connect Provider (Module 2 advanced lab),EC2 Fleet (Module 6 optional lab). Credentials Binding,Docker Pipeline were already installed in the previous two courses.

# Alternatively, use the jenkins-plugin-cli bundled with the controller image (Course 5 will bake it into the image)
docker compose exec jenkins jenkins-plugin-cli --plugins aws-credentials pipeline-aws oidc-provider ec2-fleet
docker compose restart jenkins

Step 5: save the variables file (used repeatedly in later modules)

cat > ~/jenkinslab/aws-part4.env <<EOF
export AWS_REGION=ca-central-1 ACCOUNT_ID=$ACCOUNT_ID REGISTRY=$REGISTRY
export ECR_REPO=myapp CLUSTER=myapp-lab SERVICE=myapp
export DEPLOY_ROLE=jenkins-myapp-deployer EXEC_ROLE=myappTaskExecutionRole
EOF
source ~/jenkinslab/aws-part4.env

Warm-up: answer from memory (30 seconds)

Jenkins’ withCredentials binding: is it resolved on the controller or on the agent?

Credential values are retrieved on controller the controller from the credential store (when the AWS Credentials plugin calls STS, it does so in the controller’s JVM too), and then passed as environment variables to steps running on the agent. This determines “which machine the instance profile belongs to,” which Module 2 uses repeatedly.

Why is “storing AWS_ACCESS_KEY_ID in Jenkins credentials” still a risk?

Long-term keys never expire; anyone who can read them in a pipeline (including the Jenkinsfile author, malicious PR builds, plugin vulnerabilities, and backup leaks) can use them indefinitely. Jenkins’ log masking only blocks “printing as-is”; it cannot block base64 and other transformed output.

Can GitHub Actions natively obtain an OIDC token? Can Jenkins?

Jenkins core cannot. You need to install OpenID Connect Provider plugin, which lets Jenkins act as its own issuer and sign id tokens with a private key. AWS fetches the public key from the issuer on every AssumeRoleWithWebIdentity call, so the issuer URL must be reachable from the internet (by AWS); otherwise, host the two static JSON files elsewhere.

Environment self-check list

Module 1 · Choosing a deployment architecture on AWS

00:00 – 05:00 · First decide “how much the team is willing to operate,” then decide which set of AWS APIs the Jenkinsfile should call
5 minECS Fargate · Express Mode · EKS · LambdaApp 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 APIs a Jenkins pipeline needs to call.
  • Understand that in the Jenkins ecosystem there is no official AWS-maintained “deployment Action” like GitHub Actions. The mainstream approach is to use the AWS CLI, kubectl or SAM on agents; Jenkins plugins only handle credentials and agents.
  • Distinguish the “CI deployment identity” from “runtime identities”: task execution role, task role, Pod Identity, Lambda execution role.
Prerequisites: The ECS object model from Docker Course 4 (cluster, task definition, service). Importance:★★★★

What: four mainstream landing targets

ECS on FargateECS Express ModeEKSLambda
What you deliverImage + task definition JSON + service configurationImage + two IAM roles (one API call)Image + Kubernetes manifests / Helm chartContainer image (requires the Lambda runtime interface) or zip
What AWS manages for youServers, scheduling, rolling deploymentsAutomatically creates the ALB, autoscaling and networking on top of ECSControl plane (Auto Mode also manages nodes)All servers and scaling; billed per request
Core commands in the Jenkinsfileaws ecs register-task-definition → update-service → wait services-stableaws ecs create-express-gateway-service / updateaws eks update-kubeconfig → kubectl / helmaws lambda update-function-code → publish-version → update-alias
Core permissions needed by the deployment identityecs:RegisterTaskDefinition,ecs:UpdateService,ecs:DescribeServices,iam:PassRoleExpress service create/update + iam:PassRoleeks:DescribeCluster + EKS access entrylambda:UpdateFunctionCode,PublishVersion,UpdateAlias
Typical cost starting pointsBilled by task vCPU/memory-secondsExpress Mode itself is free; you pay only for underlying resources (Fargate, ALB, etc.)Cluster US$0.10 per hour (standard support) + nodesRequests + GB-seconds, with a free tier

Why: why the deployment target affects the Jenkinsfile and identity design

The “deploy” stage of a Jenkins pipeline is essentially: on some agent, using temporary credentials for some IAM identity, call a set of AWS APIs. Choosing ECS means giving the deployment role ECS permissions and iam:PassRole; choosing EKS, IAM only answers “who are you”; whether you can kubectl apply is decided by EKS access entries and Kubernetes RBAC; choosing Lambda, rollback means pointing an alias back to an old version. The target determines the deployment role’s permission policy, rollback method and troubleshooting entry point.

How: Jenkins’ approach versus GitHub / Azure DevOps

  • GitHub Actions: maintained by AWS configure-aws-credentials,amazon-ecr-login,amazon-ecs-deploy-task-definition and other Actions (see GitHub Course 4).
  • Azure Pipelines: the AWS Toolkit extension provides service connections and tasks (see Azure DevOps Course 4).
  • Jenkins: plugins do two things —credentials (AWS Credentials, OpenID Connect Provider, Pipeline: AWS Steps’ withAWS) and agent (EC2 Fleet, Amazon EC2, Kubernetes). The deployment itself is done with the AWS CLI on the agent: it is readable, reproducible on a local machine, and unaffected by a plugin falling out of maintenance. Amazon ECR The plugin (docker.withRegistry('…', 'ecr:region:id')) is currently marked “looking for a maintainer” on plugins.jenkins.io, so this course uses the official documentation’s aws ecr get-login-password.

How: current status of App Runner (verified)

The AWS official document “AWS App Runner availability change” states that App Runner no longer accepts new customers; existing customers can keep using it as usual (including creating new services), and AWS continues to invest in security and availability, but has no plans to add new features. The official recommendation is to migrate to Amazon ECS Express Mode: one API call, one image and two IAM roles (ecsTaskExecutionRole and ecsInfrastructureRoleForExpressServices). ECS creates the Fargate service, ALB, autoscaling 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; take direct control of the underlying ECS service when fine-grained control is needed.
  • Already have task definitions and services, and want precise control over each release: ECS on Fargate + AWS CLI (the main path of this course).
  • The company already has an EKS platform: application teams’ Jenkins gets permissions only in a specific namespace.
  • Event-driven, intermittent traffic, single execution ≤ 15 minutes: Lambda (container image uncompressed up to 10 GB).
Common misconceptions① “Deploying Jenkins to AWS requires installing an AWS deployment plugin”: not needed; plugins only solve credentials and agents, and the AWS CLI is the deployment tool. ② “Deploying to EKS only needs IAM permissions”: IAM only lets you call eks:DescribeCluster and generate tokens; kubectl apply you still need an access entry. ③ “App Runner has been shut down”: it has not; it just does not accept new customers. ④ “Deployment identity and application runtime identity can share one role”: possible but not advisable; the deployment role passes iam:PassRole the runtime role to ECS/Lambda. Separating the two is what least privilege means.

Architecture diagram: one Jenkins, four landing targets

Jenkins controller: scheduling, credential storageagent (linux docker):docker build · aws CLIkubectl · jqJenkinsfile in the repository root signed request AWS STS AssumeRole /AssumeRoleWithWebIdentity→ temporary credentials (default 1h) ECR (myapp)GetAuthorizationToken · push ECS on FargateRegisterTaskDefinition · UpdateService EKSget-token → K8s API (access entry) LambdaUpdateFunctionCode · UpdateAlias App RunnerNot accepting new customers → Express Mode Runtime identity (a separate matter) ECS: task execution role(pulls images, writes logs)ECS: task role (application)EKS: Pod Identity / IRSALambda: execution roleThe deployment role only needs iam:PassRole Deployment role jenkins-myapp-deployer ≠ runtime role myappTaskExecutionRole The former lets Jenkins “deploy”; the latter lets the ECS agent pull images and write logs Separating the two is the key to least privilege
Figure 1-1: each Jenkins build exchanges for one set of temporary credentials, and all subsequent deployment API calls use these credentials

Decision flow

Event-driven,≤ 15 minutes? Lambda Yes No Already have a Kubernetesplatform / need CRDs? EKS Yes No Want “one call to buildALB + scaling”? ECS Express Mode Yes No ECS on FargateTask definition + service (main path of this course) Do not choose App Runner for new projects (it accepts no new customers); whichever you choose, the Jenkins-side identity chain is solved in Module 2
Figure 1-2: simplified decision flow (real selection must also consider team skills, compliance and existing platforms)

Interaction: deployment target selector

Answer 4 questions to see the recommended deployment target, the commands the Jenkinsfile deployment stage needs, and the core permissions of the deployment role. Each step shows its decision rationale.

Start from the first question.
# Recommendation results will be shown here

Core commands: survey the “foundation” of the account

CommandPurposeNotes
aws ec2 describe-vpcs --filters Name=is-default,Values=trueFind default VPCThis lab uses public subnets in the default VPC, which saves NAT gateway costs
aws ecs create-cluster --cluster-name myapp-labCreate ECS clusterThe cluster itself is free; first use automatically creates the ECS service-linked role
aws logs create-log-group --log-group-name /ecs/myappCreate log groupA task definition that references a non-existent log group will cause task startup to fail
aws service-quotas list-service-quotas --service-code fargateCheck Fargate quotaNew accounts may have lower quotas
aws ecs create-express-gateway-service …Express Mode creates the full stack in one stepRequires --execution-role-arn and --infrastructure-role-arn
source ~/jenkinslab/aws-part4.env
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 $CLUSTER --tags key=course,value=jenkins-part4 \
  --query 'cluster.[clusterName,status]' --output text
VPC=vpc-0a1b2c3d SUBNETS=subnet-0aaa,subnet-0bbb,subnet-0ccc
myapp-lab   ACTIVE

Express Mode CLI syntax (for reference)

Adapted from the CLI example in AWS’s official App Runner migration guide (port and health check path replaced with myapp’s values). In the Jenkinsfile it is likewise just one command sh:

aws ecs create-express-gateway-service \
  --execution-role-arn arn:aws:iam::111122223333:role/ecsTaskExecutionRole \
  --infrastructure-role-arn arn:aws:iam::111122223333:role/ecsInfrastructureRoleForExpressServices \
  --primary-container '{"image":"111122223333.dkr.ecr.ca-central-1.amazonaws.com/myapp:1.1-abc1234","containerPort":5000}' \
  --service-name myapp-express --health-check-path /healthz \
  --scaling-target '{"minTaskCount":1,"maxTaskCount":3}'

How to verify: The ECS console “Resources” tab shows the ALB, target group and default URL. Common errors: Forgetting that Express Mode creates an ALB (billed hourly); if you don’t delete it after the lab, charges continue. Production use: A replacement for App Runner’s “push and it’s live” experience.

Lab 1: prepare the ECS cluster, log group, security group and task execution role (about 4 minutes)

Create the cluster and log group (on your own computer, as administrator)
source ~/jenkinslab/aws-part4.env
aws ecs create-cluster --cluster-name $CLUSTER --tags key=course,value=jenkins-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
Create the task security group (allow only your IP to access port 5000)
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 course does not create an ALB; the task gets a public IP directly. This is only suitable for labs: production should use a private subnet + ALB (see Docker Course 4).

Create the task execution role (the ECS agent uses it to pull ECR images and write CloudWatch logs; this is a “runtime identity,” not Jenkins’ identity)
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 $EXEC_ROLE --assume-role-policy-document file://ecs-tasks-trust.json
aws iam attach-role-policy --role-name $EXEC_ROLE \
  --policy-arn arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy
Append variables
cat >> ~/jenkinslab/aws-part4.env <<EOF
export VPC_ID=$VPC_ID SUBNETS=$SUBNETS TASK_SG=$TASK_SG
EOF
source ~/jenkinslab/aws-part4.env
Verifyaws ecs describe-clusters --clusters myapp-lab --query 'clusters[0].status' returns "ACTIVE"; aws iam get-role --role-name myappTaskExecutionRole --query Role.Arn returns the ARN. Cost: The cluster, log group, security group and role themselves are all free.

Case 1: plugin abandonment breaks a release

Problem: One team had all its pipelines use docker.withRegistry('…', 'ecr:…') (Amazon ECR plugin) to log in to ECR; after a Jenkins core upgrade, plugin compatibility broke, and releases were blocked company-wide. Fix: Switched to running aws ecr get-login-password | docker login --password-stdin on the agent, and wrapped this logic in one step of the shared library. Lesson: Keep deployment logic in standard CLI tools on the agent as much as possible; plugins should only take on Jenkins-specific responsibilities (credentials, agents), which minimizes upgrade risk.

Case 2: App Runner cannot create services in new accounts

Problem: A new business line opened a new AWS account, followed an old blog and used App Runner; creation failed. Root cause: App Runner no longer accepts new customers. Fix: Switch to ECS Express Mode; the Jenkinsfile only needs to change the deployment command to aws ecs create-express-gateway-service / update.

Case 3: EKS just to run one API

Problem: A three-person team deployed a single Flask API to a self-managed EKS; cluster fees, node fees, kubeconfig and access-entry maintenance cost far more than the application was worth. Fix: Moved to ECS on Fargate; the deployment role’s permissions went from “two systems, IAM + K8s RBAC” down to one set of ECS APIs. Limit: If the company already has a shared EKS platform, application teams should get only namespace-level permissions for this to be cost-effective.

Common errors and fixes

Unable to assume the service linked role. Please verify that the ECS service linked role exists.

Cause: First use of ECS in a new account: the service-linked role AWSServiceRoleForECS has not been created yet (usually created automatically, occasionally with a delay).

aws iam get-role --role-name AWSServiceRoleForECS || aws iam create-service-linked-role --aws-service-name ecs.amazonaws.com
An error occurred (InvalidGroup.Duplicate) when calling the CreateSecurityGroup operation: The security group 'myapp-task-sg' already exists

Cause: Repeated execution of the lab. Fix: Look up the existing ID and reuse it:

aws ec2 describe-security-groups --filters Name=group-name,Values=myapp-task-sg --query 'SecurityGroups[0].GroupId' --output text
You've reached the limit on the number of vCPUs you can run concurrently

Cause: The Fargate On-Demand vCPU quota is insufficient (common in new accounts). Fix: Check and request an increase in Service Quotas; in the lab, reduce desiredCount.

InvalidParameterException: The specified log group does not exist.

Cause: The task definition references a CloudWatch log group that does not exist. Fix:aws logs create-log-group --log-group-name /ecs/myapp (already created in this module’s lab).

Command-line tasks
1. List the default subnet ID for each Availability Zone in the default VPC, joined with commas.
aws ec2 describe-subnets --filters Name=vpc-id,Values=$VPC_ID Name=default-for-az,Values=true \
  --query 'Subnets[].SubnetId' --output text | tr '\t' ','
2. Confirm the ECS service-linked role exists and print its ARN.
aws iam get-role --role-name AWSServiceRoleForECS --query Role.Arn --output text
Scenario analysis
The team has 5 HTTP microservices, nobody knows Kubernetes, the boss wants “push and it’s live, like App Runner,” and CI is already Jenkins. What do you recommend? How do you do it on the Jenkins side?

Recommend ECS Express Mode (App Runner does not accept new customers). Jenkins side: the agent obtains the deployment role via an instance profile or Pod Identity (Modules 2 and 6) → aws ecr get-login-password log in → build and push an immutable tag → aws ecs create-express-gateway-service create (first time) / update (thereafter). Put this into a shared library, so each of the 5 services’ Jenkinsfiles needs only a few lines. If a service needs a finer deployment strategy, manage the underlying ECS service directly.

Verified instructional 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 the trade-offs of running containers on ECS and on Lambda
▶
AWS re:Invent 2024 - Unleashing the power of Amazon ECS for platform teams (SVS330) — AWS Events
English · How platform teams provide ECS to application teams

Official documentation

Video storyboard (about 60 seconds)

This courseware cannot generate video/MP3 directly; the storyboard and narration script below can be handed to a video tool.

Shot 1 · 0–15s
Visual: a Jenkins butler icon stands on the left, with four doors on the right: ECS, Express Mode, EKS, Lambda; the App Runner door has a sign reading “no new guests.”
Narration: to deploy from Jenkins to AWS, first decide which door the application goes behind.
Shot 2 · 15–40s
Visual: above each door, the matching CLI command appears: register-task-definition, update-kubeconfig, update-alias.
Narration: Jenkins has no official deployment plugin; deployment is a set of AWS CLI commands on the agent, and plugins only handle credentials and agents.
Shot 3 · 40–60s
Visual: two keys are separated: a “deployment role” key handed to Jenkins, and a “runtime role” key handed to the ECS task.
Narration: the deployment role handles releases, and the runtime role lets the application access AWS. Keeping the two separate is what least privilege means.
or reach a score of ≥ 70% on the quiz

Module 2 · Identity from Jenkins to AWS: IAM roles, instance profiles & OIDC

05:00 – 13:00 · Only two key questions: where do the credentials come from, and does the controller or the agent request them from STS?
8 minAWS Credentials 265 · OpenID Connect Provider 234Core module★★★★★
Learning objectives
  • List the 5 ways Jenkins accesses AWS, and for each one state its credential source, where it is resolved (controller / agent), its isolation granularity, and whether it involves long-term keys.
  • Create a deployment role jenkins-myapp-deployer (least privilege + trust policy), and in the pipeline, through AmazonWebServicesCredentialsBinding the roleArn to exchange for 1-hour temporary credentials.
  • Understand the prerequisite for the OpenID Connect Provider plugin to make Jenkins itself an OIDC issuer (publicly reachable HTTPS or hosted static JSON), and write a trust policy restricted by job URL.
  • Know when long-term keys are still unavoidable, and how to shrink them down to “may only AssumeRole one role.”
Prerequisite knowledge: The difference between IAM roles, trust policies and permission policies; the withCredentials. Importance:★★★★★

What: overview of the five approaches (verified 2026-11)

#ApproachCredential sourceWho requests credentials from STSLong-term keys?Isolation granularity
AAWS Credentials plugin: access keys + roleArnIAM user access keys, encrypted and stored in JENKINS_HOMEcontroller (the plugin calls STS in the controller JVM sts:AssumeRole, default 3600 seconds)YesPer Jenkins credential (folder-level credentials can limit scope)
BAWS Credentials plugin: access keys left empty + roleArnthe controller’s own default credential chain (such as the instance profile of the EC2 instance hosting the controller)controllerNonePer Jenkins credential; but the controller’s own role must be able to AssumeRole all target roles
Cagent-side default credential chain: EC2 instance profile (agents launched by the EC2 Fleet / Amazon EC2 plugin)agent host’s IMDSv2agent the AWS CLI / SDK on theNonePer agent (label / node pool) — all jobs on the same agent share this role
DEKS Pod Identity / IRSA: Pod agent created by the Kubernetes plugin on EKSPod’s service account (Pod Identity Agent or projected service account token)agent Pod the CLI / SDK on theNonePer Pod template’s serviceAccountName
EOpenID Connect Provider plugin + AssumeRoleWithWebIdentityJWT signed by Jenkins with its own private key for each build (default sub = job URL)agent the CLI on theNone (but Jenkins’ signing private key is a new “root secret”)Per job / branch (trust policy matches sub) — the finest

B’s behavior comes from the plugin source code AWSCredentialsImpl.resolveCredentials(): when an IAM role is configured and the access key and private key are both empty, “delegation to instance profile” is used, constructing the STS client with the SDK default provider chain. The plugin page does not document this; it is an implementation detail, so verify it yourself after upgrades. Pipeline: AWS Steps of the withAWS(role:…, roleAccount:…) can also AssumeRole; the documentation says it “looks up credentials on the controller by default,”useNode: true when it is changed to obtain them on the current node; its withAWS documentation does not list a Web Identity option.

Why: why “where it is resolved” matters more than “which plugin is used”

  • A / B are resolved on the controller: the controller must be able to reach STS; B uses the controller ’s instance profile, not the agent’s. Many people put the controller on EC2 and agents elsewhere precisely to achieve “no keys on the controller” with B.
  • C / D are resolved on the agent: Jenkins knows nothing about the AWS credentials; sh 'aws …' is directly usable. The cost is that isolation granularity becomes coarser: anyone who can schedule a job onto this agent can use this role. So for a role that “can deploy to production,” create a dedicated label / node pool, and combine it with the authorization controls of Course 6 to govern who can use this label.
  • E is closest to the GitHub Actions OIDC model: the trust policy can be written to allow only the myapp ’s main branch. But AWS fetches the public key from the issuer on every AssumeRoleWithWebIdentity call, so the issuer URL must be reachable by AWS; a local 127.0.0.1:8080 Jenkins cannot do this, unless you use an “alternate issuer” to host the two static JSON files on public HTTPS (such as an S3 static website + CloudFront).

How: honestly, when long-term keys are still unavoidable

ScenarioWhyMitigation
This course’s local Jenkins (Docker Compose, 127.0.0.1)Not on AWS (no instance profile), and the issuer is not publicly reachableIAM user Only allow sts:AssumeRole to one role; you may add aws:SourceIp conditions; delete after the lab (Module 8)
On-premises Jenkins with an enterprise PKISame as aboveConsider IAM Roles Anywhere (exchanging X.509 certificates for temporary credentials; requires configuring a credential helper on the agent yourself; not covered in this course)
On-premises Jenkins that can publish static files—OIDC Provider plugin + alternate issuer (method E), removing keys completely
Jenkins on AWS—should have no long-term keys: the controller uses B, agents use C / D

When: recommended combinations

  • Jenkins on EC2, agents via EC2 Fleet: the agent instance profile (C) is granted only the permission to “AssumeRole the deployment role,” and deployment roles are split by environment.
  • Jenkins on EKS: the controller and agent Pods each use a service account + Pod Identity (D); Pods that need to run on EKS Fargate use IRSA instead (Pod Identity does not support Fargate).
  • Multi-cloud / hybrid / need per-job permissions: OIDC Provider plugin (E).
  • Just doing a lab: A, with strictly limited permissions, deleted when finished.
Common misconceptions① “If the AWS Credentials plugin key is left empty, it uses the agent’s instance profile”: no; binding is resolved on the controller, using the controller’s credential chain. ② “Jenkins natively supports OIDC, just like GitHub Actions”: the core does not; it requires the OpenID Connect Provider plugin, and the issuer must be publicly reachable. ③ “If the log shows **** it is safe”: masking only prevents verbatim output; anyone who can edit the Jenkinsfile can obtain temporary credentials, so the deployment role’s permissions and session duration are the real boundary. ④ “Pod Identity and IRSA are interchangeable, they work anywhere”: Pod Identity does not support Pods on Fargate, and IRSA requires creating an IAM OIDC provider for each cluster.

Comparison of the five identity chains

ApproachCredential sourceSTS APIResult A access keyresolved on controller AKIA… encrypted in JENKINS_HOME(long-lived, needs rotation) AssumeRole B key left emptyresolved on controller controller’s IMDSv2 /controller Pod’s Pod Identity AssumeRole C instance profileresolved on agent agent EC2’s IMDSv2(EC2 rotates automatically) (optional) AssumeRolecredential_source=Ec2InstanceMetadata D Pod Identity/IRSAresolved on agent Pod service account → 169.254.170.23 /projected token AWS_WEB_IDENTITY_TOKEN_FILE eks-auth:AssumeRoleForPodIdentity/ AssumeRoleWithWebIdentity E Jenkins OIDCresolved on agent controller issues JWT (sub = job URL)→ token file handed to agent AssumeRoleWithWebIdentity temporary credentials for the deployment roleASIA… + SessionTokendefault 1 hour→ ECR / ECS / EKS / LambdaCloudTrail records the session name Red: has long-term keys; yellow: no keys but permissions concentrated on the controller; green: no keys, resolved on the agent
Figure 2-1: all five paths ultimately exchange for the same thing: short-term session credentials for the deployment role

What trust policies look like (three kinds of Principal)

A / B / C: AWS principal "Principal": {"AWS": "arn:aws:iam::111122223333: user/jenkins-lab-bootstrap"}or role/jenkins-agent-ec2"Action": "sts:AssumeRole"The caller also needs an identity policy that allows it D (Pod Identity): service principal "Principal": {"Service": "pods.eks.amazonaws.com"}"Action": ["sts:AssumeRole", "sts:TagSession"]The binding relationship is on the EKS side:create-pod-identity-association D (IRSA) / E: federated principal "Principal": {"Federated": "…:oidc-provider/jenkins.example.com/oidc"}"Action": "sts:AssumeRoleWithWebIdentity"Condition: …:aud = sts.amazonaws.com …:sub = allowed job / SA
Figure 2-2: “who may assume this role” is written in the trust policy; “what you can do after assuming it” is written in the permission policy

Core animation: how credentials reach AWS

Choose an identity method, then play. Orange highlighting shows the components currently involved; the log area shows the real API calls / environment variables / Jenkins logs for that step.

agent (sh step)aws CLI / docker controllerCredential store · binding resolution Credential source(choose method) AWS STSIssue temporary credentials IAM evaluationTrust policy + permission policy ECR myappGetAuthorizationToken · push ECS myapp-labRegisterTaskDefinition · UpdateService CloudTrailwho, which session, what was called
First choose an identity method (default A).
Three things to watch while viewing the animation① Does the controller box light up? If so, the credentials are resolved on the controller. ② In the credential source box, is it a “long-term key” or “metadata / token”? ③ The session name last recorded in CloudTrail: in production it should trace back to a specific job and build number.

Commands and configuration at a glance

Command / configurationPurposeKey points
aws iam create-role --assume-role-policy-documentCreate deployment role and trust policyUsers/roles referenced in the trust policy must already exist
aws iam put-role-policyInline permission policyECR push, ECS deployment,iam:PassRole (restricted to iam:PassedToService)
[$class: 'AmazonWebServicesCredentialsBinding', credentialsId, roleArn, roleSessionName]AWS Credentials plugin bindinginjects AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY (add AWS_SESSION_TOKEN when there is a roleArn)
withAWS(role:…, roleAccount:…, region:…)Pipeline: AWS StepsBy default credentials are fetched on the controller; useNode: true fetched on the current node
file(credentialsId: 'aws-oidc-idtoken', variable: 'AWS_WEB_IDENTITY_TOKEN_FILE')OIDC Provider plugin (token file)then set AWS_ROLE_ARN, the CLI automatically calls AssumeRoleWithWebIdentity
aws iam create-open-id-connect-provider --url … --client-id-list sts.amazonaws.comRegister Jenkins issuerWhen the certificate is issued by a trusted CA, AWS validates it using its built-in root store and does not depend on the thumbprint
aws sts get-caller-identity“Who am I right now”The first command for any identity problem; requires no permissions

1) Permission policy for the deployment role (least privilege)

source ~/jenkinslab/aws-part4.env
cat > deployer-policy.json <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    { "Sid": "EcrAuth", "Effect": "Allow", "Action": "ecr:GetAuthorizationToken", "Resource": "*" },
    { "Sid": "EcrPushMyapp", "Effect": "Allow",
      "Action": ["ecr:BatchCheckLayerAvailability","ecr:InitiateLayerUpload","ecr:UploadLayerPart",
                 "ecr:CompleteLayerUpload","ecr:PutImage","ecr:BatchGetImage","ecr:DescribeImages",
                 "ecr:DescribeImageScanFindings"],
      "Resource": "arn:aws:ecr:$AWS_REGION:$ACCOUNT_ID:repository/myapp" },
    { "Sid": "EcsDeploy", "Effect": "Allow",
      "Action": ["ecs:RegisterTaskDefinition","ecs:DescribeTaskDefinition","ecs:DescribeServices",
                 "ecs:UpdateService","ecs:DescribeTasks","ecs:ListTasks"],
      "Resource": "*" },
    { "Sid": "PassOnlyExecRoleToEcs", "Effect": "Allow", "Action": "iam:PassRole",
      "Resource": "arn:aws:iam::$ACCOUNT_ID:role/$EXEC_ROLE",
      "Condition": { "StringEquals": { "iam:PassedToService": "ecs-tasks.amazonaws.com" } } }
  ]
}
EOF

RegisterTaskDefinition does not support resource-level restrictions, so use *; UpdateService In production, restrict it to the specific service ARN (arn:aws:ecs:ca-central-1:111122223333:service/myapp-lab/myapp).

2) Jenkinsfile snippets for each method

// A: access key + AssumeRole (the local lab in this course)
withCredentials([[$class: 'AmazonWebServicesCredentialsBinding',
                  credentialsId: 'aws-lab-bootstrap',
                  roleArn: "arn:aws:iam::${env.ACCOUNT_ID}:role/jenkins-myapp-deployer",
                  roleSessionName: "jenkins-myapp-${env.BUILD_NUMBER}"]]) {
  sh 'aws sts get-caller-identity'
}

// C / D: the agent has its own identity; no Jenkins credentials needed
node('aws-deploy') {                       // dedicated label; only trusted jobs are scheduled here
  sh 'aws sts get-caller-identity'
}

// E: OpenID Connect Provider plugin
withEnv(["AWS_ROLE_ARN=arn:aws:iam::${env.ACCOUNT_ID}:role/jenkins-myapp-oidc",
         "AWS_ROLE_SESSION_NAME=jenkins-myapp-${env.BUILD_NUMBER}"]) {
  withCredentials([file(credentialsId: 'aws-oidc-idtoken', variable: 'AWS_WEB_IDENTITY_TOKEN_FILE')]) {
    sh 'aws sts get-caller-identity'
  }
}

How to verify: The output Arn should be arn:aws:sts::111122223333:assumed-role/jenkins-myapp-deployer/jenkins-myapp-42. Common errors: Putting roleArn into the “IAM Role To Use” field of the credential while also writing roleArn in the binding, so when troubleshooting you cannot tell which role was actually assumed — choose one place only. Production use: The session name includes the build number, so CloudTrail lets you trace API calls back to a specific build.

3) Role chaining with a profile on the agent (recommended approach for method C)

# ~/.aws/config on the agent image/AMI (contains no keys)
[profile deployer]
role_arn = arn:aws:iam::111122223333:role/jenkins-myapp-deployer
credential_source = Ec2InstanceMetadata
role_session_name = jenkins-agent
region = ca-central-1
sh 'AWS_PROFILE=deployer aws sts get-caller-identity'

instance profile role jenkins-agent-ec2 only has sts:AssumeRole permission; the real deployment permissions are in jenkins-myapp-deployer; split out …-dev / …-prod two deployment roles by environment, and the agent role itself needs no change.

Lab 2: create a deployment role and have Jenkins print “who am I” (about 6 minutes)

Cost / permissions / risks IAM is free. This lab creates one long-term access key (method A), which can only AssumeRole into jenkins-myapp-deployer; do not copy this into production; Module 8 deletes it. Requires your administrator identity (IAM write permissions).
Create a bootstrap user that can only AssumeRole (local machine)
source ~/jenkinslab/aws-part4.env
aws iam create-user --user-name jenkins-lab-bootstrap --tags Key=course,Value=jenkins-part4
cat > bootstrap-policy.json <<EOF
{ "Version": "2012-10-17",
  "Statement": [{ "Effect": "Allow", "Action": "sts:AssumeRole",
                  "Resource": "arn:aws:iam::$ACCOUNT_ID:role/$DEPLOY_ROLE" }] }
EOF
aws iam put-user-policy --user-name jenkins-lab-bootstrap --policy-name only-assume-deployer \
  --policy-document file://bootstrap-policy.json
Create the deployment role (trusting the bootstrap user, maximum session 1 hour)
cat > deployer-trust.json <<EOF
{ "Version": "2012-10-17",
  "Statement": [{ "Effect": "Allow",
                  "Principal": { "AWS": "arn:aws:iam::$ACCOUNT_ID:user/jenkins-lab-bootstrap" },
                  "Action": "sts:AssumeRole" }] }
EOF
aws iam create-role --role-name $DEPLOY_ROLE --assume-role-policy-document file://deployer-trust.json \
  --max-session-duration 3600 --tags Key=course,Value=jenkins-part4
aws iam put-role-policy --role-name $DEPLOY_ROLE --policy-name deploy-myapp \
  --policy-document file://deployer-policy.json     # file generated by the commands on the previous page
Generate access keys and enter them into Jenkins
aws iam create-access-key --user-name jenkins-lab-bootstrap \
  --query 'AccessKey.[AccessKeyId,SecretAccessKey]' --output text

Jenkins → Manage Jenkins → Credentials → System → Global credentials → Add Credentials: choose Kind AWS Credentials, set ID to aws-lab-bootstrap, enter the Access Key ID and Secret Access Key,leave IAM Role To Use empty (this course passes roleArn in the binding). After saving, immediately clear the keys from the terminal history.

Add a temporary Jenkinsfile stage in the myapp repository (or create a new Pipeline job aws-whoami, using the script below)
pipeline {
  agent { label 'linux docker' }
  environment { AWS_REGION = 'ca-central-1'; ACCOUNT_ID = '111122223333' }   // replace with your account number
  stages {
    stage('whoami') {
      steps {
        withCredentials([[$class: 'AmazonWebServicesCredentialsBinding', credentialsId: 'aws-lab-bootstrap',
                          roleArn: "arn:aws:iam::${env.ACCOUNT_ID}:role/jenkins-myapp-deployer",
                          roleSessionName: "jenkins-myapp-${env.BUILD_NUMBER}"]]) {
          sh '''
            aws sts get-caller-identity
            test -n "$AWS_SESSION_TOKEN" && echo "Temporary credentials: session token present"
          '''
        }
      }
    }
  }
}
[Pipeline] withCredentials
Masking supported pattern matches of $AWS_ACCESS_KEY_ID or $AWS_SECRET_ACCESS_KEY or $AWS_SESSION_TOKEN
[Pipeline] sh
+ aws sts get-caller-identity
{
    "UserId": "AROAEXAMPLEROLEID:jenkins-myapp-7",
    "Account": "111122223333",
    "Arn": "arn:aws:sts::111122223333:assumed-role/jenkins-myapp-deployer/jenkins-myapp-7"
}
Temporary credentials: session token present
Verify that the bootstrap key itself has almost no permissions (on this machine, using the newly generated key)
AWS_ACCESS_KEY_ID=AKIA... AWS_SECRET_ACCESS_KEY=... aws ecr describe-repositories --region ca-central-1
An error occurred (AccessDeniedException) when calling the DescribeRepositories operation: User: arn:aws:iam::111122223333:user/jenkins-lab-bootstrap is not authorized to perform: ecr:DescribeRepositories ...

This is exactly the intended result: leaking this key is limited to “can assume the deployment role for 1 hour,” and the deployment role can only act on myapp.

Advanced (optional, requires a Jenkins reachable over public HTTPS): method E, removing keys completely

Create the OIDC credential: Add Credentials → choose Kind OpenID Connect id token as file, ID aws-oidc-idtoken, set Audience to sts.amazonaws.com, then after saving click Update to view the generated issuer (such as https://jenkins.example.com/oidc). If AWS cannot reach Jenkins, enter in the issuer field an HTTPS address where you can host static files; the plugin will provide the contents of the two JSON files to host.
Register the identity provider and create the role
aws iam create-open-id-connect-provider --url https://jenkins.example.com/oidc \
  --client-id-list sts.amazonaws.com
cat > oidc-trust.json <<EOF
{ "Version": "2012-10-17",
  "Statement": [{ "Effect": "Allow",
    "Principal": { "Federated": "arn:aws:iam::$ACCOUNT_ID:oidc-provider/jenkins.example.com/oidc" },
    "Action": "sts:AssumeRoleWithWebIdentity",
    "Condition": { "StringEquals": {
      "jenkins.example.com/oidc:aud": "sts.amazonaws.com",
      "jenkins.example.com/oidc:sub": "https://jenkins.example.com/job/myapp-multibranch/job/main/" } } }] }
EOF
aws iam create-role --role-name jenkins-myapp-oidc --assume-role-policy-document file://oidc-trust.json
aws iam put-role-policy --role-name jenkins-myapp-oidc --policy-name deploy-myapp --policy-document file://deployer-policy.json

sub The default is the job URL; for a multibranch pipeline the main branch URL looks like …/job/myapp-multibranch/job/main/. You can customize it in the claim template under Configure Global Security → OpenID Connect (keep at least sub). This step was not actually run in this course environment (the local Jenkins has no public issuer); the commands were written from the plugin README and IAM documentation.

Case 1: a backup leaked JENKINS_HOME

Problem: A company backed up JENKINS_HOME to an S3 bucket with overly broad permissions; it contained credentials.xml and secrets/ directories — with both, every credential could be decrypted, including an AWS access key with AdministratorAccess. Fix: The controller was moved to EC2; AWS Credentials were changed to “key left empty + role ARN” (method B), and agents changed to EC2 Fleet + instance profile (method C); all old keys were revoked; IAM Access Analyzer was used to find long-term keys still in use. Limit: The controller’s instance profile becomes a new high-value target, so restrict who can log in to the controller host and who can write to the Groovy script console.

Case 2: “anyone can deploy to production” on shared agents

Problem: The agent pool used the same instance profile, which had production deployment permissions; any developer could write sh 'aws ecs update-service …' in their own branch’s Jenkinsfile and change production. Fix: Split into two node pools: aws-build (can only push to ECR) and aws-deploy-prod (can only be used by the deployment jobs of main branches, combined with the Course 6 authorization policies and job restrictions); the production deployment role’s trust policy trusts only the instance role of the aws-deploy-prod pool. Limit: Agent-level isolation is still less fine-grained than per-job isolation with method E.

Case 3: on-premises Jenkins uses OIDC to remove keys

Problem: Jenkins is on the internal network, and the security team prohibits new long-term keys. Fix: The OpenID Connect Provider plugin uses an alternate issuer, placing .well-known/openid-configuration and the JWKS two static files on S3 + CloudFront (public HTTPS); IAM registers this issuer; the trust policy is restricted by job URL. Limit: After rotating the signing key (click Update on the credential and then save), the hosted JWKS must be updated too, otherwise STS reports InvalidIdentityToken.

Common errors and fixes

User: arn:aws:iam::111122223333:user/jenkins-lab-bootstrap is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::111122223333:role/jenkins-myapp-deployer

Cause: Both sides must allow it: the caller’s identity policy allows sts:AssumeRole,and the role’s trust policy Principal includes the caller. Commonly the trust policy has the wrong account number or user name, or the role was recreated (the ARN in the trust policy points to the old principal’s unique ID).

aws iam get-role --role-name jenkins-myapp-deployer --query Role.AssumeRolePolicyDocument
aws iam get-user-policy --user-name jenkins-lab-bootstrap --policy-name only-assume-deployer

Fix: Align the ARNs on both sides; if the principal was deleted and recreated, re-save the trust policy.

Unable to locate credentials. You can configure credentials by running "aws configure".

Cause:sh 'aws …' Running on the agent, where the agent’s default credential chain is empty: not inside a withCredentials block; the agent is not on EC2; or the EC2 instance has no instance profile; or the container’s IMDSv2 hop count is insufficient (see Module 7).

env | grep -E '^AWS_' | sed 's/=.*/=***/'      # show variable names only
aws configure list
An error occurred (InvalidIdentityToken) when calling the AssumeRoleWithWebIdentity operation: Couldn't retrieve verification key from your identity provider

Cause: In method E, STS cannot reach the Jenkins issuer’s discovery / JWKS (Jenkins is on the internal network, blocked by a firewall or SSO, or the certificate chain order is wrong), or the JWKS hosted by the alternate issuer does not match the current signing key.

curl -s https://jenkins.example.com/oidc/.well-known/openid-configuration | jq .
curl -s "$(curl -s https://jenkins.example.com/oidc/.well-known/openid-configuration | jq -r .jwks_uri)" | jq '.keys[].kid'
An error occurred (InvalidIdentityToken) when calling the AssumeRoleWithWebIdentity operation: No OpenIDConnect provider found in your account for https://jenkins.example.com/oidc

Cause: The URL registered in IAM and the token iss do not match exactly (extra or missing path, trailing slash, or case). Fix: Decode the token (look at the payload only; do not paste it anywhere online) and check iss, then rebuild the identity provider with its values.

An error occurred (AccessDenied) when calling the AssumeRoleWithWebIdentity operation: Not authorized to perform sts:AssumeRoleWithWebIdentity

Cause: Trust policy condition mismatch: sub is another branch / job (for example a PR build …/job/PR-12/), or the audience is not sts.amazonaws.com. Fix: Check the request parameters of the failed event in CloudTrail, and adjust the condition according to the real sub ; do not simplify by changing the condition to StringLike "*".

Command-line tasks
1. Without printing any keys, confirm which identity the current shell uses and which source the credentials come from.
aws sts get-caller-identity --query Arn --output text
aws configure list        # the Type column shows env / shared-credentials-file / iam-role / container-role, etc.
2. Add one more principal to the deployment role’s trust policy: the EC2 agent’s role jenkins-agent-ec2.
cat > trust2.json <<EOF
{ "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": "sts:AssumeRole",
  "Principal": { "AWS": ["arn:aws:iam::$ACCOUNT_ID:user/jenkins-lab-bootstrap",
                         "arn:aws:iam::$ACCOUNT_ID:role/jenkins-agent-ec2"] } }] }
EOF
aws iam update-assume-role-policy --role-name jenkins-myapp-deployer --policy-document file://trust2.json
Scenario analysis
The Jenkins controller is on EC2, and the agent is a Pod in EKS. The team wants to “store absolutely no keys,” and requires that only the myapp branch of the main can deploy to prod. How would you design it?

Agent Pods use Pod Identity (the build uses service account jenkins-build that can only push to ECR). There are two ways to do prod deployment: ① use the OIDC Provider plugin (the controller is on EC2, so it can be given public HTTPS or an alternate issuer), with the prod role trust policy’s sub exact match …/job/myapp-multibranch/job/main/; ② a separate Pod template + service account jenkins-deploy-prod (Pod Identity association with the prod role), then use Jenkins authorization (Course 6) to restrict use of that Pod template to main-branch jobs only. The isolation in ① is enforced on the AWS side; ② depends on Jenkins being configured correctly. Neither requires long-term keys.

Verified instructional videos

▶
EKS Pod Identity vs IRSA | Securely Connect Kubernetes Pods to AWS Services — Containers from the Couch
English · AWS containers team talk that explains the two implementations of method D; the EKS user guide page also embeds this video
▶
How to Give AWS IAM Role in Jenkins | AWS IAM Role Training | Jenkins IAM Role Tutorial — Dorothy Scott
English · third-party introductory demo, usable as a UI reference for Jenkins + IAM roles; this course and the official documentation take precedence

No verified video explaining the Jenkins OpenID Connect Provider plugin + AWS was found; see the storyboard below.

Official documentation

Video storyboard (about 90 seconds)

This courseware cannot generate video/MP3 directly; the storyboard and narration script below can be handed to a video tool.

Shot 1 · 0–20s
Visual: in a Jenkins safe lies a bronze key marked AKIA, with no expiry date on it.
Narration: the simplest approach is to store an access key in Jenkins, but this key never expires, and whoever obtains it can use it.
Shot 2 · 20–45s
Visual: the agent server takes a temporary card from the “metadata service” beneath its feet, one that self-destructs after one hour; on the other side, an EKS Pod receives its card from the Pod Identity Agent.
Narration: when the agent runs on AWS, credentials come from the instance profile or the Pod’s service account, so Jenkins never needs to store a key.
Shot 3 · 45–75s
Visual: the Jenkins controller stamps and issues a JWT whose sub equals the job address; STS checks the stamp against Jenkins’ jwks address with a magnifying glass.
Narration: the OpenID Connect Provider plugin makes Jenkins its own issuer; AWS comes back to fetch the public key every time, so the issuer address must be reachable from the internet.
Shot 4 · 75–90s
Visual: all routes converge into the same “temporary credentials for the deployment role,” and CloudTrail records the session name jenkins-myapp-42.
Narration: different roads, same destination: ultimately one-hour temporary credentials, with the permission boundary set on the deployment role.
or reach a score of ≥ 70% on the quiz

Module 3 · Build and push to ECR

13:00 – 21:00 · The ECR docker password lives only 12 hours, so fetch it fresh on each build; tags are immutable, and deployment uses the digest
8 minECR private repository myappIMMUTABLE + scanOnPush★★★★★
Learning objectives
  • Explain aws ecr get-login-password behind the GetAuthorizationToken: the token is valid for 12 hours, and its permission scope equals the IAM identity that fetched it.
  • Know why ECR should not be stored as a Jenkins registry-creds (username and password) credential, and the residual risk of Docker credentials on agents (DOCKER_CONFIG isolation).
  • Create immutable tags, scan-on-push, and a repository with a lifecycle policy myapp, and in the Jenkinsfile build, test, push and obtain digest.
Prerequisite knowledge: Images, tags and digests from the Docker course; the deployment role from Module 2. Importance:★★★★★

What: several key facts about ECR (verified)

  • One private registry per account per region: 111122223333.dkr.ecr.ca-central-1.amazonaws.com, repositories myapp.
  • The Docker CLI does not support IAM authentication. ECR uses GetAuthorizationToken returns a base64 “username AWS + password,”valid for 12 hours, with a permission scope equal to the IAM principal that obtained it; aws ecr get-login-password only decodes it for you.
  • One docker push corresponding IAM actions: BatchCheckLayerAvailability → InitiateLayerUpload → UploadLayerPart → CompleteLayerUpload → PutImage. Layers that already exist are skipped (Layer already exists).
  • Tag mutability: IMMUTABLE When set to IMMUTABLE, the same tag cannot be repointed to a new digest; a repeated push reports tag invalid … cannot be overwritten because the repository is immutable.
  • Scan on push (basic scanning) and enhanced scanning (Amazon Inspector, billed per image); lifecycle policies expire old images according to rules.

Why: why not use registry-creds

The registry-creds from the previous two courses is a “username + password” credential, suitable for static-password registries such as Gitea/Harbor. The ECR password expires after 12 hours; storing it in Jenkins just means “it worked yesterday and gives 401 today.” The correct approach is to fetch it fresh using the current AWS identity on every build:

aws ecr get-login-password --region ca-central-1 | docker login --username AWS --password-stdin 111122223333.dkr.ecr.ca-central-1.amazonaws.com

Another easily overlooked point: docker login writes the token into ~/.docker/config.json on the agent, and for 12 hours other jobs on the same agent can use it to push. Use DOCKER_CONFIG=$WORKSPACE_TMP/docker to confine the login to the build’s temporary directory, and docker logout when finished.

How: comparison of three login methods

MethodApplicable toNotes
get-login-password | docker loginAll identity methods (A–E)Official documented method; this course’s main path
Amazon ECR Docker Credential Helper (docker-credential-ecr-login)Agent has its own identity (C / D)Docker fetches tokens each time it needs one via the default credential chain, storing no password on disk; the official documentation notes MFA is not yet supported
Amazon ECR plugin docker.withRegistry('https://…', 'ecr:ca-central-1:aws-lab-bootstrap')Existing legacy pipelinesPlugin version 1.175 is currently “looking for a maintainer”; new pipelines should not depend on it

When: tag and digest strategy

  • Tag = human-readable version: 1.1-<7-character commit ID> (corresponding to the Docker course’s myapp:1.1); immutable, never reused.
  • Deployment references digest (myapp@sha256:…): even if someone changes the repository back to MUTABLE, what is deployed is still the exact bytes you tested.
  • Do not push latest to an immutable repository — the second push would fail, and you do not need it.
Common misconceptions① “ECR tokens expire after 1 hour, like IAM credentials”: ECR tokens last 12 hours and are unrelated to the STS session that obtained them; after the session expires, an already-logged-in docker can still push until the token expires. ② “Enabling scanOnPush makes it secure”: basic scanning only checks operating-system package vulnerabilities; results must be actively read in the pipeline and used to decide whether to block. ③ “Lifecycle policies only delete unused images”: they do not know which image is being referenced by ECS/Lambda; deleting an image that Lambda references puts the function into the Failed state.

Build → push data flow

agent1 (linux docker) 1 checkout lab/myapp2 docker build -t myapp:1.1-abc12343 pytest (inside container)4 get-login-password5 docker push6 describe-images → digest7 docker logout HTTPS api.ecr.ca-central-1GetAuthorizationToken (12h) Registry v2 *.dkr.ecr…/myappLayer upload → PutImageIMMUTABLE checks tag Basic scanningscanOnPush→ findings LifecycleKeep latest 10Untagged for 1 day Output to the next stageIMAGE_URI = …/myapp@sha256:9f2c…
Figure 3-1: two endpoints: api.ecr issues tokens, dkr.ecr receives images; the deployment stage gets the digest

Lifetime comparison of tokens and credentials

0h6h12h STS 1h ECR authorization token (the docker login password) 12 hours — kept in ~/.docker/config.json IAM user access keys: no expiry (until deleted or rotated)
Figure 3-2: session expiry does not mean the docker login state is invalid, so isolate it with DOCKER_CONFIG and log out in post

Animation: what happens on the ECR side during one docker push

After choosing a scenario, play: normal push, layers already exist (second build), immutable tag conflict. The log shows Docker output and the corresponding IAM actions / APIs.

docker CLIagent1 ECR APIGetAuthorizationToken Registry endpoint/v2/myapp/… Layer 1 python:3.12-slim Layer 2 pip install Layer 3 application code Manifest + tagPutImage Scan / eventsscanOnPushEventBridge
Select a scenario first (default: first push).

Command overview

CommandPurposeKey parameters
aws ecr create-repositoryCreate repository--image-tag-mutability IMMUTABLE,--image-scanning-configuration scanOnPush=true
aws ecr put-lifecycle-policyautomatically clean up old images--lifecycle-policy-text file://…
aws ecr get-login-password | docker logindocker loginusername is fixed AWS,--password-stdin
aws ecr describe-images --image-ids imageTag=…get digest, push time, scan status--query 'imageDetails[0].imageDigest'
aws ecr wait image-scan-completewait for the scan to finishafterwards describe-image-scan-findings
aws ecr batch-delete-imagedelete imageused during cleanup
source ~/jenkinslab/aws-part4.env
aws ecr create-repository --repository-name $ECR_REPO \
  --image-tag-mutability IMMUTABLE \
  --image-scanning-configuration scanOnPush=true \
  --tags Key=course,Value=jenkins-part4 \
  --query 'repository.repositoryUri' --output text
111122223333.dkr.ecr.ca-central-1.amazonaws.com/myapp
cat > lifecycle.json <<'EOF'
{ "rules": [
  { "rulePriority": 1, "description": "untagged after 1 day",
    "selection": { "tagStatus": "untagged", "countType": "sinceImagePushed", "countUnit": "days", "countNumber": 1 },
    "action": { "type": "expire" } },
  { "rulePriority": 2, "description": "keep last 10",
    "selection": { "tagStatus": "any", "countType": "imageCountMoreThan", "countNumber": 10 },
    "action": { "type": "expire" } } ] }
EOF
aws ecr put-lifecycle-policy --repository-name $ECR_REPO --lifecycle-policy-text file://lifecycle.json

Jenkinsfile: build, test, push (method A; for methods C/D, simply remove withCredentials)

pipeline {
  agent { label 'linux docker' }
  options { disableConcurrentBuilds(); buildDiscarder(logRotator(numToKeepStr: '20')) }
  environment {
    AWS_REGION = 'ca-central-1'
    ACCOUNT_ID = '111122223333'
    REGISTRY   = '111122223333.dkr.ecr.ca-central-1.amazonaws.com'
    DEPLOY_ROLE_ARN = 'arn:aws:iam::111122223333:role/jenkins-myapp-deployer'
  }
  stages {
    stage('Build') {
      steps {
        script {
          env.IMAGE_TAG = '1.1-' + sh(returnStdout: true, script: 'git rev-parse --short=7 HEAD').trim()
        }
        sh 'docker build --pull -t myapp:$IMAGE_TAG .'
      }
    }
    stage('Test') {
      steps { sh 'docker run --rm myapp:$IMAGE_TAG python -m pytest -q' }
    }
    stage('Push to ECR') {
      environment { DOCKER_CONFIG = "${env.WORKSPACE_TMP}/docker" }   // the login state belongs only to this build
      steps {
        withCredentials([[$class: 'AmazonWebServicesCredentialsBinding', credentialsId: 'aws-lab-bootstrap',
                          roleArn: env.DEPLOY_ROLE_ARN, roleSessionName: "jenkins-myapp-${env.BUILD_NUMBER}"]]) {
          sh '''
            set -eu
            aws ecr get-login-password --region "$AWS_REGION" | docker login --username AWS --password-stdin "$REGISTRY"
            docker tag myapp:$IMAGE_TAG $REGISTRY/myapp:$IMAGE_TAG
            docker push $REGISTRY/myapp:$IMAGE_TAG
            aws ecr describe-images --repository-name myapp --image-ids imageTag=$IMAGE_TAG \
              --query 'imageDetails[0].imageDigest' --output text > image.digest
          '''
          script { env.IMAGE_URI = "${env.REGISTRY}/myapp@" + readFile('image.digest').trim() }
          echo "IMAGE_URI=${env.IMAGE_URI}"
        }
      }
      post { always { sh 'docker logout $REGISTRY || true' } }
    }
  }
}

How to verify: The console log shows Login Succeeded and …: digest: sha256:… size: …, and finally prints IMAGE_URI=…/myapp@sha256:…. Common errors: The test command depends on pytest being installed in the image — if the production image of myapp does not include test dependencies, switch to a target of a multi-stage build test target (see the Docker course). Production use:image.digest Can be used archiveArtifacts as an archive, for a later release pipeline that “deploys without building.”

Read the scan results and block (optional)

aws ecr wait image-scan-complete --repository-name myapp --image-id imageTag=$IMAGE_TAG
aws ecr describe-image-scan-findings --repository-name myapp --image-id imageTag=$IMAGE_TAG \
  --query 'imageScanFindings.findingSeverityCounts' --output json
# fail if CRITICAL > 0
test "$(aws ecr describe-image-scan-findings --repository-name myapp --image-id imageTag=$IMAGE_TAG \
  --query 'imageScanFindings.findingSeverityCounts.CRITICAL' --output text)" = "None"

Lab 3: push myapp to ECR from the pipeline (about 6 minutes)

Cost ECR storage costs about US$0.10 per GB per month; the myapp image is about 150 MB, which can be ignored during the lab. Pulling from ECR to ECS in the same region incurs no data transfer charge.
Create the repository and lifecycle policy: run the commands from the “Commands” page: create-repository and put-lifecycle-policy.
Commit the Jenkinsfile: commit the Jenkinsfile from the “Commands” page to the Gitea repository lab/myapp in the root directory (replacing the account number), and run the myapp pipeline in Jenkins (the multibranch job created in Course 2 discovers it automatically).
cd ~/src/myapp     # the directory where you cloned lab/myapp in Course 1
git add Jenkinsfile && git commit -m "ci: push to ECR (jenkins part4)" && git push
Check the console output
+ docker push 111122223333.dkr.ecr.ca-central-1.amazonaws.com/myapp:1.1-abc1234
The push refers to repository [111122223333.dkr.ecr.ca-central-1.amazonaws.com/myapp]
5f70bf18a086: Pushed
e3b0c44298fc: Pushed
1.1-abc1234: digest: sha256:9f2c6e0d... size: 1789
IMAGE_URI=111122223333.dkr.ecr.ca-central-1.amazonaws.com/myapp@sha256:9f2c6e0d...
Verify on this machine
aws ecr describe-images --repository-name myapp \
  --query 'imageDetails[].[imageTags[0],imageDigest,imageScanStatus.status]' --output table
Experience immutable tags: in Jenkins, “Replay” (or re-run) the same commit; the Push stage should fail:
tag invalid: The image tag '1.1-abc1234' already exists in the 'myapp' repository and cannot be overwritten because the repository is immutable.

This is a protection, not a fault: an image with the same commit ID already exists. In production the practice is “if it already exists, skip the build and push,” see “Production cases.”

Case 1: re-running a pipeline fails because of an immutable tag

Problem: After a deployment stage failure, the whole pipeline was re-run, and the push stage failed because the tag already existed. Fix: Query before pushing; if it exists, take the digest directly:

if aws ecr describe-images --repository-name myapp --image-ids imageTag=$IMAGE_TAG >/dev/null 2>&1; then
  echo "Image already exists, skipping push"
else
  docker push $REGISTRY/myapp:$IMAGE_TAG
fi

Limit: This assumes tags map one-to-one to source code (including the commit ID); do not use the build number as the only tag.

Case 2: leftover ECR login state on a shared agent

Problem: A security audit found that the static agent’s /home/jenkins/.docker/config.json contained ECR tokens for multiple accounts, so any job scheduled on this agent could push to the production repository. Fix: Pipelines uniformly use DOCKER_CONFIG=$WORKSPACE_TMP/docker,post { always { docker logout } }; the long-term solution is to switch to one-off agents (Module 6).

Case 3: a lifecycle policy deleted an image that Lambda was using

Problem: The “keep the latest 10” rule cleared the image of a rarely invoked Lambda, and the function entered the Failed state. Fix: Use a separate tag prefix for versions that are referenced long-term and exclude them in the rule (tagPrefixList / tagPatternList option), or split by repository; after deployment, periodically verify that “the referenced digests still exist.”

Common errors and fixes

no basic auth credentials

Cause: docker is not logged in to this registry: login and push used different DOCKER_CONFIG, the registry hostname is spelled differently (region, account number), or the login happened on another agent (docker login and docker push are written in different stages / nodes).

echo "$DOCKER_CONFIG"; cat "${DOCKER_CONFIG:-$HOME/.docker}/config.json" | jq '.auths | keys'
denied: User: arn:aws:sts::111122223333:assumed-role/jenkins-myapp-deployer/jenkins-myapp-9 is not authorized to perform: ecr:InitiateLayerUpload on resource: arn:aws:ecr:ca-central-1:111122223333:repository/myapp

Cause: The deployment role lacks the layer upload actions needed for push, or its Resource points to another repository/region. Fix: Add BatchCheckLayerAvailability / InitiateLayerUpload / UploadLayerPart / CompleteLayerUpload / PutImage. Note that GetAuthorizationToken must be "Resource": "*".

An error occurred (RepositoryNotFoundException) when calling the DescribeImages operation: The repository with name 'myapp' does not exist in the registry with id '111122223333'

Cause: Most likely the region is wrong: on the agent, AWS_REGION is not set, while ~/.aws/config defaults to another region. Fix: Explicitly set environment in the Jenkinsfile’s AWS_REGION = 'ca-central-1'.

Error response from daemon: login attempt to https://111122223333.dkr.ecr.ca-central-1.amazonaws.com/v2/ failed with status: 400 Bad Request

Cause: The token came from another region (get-login-password was not passed, --region, so the default-region token was used). Fix: Specify ca-central-1 on both sides.

Command-line tasks
1. List the tags and push times of the 3 most recently pushed images in the repository myapp.
aws ecr describe-images --repository-name myapp \
  --query 'sort_by(imageDetails,&imagePushedAt)[-3:].[imageTags[0],imagePushedAt]' --output table
2. Confirm the repository really uses immutable tags and has scan-on-push enabled.
aws ecr describe-repositories --repository-names myapp \
  --query 'repositories[0].[imageTagMutability,imageScanningConfiguration.scanOnPush]' --output text
Scenario analysis
The team wants to change the ECR login to “store a username AWS + password credential in Jenkins, refreshed by a scheduled job once a day.” How do you assess this?

Not recommended. ① The token expires after 12 hours, so a “daily refresh” will inevitably fail during the gap; ② the token’s permissions equal the identity of the refresh job, which is often broader than a single pipeline needs; ③ the token is stored long-term as a credential on the controller, increasing the exposure surface. The correct approach: on each build, fetch it using the current identity get-login-password fresh, and use DOCKER_CONFIG to isolate it and log out at the end; when the agent has its own identity, switch to the ECR Credential Helper.

Verified instructional videos

▶
Amazon Elastic Container Registry (Amazon ECR) Explained | Amazon Web Services — Amazon Web Services
English · ECR official overview
▶
AWS re:Invent 2023 - Dive deep into Amazon ECR (CON405) — AWS Events
English · Deep dive into ECR push, replication, scanning
▶
How to Push a Docker Image from Jenkins to Amazon Elastic Container Registry (ECR) — iQuant
English · third-party Jenkins demo; if the video uses long-term access keys or mutable tags, replace them following this course’s approach

Official documentation

Video storyboard (about 60 seconds)

This courseware cannot generate video/MP3 directly; the storyboard and narration script below can be handed to a video tool.

Shot 1 · 0–20s
Visual: the agent hands temporary credentials to the ECR API window and gets back a pass marked “12 hours.”
Narration: Docker doesn’t understand IAM, so each build first uses the current identity to exchange for a twelve-hour ECR pass.
Shot 2 · 20–45s
Visual: three layers of blocks fly to the repository one by one; the first shows “already exists, skipped”; finally, the tag 1.1-abc1234 is attached and a lock is sealed on it.
Narration: layers that already exist are not uploaded again; tags are immutable, and the same tag always points to the same digest.
Shot 3 · 45–60s
Visual: the next pipeline stage receives only a string of sha256 addresses; the pass on the agent is torn up (docker logout).
Narration: deployment references the digest; the build clears the login state when it ends, so the next job cannot pick up your pass.
or reach a score of ≥ 70% on the quiz

Module 4 · Deploy to ECS on Fargate

21:00 – 29:00 · Register a new task definition revision → update the service → wait for stability → confirm that the new version is the one that is stable
8 minECS rolling deployment · deployment circuit breakerThe services-stable trap★★★★★
Learning objectives
  • Put the task definition template in the repository, and use jq to render the image digest,register-task-definition to obtain a new revision.
  • Use update-service to trigger a rolling deployment, and understand minimumHealthyPercent / maximumPercent and the deployment circuit breaker (automatic rollback).
  • Know aws ecs wait services-stable in also returns successfully after a rollback completes, and you must additionally verify that the task definition of the PRIMARY deployment matches rolloutState, otherwise Jenkins will mark the failed release green.
Prerequisite knowledge: The IMAGE_URI produced in Module 3; the ECS object model from Docker Course 4. Importance:★★★★★

What: which APIs make up one ECS deployment

StepAPI / CLIResult
1 Render(local) jq replace image, execution roletaskdef.rendered.json
2 Registerecs:RegisterTaskDefinitionnew revision myapp:7 (revision numbers only increase and are never changed; old revisions remain available for rollback)
3 Update serviceecs:UpdateService (requires permission on the execution role iam:PassRole)the new deployment becomes PRIMARY; the old deployment becomes ACTIVE
4 Waitaws ecs wait services-stable (polls every 15 seconds DescribeServices, up to 40 times)runningCount = desiredCount and only one deployment remains
5 VerifyDescribeServices of deployments[?status=='PRIMARY']taskDefinition is the ARN from step 2, and rolloutState = COMPLETED

Why: why services-stable is not enough

Enabling the deployment circuit breaker (deploymentCircuitBreaker={enable=true,rollback=true}): when new tasks repeatedly fail to start, ECS marks the deployment as FAILED and automatically rolls back to the last successful revision. After the rollback completes, the service becomes “stable” again —services-stable returns normally with exit code 0. If the pipeline only looks at this wait command, you get “deployment failed but the build is green.” So step 5 is mandatory.

How: rolling parameters

  • minimumHealthyPercent=100, maximumPercent=200: start new tasks first, stop old tasks only after the new ones are healthy; no capacity reduction (this course’s setting).
  • minimumHealthyPercent=50: allows stopping half of the old tasks first; saves resources but reduces capacity.
  • The circuit breaker’s failure threshold is computed from desiredCount (the documentation gives a lower and upper bound); even with a small desiredCount it needs at least several failures before deciding, so rolling back a small service takes several minutes.
  • Without an ALB, “healthy” only means the container stays running (plus an optional container healthCheck); with an ALB, target group health checks must also pass — this is the threshold production should have.

When: which deployment method to choose

MethodSuitable forJenkins side
Rolling update + circuit breaker (this course)The vast majority of stateless servicesThe 5 steps above
ECS native blue/green deploymentNeeds test traffic, lifecycle hooks, fast switch-backSet the service’s deployment strategy to blue/green; Jenkins is still only update-service
Express ModeMinimal configuration is the prioritySee Module 1
Comparison GitHub Actions uses amazon-ecs-render-task-definition + amazon-ecs-deploy-task-definition (wait-for-service-stability) to complete the same 5 steps; see GitHub Course 4 Module 4; for the Azure Pipelines approach, see Azure DevOps Course 4. Jenkins uses pure CLI, so the logic is completely transparent.
Common misconceptions① “update-service --force-new-deployment will deploy the new image” — it only uses the same task definition to relaunch tasks; the new image is pulled only if the task definition uses a mutable tag, which is the root cause of non-reproducible deployments. ② “The deployment role needs AdministratorAccess to update a service” — only a few ECS actions plus permission on the execution role are needed iam:PassRole. ③ “Rolling back proves the circuit breaker is broken” — the circuit breaker is designed exactly for this; what you need to investigate is why the new tasks cannot start (stoppedReason).

Deployment sequence

Jenkins agentECS control planeFargateECR / CloudWatch RegisterTaskDefinition → myapp:7 UpdateService(taskDefinition=myapp:7) Start new task (ENI, public IP) Execution role pulls image @sha256 · writes logs RUNNING (healthy) Stop old task (myapp:6) DescribeServices × N (wait services-stable) Verify PRIMARY = myapp:7 and COMPLETED
Figure 4-1: the final “verify” step is something Jenkins must do itself; ECS will not judge “deployment success” for you

Circuit breaker state machine

IN_PROGRESS COMPLETED FAILED Roll back deploymentprevious successful revision service “stable”waiter returns 0! New task healthyfailed task count ≥ threshold
Figure 4-2: FAILED → rollback → “stable”: the pipeline must recognize this path

Animation: rolling deployment and circuit-breaker rollback

desiredCount = 2, minimumHealthyPercent = 100, maximumPercent = 200. Choose “good image” or “bad image,” then play, and observe task states and Jenkins’ final verdict.

RUNNINGPENDING / PROVISIONINGNew revisionSTOPPED
Select a scenario first (default: good image).

Command overview

CommandPurposeNotes
aws ecs register-task-definition --cli-input-json file://…Register new revisionreturns taskDefinitionArn
aws ecs create-service … --deployment-configuration …Create the service for the first time (administrator, one-time)Enable circuit breaker + rollback
aws ecs update-service --task-definition ARNDeployEach pipeline run
aws ecs wait services-stableWaitUp to about 10 minutes; exit code 255 on timeout
aws ecs describe-services --query 'services[0].deployments'View deployment and rolloutStateVerify PRIMARY
aws ecs describe-tasks --query 'tasks[].stoppedReason'See why tasks stoppedFirst place to look when troubleshooting

Task definition template in the repository deploy/ecs-taskdef.json

{
  "family": "myapp",
  "networkMode": "awsvpc",
  "requiresCompatibilities": ["FARGATE"],
  "cpu": "256",
  "memory": "512",
  "runtimePlatform": { "cpuArchitecture": "X86_64", "operatingSystemFamily": "LINUX" },
  "executionRoleArn": "__EXEC_ROLE_ARN__",
  "containerDefinitions": [{
    "name": "myapp",
    "image": "__IMAGE_URI__",
    "essential": true,
    "portMappings": [{ "containerPort": 5000, "protocol": "tcp" }],
    "logConfiguration": { "logDriver": "awslogs", "options": {
      "awslogs-group": "/ecs/myapp", "awslogs-region": "ca-central-1", "awslogs-stream-prefix": "myapp" } }
  }]
}

The Deploy stage of the Jenkinsfile (placed after Push in Module 3)

stage('Deploy to ECS') {
  when { branch 'main' }
  steps {
    withCredentials([[$class: 'AmazonWebServicesCredentialsBinding', credentialsId: 'aws-lab-bootstrap',
                      roleArn: env.DEPLOY_ROLE_ARN, roleSessionName: "jenkins-myapp-${env.BUILD_NUMBER}"]]) {
      sh '''
        set -eu
        jq --arg img "$IMAGE_URI" --arg exec "arn:aws:iam::$ACCOUNT_ID:role/myappTaskExecutionRole" \
           '.containerDefinitions[0].image=$img | .executionRoleArn=$exec' deploy/ecs-taskdef.json > taskdef.rendered.json
        TD_ARN=$(aws ecs register-task-definition --cli-input-json file://taskdef.rendered.json \
                 --query taskDefinition.taskDefinitionArn --output text)
        echo "registered $TD_ARN"
        aws ecs update-service --cluster myapp-lab --service myapp --task-definition "$TD_ARN" \
          --query 'service.deployments[0].[id,status]' --output text
        aws ecs wait services-stable --cluster myapp-lab --services myapp
        OUT=$(aws ecs describe-services --cluster myapp-lab --services myapp \
              --query "services[0].deployments[?status=='PRIMARY'] | [0].[taskDefinition,rolloutState]" --output text)
        PRIMARY_TD=$(echo "$OUT" | cut -f1); STATE=$(echo "$OUT" | cut -f2)
        echo "PRIMARY=$PRIMARY_TD rolloutState=$STATE"
        if [ "$PRIMARY_TD" != "$TD_ARN" ] || [ "$STATE" != "COMPLETED" ]; then
          echo "Deployment not effective (may have been rolled back by the circuit breaker)"; exit 1
        fi
      '''
    }
  }
}
registered arn:aws:ecs:ca-central-1:111122223333:task-definition/myapp:7
ecs-svc/1234567890123456789   PRIMARY
PRIMARY=arn:aws:ecs:ca-central-1:111122223333:task-definition/myapp:7 rolloutState=COMPLETED

Parameter explanation:when { branch 'main' } deploy only on the main branch of the multibranch pipeline; --output text the two columns of cut -f1/-f2 are separated by tabs, and are extracted separately. Common errors: In Groovy’s ''' string, $ is not interpolated by Groovy (it is handed to the shell); if you change it to """ you must write the shell variables as \$VAR. Production use: Wrap this logic as a shared library step ecsDeploy(cluster, service, imageUri) (the shared library from Course 2).

Lab 4: create the service and have the pipeline complete one deployment (about 8 minutes)

Cost One 0.25 vCPU / 0.5 GB Fargate task in ca-central-1 costs about US$0.013 per hour (estimated from the vCPU and GB-hour prices; the calculator is authoritative), plus a public IPv4 address at about US$0.005 per hour; CloudWatch log volume is very small. Delete the service when you finish the capstone lab or Module 8.
Commit the template: commit the template above deploy/ecs-taskdef.json to lab/myapp.
Administrator creates the service (one-time, on this machine): use the first image pushed in Module 3
source ~/jenkinslab/aws-part4.env
DIGEST=$(aws ecr describe-images --repository-name myapp --query 'sort_by(imageDetails,&imagePushedAt)[-1].imageDigest' --output text)
jq --arg img "$REGISTRY/myapp@$DIGEST" --arg exec "arn:aws:iam::$ACCOUNT_ID:role/$EXEC_ROLE" \
   '.containerDefinitions[0].image=$img | .executionRoleArn=$exec' ~/src/myapp/deploy/ecs-taskdef.json > td.json
aws ecs register-task-definition --cli-input-json file://td.json --query taskDefinition.revision
aws ecs create-service --cluster $CLUSTER --service-name $SERVICE --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=jenkins-part4 --query 'service.serviceName'
aws ecs wait services-stable --cluster $CLUSTER --services $SERVICE && echo stable
Add the Deploy stage and push: add the Deploy stage from the “Commands” page after the Push stage in the Jenkinsfile, change myapp’s welcome text (for example, the version number 1.1), and commit to main.
Smoke test (this machine): get the task’s public IP and access port 5000
TASK=$(aws ecs list-tasks --cluster $CLUSTER --service-name $SERVICE --query 'taskArns[0]' --output text)
ENI=$(aws ecs describe-tasks --cluster $CLUSTER --tasks $TASK \
  --query "tasks[0].attachments[0].details[?name=='networkInterfaceId'].value" --output text)
IP=$(aws ec2 describe-network-interfaces --network-interface-ids $ENI --query 'NetworkInterfaces[0].Association.PublicIp' --output text)
curl -s http://$IP:5000/healthz
ok
(Optional, about 5–10 minutes) experience the circuit-breaker rollback: on a temporary branch, add "command": ["sh","-c","exit 1"], and temporarily remove when { branch 'main' } run once. Observe the ECS events and Jenkins results:
PRIMARY=arn:aws:ecs:ca-central-1:111122223333:task-definition/myapp:7 rolloutState=COMPLETED
Deployment not effective (may have been rolled back by the circuit breaker)
ERROR: script returned exit code 1

Here PRIMARY is already the old revision after rollback myapp:7, while this registration produced myapp:8. Delete the temporary branch after the lab.

Case 1: green build, red production

Problem: The pipeline only has update-service + wait services-stable. The new version failed to start because of a missing environment variable, the circuit breaker rolled it back, Jenkins showed success, and the team believed the new feature was live. Fix: Add the PRIMARY verification (as written in this module), and on failure print the most recent 5 events of describe-services to the console. Limit: Rollbacks take several minutes, so the total pipeline duration increases; set timeout(time: 15, unit: 'MINUTES').

Case 2: task definition edited by hand in the console

Problem: On-call staff changed an environment variable in the console (creating a new revision), and the next Jenkins deployment overwrote it back with the repository template. Fix: The task definition comes only from the repository (Git is the single source of truth); the console is read-only; urgent changes go through a PR + pipeline. Limit: Secrets should not be written into the template; use the secrets field to reference Secrets Manager / SSM parameters (the execution role needs read permission).

Case 3: deployment role PassRole too broad

Problem: The deployment role’s iam:PassRole was written as Resource: "*", and a developer swapped in a high-privilege role as the task role in the task definition, using the ECS task to obtain administrator permissions. Fix: Restrict PassRole precisely to the allowed execution role / task role ARNs, and add iam:PassedToService = ecs-tasks.amazonaws.com conditions (as written in this course).

Common errors and fixes

An error occurred (AccessDeniedException) when calling the RegisterTaskDefinition operation: User: …assumed-role/jenkins-myapp-deployer/… is not authorized to perform: iam:PassRole on resource: arn:aws:iam::111122223333:role/myappTaskExecutionRole

Cause: The task definition references the execution role, so registration requires the deployment role to have iam:PassRole. Fix: Add the PassOnlyExecRoleToEcs statement from the Module 2 permission policy, paying attention to the ARN and conditions.

CannotPullContainerError: pull image manifest has been retried … failed to resolve ref …: not found

Cause: The image digest/tag does not exist (deleted by a lifecycle policy, wrong region), or the task’s subnet cannot reach ECR (a private subnet without NAT / VPC endpoint, or assignPublicIp=DISABLED).

aws ecs describe-tasks --cluster myapp-lab --tasks $TASK --query 'tasks[0].[lastStatus,stoppedReason,containers[0].reason]'
aws ecr describe-images --repository-name myapp --image-ids imageDigest=sha256:...
Essential container in task exited (log shows exec /usr/local/bin/gunicorn: exec format error)

Cause: The image architecture does not match runtimePlatform.cpuArchitecture , for example an arm64 image was built on an ARM machine but runs on X86_64. Fix: Use docker build --platform linux/amd64 on the agent, or change the task definition to ARM64 (Fargate supports Graviton).

Waiter ServicesStable failed: Max attempts exceeded

Cause: The service did not stabilize within about 10 minutes: tasks keep failing but have not yet reached the circuit-breaker threshold, or capacity is insufficient. Diagnosis:

aws ecs describe-services --cluster myapp-lab --services myapp --query 'services[0].events[:5].[createdAt,message]' --output text
InvalidParameterException: Task definition does not support launch_type FARGATE.

Cause: The template is missing "requiresCompatibilities": ["FARGATE"], or the cpu/memory combination is not one supported by Fargate. Fix: Use valid combinations such as 256/512.

Command-line tasks
1. Manually roll the service back to the previous task definition revision (assume the current one is myapp:8).
aws ecs update-service --cluster myapp-lab --service myapp --task-definition myapp:7
aws ecs wait services-stable --cluster myapp-lab --services myapp
2. Print the 5 most recent events of the service.
aws ecs describe-services --cluster myapp-lab --services myapp \
  --query 'services[0].events[:5].[createdAt,message]' --output text
Scenario analysis
A colleague says: “As long as update-service doesn’t error in our Jenkins deployment stage, it counts as success; ECS will handle the rest.” Point out the problem and suggest improvements.

update-service It only submits the desired state; when it returns, the new tasks may not even have started. At minimum you need: ① wait services-stable to wait for convergence; ② verify that the PRIMARY deployment’s task definition is the ARN registered this time, and rolloutState=COMPLETED (to prevent misjudging success after a circuit-breaker rollback); ③ on failure, print events and stoppedReason; ④ if there is an ALB, run an external smoke test as well.

Verified instructional videos

▶
Circuit Breakers for Amazon ECS — Containers from the Couch
English · Principles and demonstration of the deployment circuit breaker
▶
How to Setup AWS ECS Fargate with a Load Balancer | Step by Step — Be A Better Dev
English · Building a production setup (ALB + private subnets)
▶
The Complete Guide to ECS Blue/Green Deployments on AWS — AWS Developers
English · ECS native blue/green deployment

Official documentation

Video storyboard (about 75 seconds)

This courseware cannot generate video/MP3 directly; the storyboard and narration script below can be handed to a video tool.

Shot 1 · 0–20s
Visual: Jenkins hands ECS a new blueprint “myapp version 7”; ECS pins it on the wall, next to version 6.
Narration: each deployment first registers a new task definition revision; old revisions are always kept, and rollback means pointing back to an old revision.
Shot 2 · 20–45s
Visual: two new tasks light up green; two old tasks go dark.
Narration: minimum healthy percent 100, maximum percent 200: start the new ones first, then stop the old ones, so capacity never drops.
Shot 3 · 45–75s
Visual: the bad-image task falls over three times in a row, the circuit breaker trips, and the service goes back to version 7 and shows “stable”; a Jenkins inspector with a magnifying glass finds PRIMARY is not version 8 and lights a red light.
Narration: the service also shows “stable” after the circuit-breaker rollback, so Jenkins must verify that what is running is this deployment’s version.
or reach a score of ≥ 70% on the quiz

Module 5 · Deploy to EKS and Lambda

29:00 – 37:00 · EKS: IAM proves “who you are,” access entries decide “what you can do”; Lambda: publish versions, move aliases
8 minEKS access entries · Lambda versions/aliasesEKS is an optional lab (has cluster costs)★★★★
Learning objectives
  • Explain kubectl The authentication chain for accessing EKS: aws eks get-token (presigned STS GetCallerIdentity) → API server verification → access entry mapping → authorization.
  • Create namespace-scoped access entry for the deployment role, and in Jenkins execute with a separate kubeconfig kubectl set image + rollout status.
  • Distinguish “Jenkins deploys from outside the cluster” (needs an access entry) from “the Jenkins agent is inside the same EKS” (can use a service account + RBAC directly).
  • Make myapp a Lambda container image (AWS Lambda Web Adapter), and use update-function-code --publish + update-alias for release and canary.
Prerequisite knowledge: K8s Course 7 (EKS), Modules 2–3. Importance:★★★★

What: the two layers of permissions in EKS

LayerWho manages itWhat the Jenkins deployment role needs
AWS API (eks:DescribeCluster)IAM permission policyAllow aws eks update-kubeconfig to get the endpoint and CA
Kubernetes API (kubectl apply / set image)EKS access entry (recommended) or the older aws-auth ConfigMap, plus K8s RBAC / access policyAccess entry: principal = deployment role ARN, access policy AmazonEKSEditPolicy, scope = namespace myapp

The EKS official documentation says access entries are “the best way to grant users access to the Kubernetes API”; access policies are permission templates maintained by AWS, and you can also map the principal to Kubernetes groups and write RBAC yourself.

Why: how the token is generated

aws eks get-token Use the current credentials to call STS GetCallerIdentity to generate a presigned URL, encoded as k8s-aws-v1.… form of a Bearer token (valid for a very short time). The API server takes it and calls STS, obtaining the caller ARN (for an AssumeRole session it is restored to the role ARN), then checks the access entry. So kubectl itself never touches access keys; it only needs to be able to “sign.”

How: two Jenkins topologies

Jenkins outside the cluster (local / EC2 / another cluster)Jenkins agent is inside the target EKS
AuthenticationIAM deployment role → aws eks get-tokenagent Pod’s service account token (in-cluster config)
AuthorizationAccess entry + access policy (namespace scope)K8s Role + RoleBinding (myapp namespace)
AWS permissions (push to ECR)same deployment rolePod Identity / IRSA (Module 6)
NoteEvery cluster needs its own access entryThe Kubernetes plugin documentation warns: agent Pods should not use a service account that has permissions on their own namespace— deployment permissions should be granted only to the target namespace

What: Lambda’s release model

  • A container image must implement Lambda Runtime API (official base images or a runtime interface client), and must be Linux only,single architecture, uncompressed up to 10 GB, and the ECR repository must be in the same region as the function.
  • myapp is an ordinary Flask/gunicorn service, not a Lambda handler. The minimal-change option: the AWS open-source project Lambda Web Adapter— add one line to the image COPY --from=public.ecr.aws/awsguru/aws-lambda-adapter:1.1.0 /lambda-adapter /opt/extensions/lambda-adapter and use AWS_LWA_PORT=5000,AWS_LWA_READINESS_CHECK_PATH=/healthz to tell it the application port and readiness path (default port 8080).
  • Release: update-function-code --publish Generate an immutable version number; an alias live points to a version and can be used routing-config to send part of the traffic to the new version (canary); rollback means pointing the alias back to the old version.
  • Lambda periodically pulls images from ECR; when the image is deleted or its permissions are revoked, the function enters the Failed state (related to the lifecycle policies in Module 3).

When

  • EKS: the company already has an EKS platform; Jenkins gets only edit permission on the target namespace.
  • Lambda: APIs and event handling with low-frequency or bursty traffic; not suitable for stateful long connections or tasks longer than 15 minutes.
Common misconceptions① “Granting the deployment role eks:* permission means you can run kubectl” — IAM permissions are not Kubernetes permissions; without an access entry you will get Unauthorized / Forbidden. ② “The access entry should use the assumed-role session ARN” — it should use the role ARN. ③ “Lambda can run any container directly” — it must implement the Runtime API; the Web Adapter is one way to do that. ④ “Images built by buildx by default work with Lambda” — the default attached provenance attestation turns the image into a multi-manifest index, and Lambda does not support multi-architecture images; add --provenance=false and specify --platform.

kubectl → EKS authentication and authorization chain

Jenkins agentkubectl set imageexec: aws eks get-token Bearer EKS API serverk8s-aws-v1.<presigned>authentication webhook STSGetCallerIdentity → role ARN access entryrole/jenkins-myapp-deployerEditPolicy · ns=myapp authorization → admission → etcdDeployment myapp updaterollout status
Figure 5-1: kubectl stores no keys; it only uses the current AWS identity to sign an STS request

Lambda versions and aliases

$LATESTupdate-function-code --publish Version 3 (old) Version 4 (new) Alias live3: 90% · 4: 10% Function URL (AWS_IAM)bound to alias live Jenkins: update-function-code --publish → wait published-version-active → update-alias (10% first, then 100% after verification) Rollback: update-alias --function-version 3 --routing-config AdditionalVersionWeights={}
Figure 5-2: versions are immutable and aliases can move — this is Lambda’s release and rollback model

Animation: two deployment chains

EKS: one kubectl set image goes through authentication, authorization and rolling update; Lambda: one version release plus an alias canary.

agent
Select a scenario first (default: EKS).

EKS: access entry and deployment

CommandPurpose
aws eks create-access-entry --cluster-name … --principal-arn …Create an access entry for the deployment role (type defaults to STANDARD)
aws eks associate-access-policy … --access-scope type=namespace,namespaces=myappBind an access policy and restrict it to a namespace
aws eks update-kubeconfig --name … --kubeconfig $WORKSPACE_TMP/kubeconfigGenerate a separate kubeconfig for this build
kubectl set image / kubectl rollout status --timeoutUpdate the image and wait
kubectl auth can-i update deployments -n myappVerify permissions
# Run once as administrator (the cluster jenkins-lab-eks already exists; see K8s Course 7)
CLUSTER_EKS=jenkins-lab-eks
ROLE_ARN=arn:aws:iam::$ACCOUNT_ID:role/jenkins-myapp-deployer
aws eks create-access-entry --cluster-name $CLUSTER_EKS --principal-arn $ROLE_ARN
aws eks associate-access-policy --cluster-name $CLUSTER_EKS --principal-arn $ROLE_ARN \
  --policy-arn arn:aws:eks::aws:cluster-access-policy/AmazonEKSEditPolicy \
  --access-scope type=namespace,namespaces=myapp
# the deployment role also needs IAM permission eks:DescribeCluster (resource is the cluster ARN)
stage('Deploy to EKS') {
  environment { KUBECONFIG = "${env.WORKSPACE_TMP}/kubeconfig" }
  steps {
    withCredentials([[$class: 'AmazonWebServicesCredentialsBinding', credentialsId: 'aws-lab-bootstrap',
                      roleArn: env.DEPLOY_ROLE_ARN, roleSessionName: "jenkins-myapp-${env.BUILD_NUMBER}"]]) {
      sh '''
        set -eu
        aws eks update-kubeconfig --name jenkins-lab-eks --region "$AWS_REGION" --kubeconfig "$KUBECONFIG"
        kubectl -n myapp set image deployment/myapp myapp="$IMAGE_URI"
        kubectl -n myapp rollout status deployment/myapp --timeout=180s
      '''
    }
  }
}

The exec plugin in the kubeconfig runs on every kubectl call, aws eks get-token, so kubectl must run inside the withCredentials block . rollout status A timeout returns non-zero and the pipeline fails; when a rollback is needed, kubectl rollout undo.

Lambda: container image and aliases

# Dockerfile.lambda — add the Lambda Web Adapter on top of the tested myapp image
ARG BASE
FROM ${BASE}
COPY --from=public.ecr.aws/awsguru/aws-lambda-adapter:1.1.0 /lambda-adapter /opt/extensions/lambda-adapter
ENV AWS_LWA_PORT=5000 \
    AWS_LWA_READINESS_CHECK_PATH=/healthz
# one-time for admin: execution role + function + alias + function URL
cat > lambda-trust.json <<'EOF'
{ "Version": "2012-10-17", "Statement": [{ "Effect": "Allow",
  "Principal": { "Service": "lambda.amazonaws.com" }, "Action": "sts:AssumeRole" }] }
EOF
aws iam create-role --role-name myapp-lambda-exec --assume-role-policy-document file://lambda-trust.json
aws iam attach-role-policy --role-name myapp-lambda-exec \
  --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
aws lambda create-function --function-name myapp-fn --package-type Image \
  --code ImageUri=$REGISTRY/myapp:1.1-abc1234-lambda \
  --role arn:aws:iam::$ACCOUNT_ID:role/myapp-lambda-exec --architectures x86_64 \
  --memory-size 512 --timeout 30
aws lambda wait function-active-v2 --function-name myapp-fn
V1=$(aws lambda publish-version --function-name myapp-fn --query Version --output text)
aws lambda create-alias --function-name myapp-fn --name live --function-version $V1
aws lambda create-function-url-config --function-name myapp-fn --qualifier live --auth-type AWS_IAM
stage('Deploy to Lambda') {
  steps {
    withCredentials([[$class: 'AmazonWebServicesCredentialsBinding', credentialsId: 'aws-lab-bootstrap',
                      roleArn: env.DEPLOY_ROLE_ARN, roleSessionName: "jenkins-myapp-${env.BUILD_NUMBER}"]]) {
      sh '''
        set -eu
        LTAG=$IMAGE_TAG-lambda
        docker build --platform linux/amd64 --provenance=false -f Dockerfile.lambda \
          --build-arg BASE="$IMAGE_URI" -t $REGISTRY/myapp:$LTAG .
        docker push $REGISTRY/myapp:$LTAG
        OLD=$(aws lambda get-alias --function-name myapp-fn --name live --query FunctionVersion --output text)
        NEW=$(aws lambda update-function-code --function-name myapp-fn --image-uri $REGISTRY/myapp:$LTAG \
              --publish --query Version --output text)
        aws lambda wait published-version-active --function-name myapp-fn --qualifier "$NEW"
        aws lambda update-alias --function-name myapp-fn --name live --function-version "$OLD" \
          --routing-config "AdditionalVersionWeights={\\"$NEW\\"=0.1}"
        echo "live: $OLD 90% / $NEW 10%"
      '''
    }
  }
}

Note on Groovy ''' string: backslashes are treated by Groovy as escape characters, so the shell’s required \" must be written in the Jenkinsfile as \\". After verification, shift full traffic: aws lambda update-alias --function-name myapp-fn --name live --function-version "$NEW" --routing-config 'AdditionalVersionWeights={}'. The deployment role must additionally be granted lambda:GetAlias,lambda:UpdateFunctionCode,lambda:PublishVersion,lambda:UpdateAlias,lambda:GetFunction (resource is the function ARN), as well as ecr:GetDownloadUrlForLayer.

# call the AWS_IAM function URL with the local administrator’s temporary credentials (curl 7.75+ supports --aws-sigv4)
eval "$(aws configure export-credentials --format env)"
URL=$(aws lambda get-function-url-config --function-name myapp-fn --qualifier live --query FunctionUrl --output text)
curl -s --aws-sigv4 "aws:amz:ca-central-1:lambda" --user "$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY" \
  -H "x-amz-security-token: $AWS_SESSION_TOKEN" "${URL}healthz"

Lab 5 (optional): Lambda canary (about 8 minutes)

Cost / scope Lambda and function URLs are essentially free within the free tier. The EKS part is read-only: a cluster costs from US$0.10 per hour plus nodes; if you already built a cluster in K8s Course 7, you may add the access entry following the “Commands” page and proceed, then delete the access entry immediately.
Prepare the Lambda image (this machine, one-time)
source ~/jenkinslab/aws-part4.env
cd ~/src/myapp
cat > Dockerfile.lambda <<'EOF'
ARG BASE
FROM ${BASE}
COPY --from=public.ecr.aws/awsguru/aws-lambda-adapter:1.1.0 /lambda-adapter /opt/extensions/lambda-adapter
ENV AWS_LWA_PORT=5000 AWS_LWA_READINESS_CHECK_PATH=/healthz
EOF
DIGEST=$(aws ecr describe-images --repository-name myapp --query 'sort_by(imageDetails,&imagePushedAt)[-1].imageDigest' --output text)
aws ecr get-login-password | docker login --username AWS --password-stdin $REGISTRY
docker build --platform linux/amd64 --provenance=false -f Dockerfile.lambda \
  --build-arg BASE=$REGISTRY/myapp@$DIGEST -t $REGISTRY/myapp:1.1-abc1234-lambda .
docker push $REGISTRY/myapp:1.1-abc1234-lambda
git add Dockerfile.lambda && git commit -m "lambda adapter image" && git push
Create the function, alias and function URL: run the one-time admin script from the “Commands” page (replacing the tag with the one you just pushed).
Add Lambda permissions to the deployment role
cat > lambda-deploy.json <<EOF
{ "Version": "2012-10-17", "Statement": [
  { "Effect": "Allow", "Action": ["lambda:GetAlias","lambda:UpdateFunctionCode","lambda:PublishVersion",
      "lambda:UpdateAlias","lambda:GetFunction","lambda:GetFunctionConfiguration"],
    "Resource": ["arn:aws:lambda:$AWS_REGION:$ACCOUNT_ID:function:myapp-fn","arn:aws:lambda:$AWS_REGION:$ACCOUNT_ID:function:myapp-fn:*"] },
  { "Effect": "Allow", "Action": "ecr:GetDownloadUrlForLayer",
    "Resource": "arn:aws:ecr:$AWS_REGION:$ACCOUNT_ID:repository/myapp" } ] }
EOF
aws iam put-role-policy --role-name $DEPLOY_ROLE --policy-name deploy-myapp-lambda --policy-document file://lambda-deploy.json
Add the Deploy to Lambda stage and run it, the console should show live: 1 90% / 2 10%.
Verify
aws lambda get-alias --function-name myapp-fn --name live --query '[FunctionVersion,RoutingConfig]'
[
    "1",
    { "AdditionalVersionWeights": { "2": 0.1 } }
]

Then use the last curl --aws-sigv4 command from the “Commands” page to access /healthz, which should return ok. The first call has a cold start (a few seconds).

Case 1: access entry scope too broad

Problem: To “get it running first,” the platform team bound the Jenkins deployment role to AmazonEKSClusterAdminPolicy (cluster scope). A tampered Jenkinsfile deleted a component from kube-system a shared namespace. Fix: Changed to AmazonEKSEditPolicy + type=namespace,namespaces=myapp; one deployment role per application, and one namespace per application. Limit: EditPolicy can still read Secrets within the namespace; sensitive applications should be mapped to custom K8s groups with narrower RBAC.

Case 2: concurrent builds overwrite each other’s kubeconfig

Problem: Two jobs ran simultaneously on the same static agent aws eks update-kubeconfig, both writing ~/.kube/config, and one job deployed to another cluster. Fix:KUBECONFIG=$WORKSPACE_TMP/kubeconfig, so each build is isolated; or use one-off Pod agents.

Case 3: Lambda image “unsupported manifest”

Problem: After upgrading Docker, Lambda updates failed with an error that the image manifest media type is not supported. Root cause: The new BuildKit version attaches provenance attestations by default, pushing an image index; Lambda does not support multi-architecture images. Fix: Uniformly add --provenance=false --platform linux/amd64 to Lambda image builds; ECS images keep their attestations, which is unaffected.

Common errors and fixes

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

Cause: The current IAM identity has no access entry in the cluster (or the session ARN was written as the entry), or kubectl ran outside the withCredentials block, so get-token used a different identity.

aws sts get-caller-identity
aws eks list-access-entries --cluster-name jenkins-lab-eks
aws eks list-associated-access-policies --cluster-name jenkins-lab-eks --principal-arn arn:aws:iam::111122223333:role/jenkins-myapp-deployer
Error from server (Forbidden): deployments.apps "myapp" is forbidden: User "arn:aws:sts::111122223333:assumed-role/jenkins-myapp-deployer/jenkins-myapp-12" cannot patch resource "deployments" in API group "apps" in the namespace "myapp"

Cause: Authentication succeeded but authorization is insufficient: the access policy scope does not include myapp, or it is bound to AmazonEKSViewPolicy. Fix: Re-associate the access policy associate-access-policy; verify with kubectl auth can-i patch deployments -n myapp to confirm.

An error occurred (AccessDeniedException) when calling the DescribeCluster operation

Cause: The deployment role lacks eks:DescribeCluster,update-kubeconfig fails. Fix: Grant eks:DescribeCluster to this cluster ARN.

InvalidParameterValueException: The image manifest, config or layer media type for the source image … is not supported.

Cause: A multi-manifest index was pushed (attestations or a multi-platform build). Fix:docker build --platform linux/amd64 --provenance=false Rebuild and push; use docker buildx imagetools inspect to confirm a single manifest.

ResourceConflictException: The operation cannot be performed at this time. An update is in progress for resource: …myapp-fn

Cause: The previous update-function-code has not finished when the next update is invoked. Fix: Between the two calls, wait for the previous update to finish aws lambda wait function-updated-v2 --function-name myapp-fn; add disableConcurrentBuilds() to the pipeline.

Command-line tasks
1. As the deployment role, check whether it can update Deployments in the myapp namespace.
kubectl auth can-i update deployments -n myapp
kubectl auth can-i update deployments -n kube-system     # should be no
2. Immediately roll the Lambda alias live back to version 1 and clear the canary weights.
aws lambda update-alias --function-name myapp-fn --name live --function-version 1 \
  --routing-config 'AdditionalVersionWeights={}'
Scenario analysis
The Jenkins controller and agent both run in EKS cluster A, and need to deploy to the myapp namespace of EKS cluster B in the same account. What is the minimum configuration needed?

① agent Pod uses service account jenkins-deploy, associates the IAM deployment role via Pod Identity (configured in cluster A); ② the deployment role has eks:DescribeCluster (cluster B); ③ in cluster B, create an access entry for this role ARN, binding AmazonEKSEditPolicy, scope namespace=myapp; ④ the Pod template image includes the aws CLI and kubectl, and the pipeline uses a separate KUBECONFIG. There are no long-term keys throughout. If you also need to push to ECR, add ECR push permissions to the same role, or split into separate build and deploy service accounts.

Verified instructional videos

▶
AWS EKS - Create Kubernetes cluster on Amazon EKS | the easy way — TechWorld with Nana
English · EKS cluster basics (an older video from before access entries; for authentication, this course and the official documentation take precedence)
▶
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 of running Lambda with container images

Official documentation

Video storyboard (about 75 seconds)

This courseware cannot generate video/MP3 directly; the storyboard and narration script below can be handed to a video tool.

Shot 1 · 0–25s
Visual: kubectl carries a signed STS postcard to the EKS gate, and the doorman calls STS to confirm “this is the jenkins-myapp-deployer role.”
Narration: kubectl signs an STS request with the current AWS identity as its token, and EKS goes to STS to verify who you are.
Shot 2 · 25–45s
Visual: the doorman checks the access-entry register: this role may only enter the myapp room, and only with edit permission.
Narration: what you can do is decided by the access entry, scoped to a namespace.
Shot 3 · 45–75s
Visual: Lambda versions are a row of numbered boxes; the alias live is a pointer that first sends 10% toward the new box, then turns everything over.
Narration: a Lambda release means generating immutable versions and then moving the alias; rollback only requires pointing the alias back.
or reach a score of ≥ 70% on the quiz

Module 6 · Jenkins agents on AWS: EC2 Fleet and EKS

37:00 – 45:00 · Moving the agent to AWS changes identity from “keys inside Jenkins” to “roles the machine / Pod carries itself”
8 minEC2 Fleet 4.5.2 · Kubernetes 4560EC2 / EKS labs are optional (they cost money)★★★★
Learning objectives
  • Explain how the EC2 Fleet plugin works: the plugin runs in the controller and, based on the queue,modifies the target capacity of the auto scaling group (ASG) / EC2 Fleet, connects to instances as agents over SSH once they start, and scales in when idle.
  • Distinguish two identities: The identity the plugin uses to manage the ASG (controller side: instance role or AWS credentials) and the identity the build uses on the agent instance (instance profile).
  • Set IMDSv2 in the launch template (HttpTokens=required, hop limit 2), and on the agent use credential_source = Ec2InstanceMetadata for role chaining.
  • On EKS, use the Kubernetes plugin’s Pod template + serviceAccountName + Pod Identity to obtain an AWS identity.
Prerequisite knowledge: Labels and executors from Course 1; methods C / D from Module 2. Course 5 will systematically configure the Kubernetes plugin with JCasC and Helm. Importance:★★★★

What: three plugins for running agents on AWS

PluginMechanismSuited toNotes (verified 2026-11)
EC2 Fleet (ec2-fleet)You pre-create the ASG (recommended) / EC2 Fleet / Spot Fleet; the plugin only adjusts target capacity and protects/terminates instancesNeeds mixed instance types, Spot, warm pools, or the team already manages AMIs with ASGsVersion 4.5.2.571; the documentation says Spot Fleet is a legacy API and recommends ASG; only the SSH connection method is described
Amazon EC2 (ec2)The plugin calls RunInstances directly, mapping AMI templates by labelSimple scenarios, when you do not want to maintain ASGsVersion 2068; the configuration includes “obtain credentials using instance profile”
Kubernetes (kubernetes)One Pod per build, deleted when finishedAlready have an EKS platformVersion 4560; can connect to the controller over WebSocket

Why: what one-off agents solve

  • Identities stay out of Jenkins: the agent instance / Pod carries its own role (C / D in Module 2), so there are no long-term keys that could be stolen.
  • No residue: ECR login state, kubeconfig and the workspace are destroyed along with the instance / Pod (setting EC2 Fleet’s “maximum uses per node = 1” makes it one-off).
  • Pay on demand: minimum capacity 0; scale in after an idle timeout.

How: the two identities of the EC2 Fleet plugin

IdentityWho uses itPermissions (listed in the plugin documentation)Source
Fleet management identitythe plugin in the controllerEC2: DescribeInstances,TerminateInstances,CreateTags,DescribeFleets,ModifyFleet,DescribeInstanceTypes , etc.; Auto Scaling: DescribeAutoScalingGroups,UpdateAutoScalingGroup,SetInstanceProtection,TerminateInstanceInAutoScalingGroup,DescribeWarmPool; IAM: ListInstanceProfiles,ListRoles,PassRole (restricted to ec2.amazonaws.com)“Leave AWS Credentials empty to use the EC2 instance role” (when the controller runs on EC2), or select an AWS credential
Build identityon the agent sh 'aws …'only needs sts:AssumeRole to the deployment role (or directly grant the permissions the build needs)instance profile in the launch template jenkins-agent-ec2

How: IMDSv2 and containers

The AWS CLI on the agent fetches credentials via IMDSv2: first PUT /latest/api/token obtain a session token, then GET /latest/meta-data/iam/security-credentials/<role>. If the build steps run inside a Docker container on the agent (agent { docker { … } }), the request must traverse one more network hop; when HttpPutResponseHopLimit is 1, the container cannot get the token, which shows up as Unable to locate credentials. Explicitly set HttpTokens=required, HttpPutResponseHopLimit=2 in the launch template.

When: Pod agents on EKS

The Kubernetes plugin creates a Pod for each build; the serviceAccountName in the Pod template determines the AWS identity (a Pod Identity association or an IRSA annotation). Note: Pod Identity does not support Pods running on EKS Fargate , in that case use IRSA; the agent Pod’s service account should not have jenkins permissions on its own namespace (plugin security recommendation). Image building (no Docker daemon), Pod template inheritance and JCasC configuration are expanded inCourse 5.

Common misconceptions① “The EC2 Fleet plugin will create the ASG for me”: no; you (ideally with Terraform) create the ASG and launch template; the plugin only adjusts capacity. ② “The bigger the agent instance role, the easier”: the instance role is the permission of every job on that machine; split node pools by purpose (build / deploy dev / deploy prod). ③ “A local controller can also use ‘empty credentials = instance role’”: that refers to the EC2 hosting the controller itself; a local controller must select an AWS credential.

EC2 Fleet architecture

Jenkins controller Build queue: label aws-deploy × 3EC2 Fleet cloud (plugin)Management identity: controller instance roleor AWS credentials (local lab)SSH launcher (credential jenkins-agent-ssh) UpdateAutoScalingGroup ASG jenkins-agentsmin 0 · max 2 · launch templateIMDSv2 · instance profile i-0a…agent i-0b…agent SSH 22 IMDSv2 role jenkins-agent-ec2only sts:AssumeRole →jenkins-myapp-deployer after N idle minutesSetInstanceProtection /TerminateInstanceInAutoScalingGroup Two identities: above is the “identity that manages the ASG” (on the controller); bottom right is the “identity that does work on AWS during the build” (on the agent) With maximum uses = 1, each instance is reclaimed after running one build — a one-off agent
Figure 6-1: the EC2 Fleet plugin only adjusts capacity; the identity on the instance comes from the launch template

Pod agent identity on EKS

controller PodKubernetes plugincreate agent Pod agent PodserviceAccountName:jenkins-agent-aws 169.254.170.23 Pod Identity AgentDaemonSet (on nodes)AssumeRoleForPodIdentity IAM rolejenkins-agent-ekstrusts pods.eks… The association lives on the EKS side (create-pod-identity-association); the IAM trust policy does not need the cluster OIDC address — a simplification relative to IRSA
Figure 6-2: whichever service account the Pod template selects determines which AWS role you get

Interaction: queue-driven EC2 Fleet scaling

Configuration: ASG min 0, max 2; 1 executor per node; maximum uses 1 (one-off); scale in after 2 idle cycles. Click “+1 build” to add a job to the queue, and observe the APIs the plugin calls and the instance states.

Build queue (label aws-deploy)
ASG jenkins-agents instances · target capacity 0 / max 2
Queuedpending / connectingonline / buildingTerminated
Queue is empty; ASG target capacity is 0 (no cost).

Command overview

CommandPurpose
aws iam create-instance-profile / add-role-to-instance-profileCreate the instance profile for the agent
aws ec2 create-launch-template … MetadataOptionsAMI, instance type, IMDSv2, user data
aws autoscaling create-auto-scaling-group --min-size 0ASG (the plugin only changes its desired count)
aws ec2 describe-instances --filters Name=tag:aws:autoscaling:groupName,Values=…View instances launched by the plugin
aws eks create-pod-identity-associationService account ↔ IAM role
aws eks create-addon --addon-name eks-pod-identity-agentInstall the Pod Identity Agent (not needed on Auto Mode clusters)

Agent instance role (may only assume the deployment role)

cat > ec2-trust.json <<'EOF'
{ "Version": "2012-10-17", "Statement": [{ "Effect": "Allow",
  "Principal": { "Service": "ec2.amazonaws.com" }, "Action": "sts:AssumeRole" }] }
EOF
aws iam create-role --role-name jenkins-agent-ec2 --assume-role-policy-document file://ec2-trust.json
aws iam put-role-policy --role-name jenkins-agent-ec2 --policy-name assume-deployer --policy-document "{
  \"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"sts:AssumeRole\",
  \"Resource\":\"arn:aws:iam::$ACCOUNT_ID:role/$DEPLOY_ROLE\"}]}"
aws iam create-instance-profile --instance-profile-name jenkins-agent-ec2
aws iam add-role-to-instance-profile --instance-profile-name jenkins-agent-ec2 --role-name jenkins-agent-ec2
# add this role to the deployment role’s trust policy (see Module 2 quiz, command-line task 2)

Launch template (Amazon Linux 2023, IMDSv2 hop limit 2)

cat > userdata.sh <<'EOF'
#!/bin/bash
set -eux
dnf install -y java-21-amazon-corretto-headless docker git jq
systemctl enable --now docker
useradd -m -s /bin/bash jenkins && usermod -aG docker jenkins
install -d -m 700 -o jenkins -g jenkins /home/jenkins/.ssh /home/jenkins/.aws
echo "ssh-ed25519 AAAAC3...REPLACE jenkins-controller" > /home/jenkins/.ssh/authorized_keys
cat > /home/jenkins/.aws/config <<'CFG'
[default]
region = ca-central-1
[profile deployer]
role_arn = arn:aws:iam::111122223333:role/jenkins-myapp-deployer
credential_source = Ec2InstanceMetadata
role_session_name = jenkins-agent
region = ca-central-1
CFG
chown -R jenkins:jenkins /home/jenkins/.ssh /home/jenkins/.aws
chmod 600 /home/jenkins/.ssh/authorized_keys
EOF
source ~/jenkinslab/aws-part4.env; MYIP=$(curl -s https://checkip.amazonaws.com)
AGENT_SG=$(aws ec2 create-security-group --group-name jenkins-agent-sg --description "jenkins agents" \
  --vpc-id $VPC_ID --query GroupId --output text)
aws ec2 authorize-security-group-ingress --group-id $AGENT_SG --protocol tcp --port 22 --cidr $MYIP/32
aws ec2 create-launch-template --launch-template-name jenkins-agent --launch-template-data "{
  \"ImageId\": \"resolve:ssm:/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64\",
  \"InstanceType\": \"t3.medium\",
  \"IamInstanceProfile\": {\"Name\": \"jenkins-agent-ec2\"},
  \"SecurityGroupIds\": [\"$AGENT_SG\"],
  \"MetadataOptions\": {\"HttpTokens\": \"required\", \"HttpPutResponseHopLimit\": 2},
  \"UserData\": \"$(base64 -w0 userdata.sh)\",
  \"TagSpecifications\": [{\"ResourceType\": \"instance\", \"Tags\": [{\"Key\": \"course\", \"Value\": \"jenkins-part4\"}]}]
}"
aws autoscaling create-auto-scaling-group --auto-scaling-group-name jenkins-agents \
  --launch-template LaunchTemplateName=jenkins-agent,Version='$Latest' \
  --min-size 0 --max-size 2 --desired-capacity 0 --vpc-zone-identifier "$SUBNETS"

How to verify:aws autoscaling describe-auto-scaling-groups --auto-scaling-group-names jenkins-agents --query 'AutoScalingGroups[0].[MinSize,MaxSize,DesiredCapacity]' returns [0, 2, 0]. Common errors: The public key in the user data was not replaced with the controller’s public key, so the SSH connection fails. Production use: The AMI should have dependencies pre-installed (Packer / EC2 Image Builder); the less user data, the faster the agent comes online.

EKS: Pod Identity + Pod template

cat > pod-trust.json <<'EOF'
{ "Version": "2012-10-17", "Statement": [{ "Effect": "Allow",
  "Principal": { "Service": "pods.eks.amazonaws.com" }, "Action": ["sts:AssumeRole","sts:TagSession"] }] }
EOF
aws iam create-role --role-name jenkins-agent-eks --assume-role-policy-document file://pod-trust.json
aws iam put-role-policy --role-name jenkins-agent-eks --policy-name deploy-myapp --policy-document file://deployer-policy.json
aws eks create-addon --cluster-name jenkins-lab-eks --addon-name eks-pod-identity-agent     # can be skipped on Auto Mode
kubectl -n jenkins create serviceaccount jenkins-agent-aws
aws eks create-pod-identity-association --cluster-name jenkins-lab-eks --namespace jenkins \
  --service-account jenkins-agent-aws --role-arn arn:aws:iam::$ACCOUNT_ID:role/jenkins-agent-eks
pipeline {
  agent {
    kubernetes {
      yaml '''
apiVersion: v1
kind: Pod
spec:
  serviceAccountName: jenkins-agent-aws
  containers:
  - name: aws
    image: public.ecr.aws/aws-cli/aws-cli:latest   # in production, pin a version or use a self-built agent image
    command: ["sleep"]
    args: ["infinity"]
'''
    }
  }
  stages {
    stage('whoami') {
      steps { container('aws') { sh 'aws sts get-caller-identity; env | grep -E "^AWS_CONTAINER" | cut -d= -f1' } }
    }
  }
}
{
    "UserId": "AROAEXAMPLE:eks-jenkins-la-jenkins-ag-0123abcd",
    "Account": "111122223333",
    "Arn": "arn:aws:sts::111122223333:assumed-role/jenkins-agent-eks/eks-jenkins-la-jenkins-ag-0123abcd"
}
AWS_CONTAINER_CREDENTIALS_FULL_URI
AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE

When Pod Identity is in effect, EKS injects AWS_CONTAINER_CREDENTIALS_FULL_URI and AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE; IRSA injects AWS_ROLE_ARN and AWS_WEB_IDENTITY_TOKEN_FILE. The session-name format follows the actual output.

Lab 6 (optional): EC2 Fleet one-off agent, removing the deployment keys from Jenkins (about 12 minutes)

Cost / risks A t3.medium in ca-central-1 costs about US$0.05 per hour (on demand; the calculator is authoritative) + a public IPv4 address; the ASG minimum is 0, and it scales in automatically when idle. A local controller needs to connect to agents via public SSH: the security group allows only your IP; in the lab you may use “do not verify host key,”production must verify.
Create the Fleet management role (a local controller has no instance role, so the bootstrap user assumes it)
cat > fleet-policy.json <<'EOF'
{ "Version": "2012-10-17", "Statement": [
  { "Effect": "Allow", "Resource": "*", "Action": [
    "ec2:DescribeSpotFleetInstances","ec2:ModifySpotFleetRequest","ec2:CreateTags","ec2:DescribeRegions",
    "ec2:DescribeInstances","ec2:TerminateInstances","ec2:DescribeInstanceStatus","ec2:DescribeSpotFleetRequests",
    "ec2:DescribeFleets","ec2:DescribeFleetInstances","ec2:ModifyFleet","ec2:DescribeInstanceTypes",
    "autoscaling:DescribeAutoScalingGroups","autoscaling:DescribeWarmPool","autoscaling:UpdateAutoScalingGroup",
    "autoscaling:SetInstanceProtection","autoscaling:TerminateInstanceInAutoScalingGroup",
    "iam:ListInstanceProfiles","iam:ListRoles"] },
  { "Effect": "Allow", "Action": "iam:PassRole", "Resource": "*",
    "Condition": { "StringEquals": { "iam:PassedToService": "ec2.amazonaws.com" } } } ] }
EOF
cp deployer-trust.json fleet-trust.json      # likewise trusts only the bootstrap user jenkins-lab-bootstrap
aws iam create-role --role-name jenkins-ec2fleet-manager --assume-role-policy-document file://fleet-trust.json
aws iam put-role-policy --role-name jenkins-ec2fleet-manager --policy-name ec2fleet --policy-document file://fleet-policy.json
# allow the bootstrap user to assume this role too
aws iam put-user-policy --user-name jenkins-lab-bootstrap --policy-name only-assume-deployer --policy-document "{
  \"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"sts:AssumeRole\",
  \"Resource\":[\"arn:aws:iam::$ACCOUNT_ID:role/$DEPLOY_ROLE\",\"arn:aws:iam::$ACCOUNT_ID:role/jenkins-ec2fleet-manager\"]}]}"

The policy content is taken from the permissions listed on the EC2 Fleet plugin page; in production, narrow Resource to that ASG, and run the controller on EC2 using its instance role (credentials left empty).

Create the agent role, launch template and ASG: run the three script segments from the “Commands” page (replacing the public key in the user data with the controller’s public key ssh-keygen -t ed25519 -f jenkins-agent generated .pub). And add jenkins-agent-ec2 to the deployment role’s trust policy.
Configure in Jenkins
  • credential: AWS Credentials, ID aws-lab-fleet, the same bootstrap key,IAM Role To Use fill in arn:aws:iam::111122223333:role/jenkins-ec2fleet-manager (this time specifying the role at the credential level).
  • Credential: SSH Username with private key, ID jenkins-agent-ssh, username jenkins.
  • Manage Jenkins → Clouds → New cloud → Amazon EC2 Fleet: in AWS Credentials choose aws-lab-fleet, Region ca-central-1, in EC2 Fleet choose jenkins-agents (ASG), Launcher choose SSH (credential jenkins-agent-ssh), Label aws-deploy, Max Idle Minutes Before Scaledown 5, Minimum/Maximum Cluster Size 0/2, Number of Executors 1, Maximum Total Uses 1. Exact field names follow the plugin version’s UI.
Run a pipeline without credentials
pipeline {
  agent { label 'aws-deploy' }
  stages {
    stage('whoami') {
      steps {
        sh 'aws sts get-caller-identity --query Arn --output text'                       // instance role
        sh 'AWS_PROFILE=deployer aws sts get-caller-identity --query Arn --output text'  // after role chaining
      }
    }
  }
}
arn:aws:sts::111122223333:assumed-role/jenkins-agent-ec2/i-0a1b2c3d4e5f60789
arn:aws:sts::111122223333:assumed-role/jenkins-myapp-deployer/jenkins-agent

The first build queues for 2–4 minutes (the ASG launches the instance + user data + SSH connection). After the build ends and it has been idle for 5 minutes, the ASG target capacity returns to 0.

Cleanup (also included in the Module 8 script)
aws autoscaling delete-auto-scaling-group --auto-scaling-group-name jenkins-agents --force-delete
aws ec2 delete-launch-template --launch-template-name jenkins-agent

Case 1: Spot interruptions cause build failures

Problem: All ASG instances used Spot; nightly batch builds were frequently interrupted by instance reclamation. Fix: ASG mixed-instance policy: 1 on-demand base capacity + Spot for the rest, spread across multiple instance types; critical deployment jobs use a separate on-demand node pool; builds set retry(conditions: [agent(), nonresumable()], count: 2). Limit: Retries of deployment-type steps must be idempotent (the approaches in Modules 3 and 4 are already idempotent).

Case 2: agents come online too slowly

Problem: Every build waits 4 minutes: user data is installing Java and Docker and pulling base images. Fix: Bake the AMI with EC2 Image Builder; enable a warm pool on the ASG (the plugin permissions include DescribeWarmPool); in EC2 Fleet set Minimum Spare Size to keep 1 machine during working hours. Limit: Reserved capacity is a cost.

Case 3: an agent on EKS could read all Secrets in the cluster

Problem: The agent Pod used the controller’s service account, which had full permissions on the jenkins namespace; a malicious Jenkinsfile read the controller’s Secret. Fix: A dedicated service account for agents, not bound to any K8s Role; AWS permissions are granted separately through Pod Identity; deployment permissions are granted only to the target namespace (Module 5).

Common errors and fixes

The node keeps showing offline, log: Connection refused / Server rejected the 1 private key(s) for jenkins

Cause: The security group does not allow port 22 from the controller’s egress IP; user data has not finished; the public key does not match; the controller is trying to connect to a private IP. Diagnosis:

aws ec2 get-console-output --instance-id i-0a1b2c3d4e5f60789 --latest --output text | tail -30
aws ec2 describe-security-groups --group-ids $AGENT_SG --query 'SecurityGroups[0].IpPermissions'
UnauthorizedOperation / AccessDenied: … is not authorized to perform: autoscaling:UpdateAutoScalingGroup

Cause: The Fleet management identity lacks permissions, or the cloud configuration uses the wrong credential (it chose a credential that can only AssumeRole the deployment role). Fix: Fill in the permissions listed on the plugin page; check the plugin’s detailed exception in the Jenkins system log (Manage Jenkins → System Log).

Builds queue on the aws-deploy label: “There are no nodes with the label ‘aws-deploy’”

Cause: The cloud configuration’s Label does not match the Jenkinsfile, or the maximum capacity has been reached. Fix: Check the labels; check the ASG’s MaxSize and EC2 Fleet’s Maximum Cluster Size. Course 7 explains systematically the causes of “builds stuck in the queue.”

In the agent Pod: An error occurred (AccessDenied) when calling the AssumeRoleForPodIdentity operation

Cause: The role trust policy lacks sts:TagSession, or the Principal is not pods.eks.amazonaws.com, or the associated namespace / service account name does not match the Pod.

aws eks list-pod-identity-associations --cluster-name jenkins-lab-eks --namespace jenkins
kubectl -n jenkins get pod -l jenkins/label -o jsonpath='{.items[*].spec.serviceAccountName}'
Command-line tasks
1. Check the current capacity and instance list of the ASG jenkins-agents.
aws autoscaling describe-auto-scaling-groups --auto-scaling-group-names jenkins-agents \
  --query 'AutoScalingGroups[0].[DesiredCapacity,Instances[].[InstanceId,LifecycleState,ProtectedFromScaleIn]]'
2. Confirm the launch template enforces IMDSv2 and the hop limit is 2.
aws ec2 describe-launch-template-versions --launch-template-name jenkins-agent --versions '$Latest' \
  --query 'LaunchTemplateVersions[0].LaunchTemplateData.MetadataOptions'
Scenario analysis
The company requires: “builds may use Spot; production deployments must run on on-demand instances; and build nodes must not have permission to deploy to production.” How would you design this with the EC2 Fleet plugin?

Two ASGs + two EC2 Fleet clouds: ① aws-build: a Spot-based mixed-instance ASG; the instance role can only push to ECR; ② aws-deploy-prod: an on-demand ASG; the instance role can only AssumeRole the production deployment role; the production deployment role’s trust policy trusts only this instance role. In the Jenkinsfile, the build stage uses agent { label 'aws-build' }, and the deployment stage uses agent { label 'aws-deploy-prod' }; the image is passed by ECR digest; then use the Course 6 authorization policy to restrict which jobs can use the aws-deploy-prod label.

Verified instructional videos

▶
Jenkins World 2017: Scaling Jenkins with Kubernetes — CloudBeesTV
English · How the Kubernetes plugin’s dynamic agents work (an older talk; for configuration screens, the current version takes precedence)
▶
How to Configure Jenkins to Use Kubernetes Pods as Build Agents — LinuxTechi
English · third-party hands-on demo
▶
EKS Pod Identity vs IRSA | Securely Connect Kubernetes Pods to AWS Services — Containers from the Couch
English · AWS identity for Pod agents

No verified video specifically on the EC2 Fleet plugin was found; see the storyboard below.

Official documentation

Video storyboard (about 60 seconds)

This courseware cannot generate video/MP3 directly; the storyboard and narration script below can be handed to a video tool.

Shot 1 · 0–20s
Visual: three tasks queue up in Jenkins; the EC2 Fleet plugin turns the ASG’s “target capacity” dial from 0 to 2.
Narration: the EC2 Fleet plugin does not create servers; it only adjusts the Auto Scaling group’s target capacity.
Shot 2 · 20–40s
Visual: the new instance wears a badge reading “jenkins-agent-ec2,” gets temporary credentials from the metadata service, then exchanges them for the deployment role’s badge.
Narration: the instance carries its own role, so the build needs no keys from Jenkins.
Shot 3 · 40–60s
Visual: the build finishes; the instance is marked “used up” and disappears; the target capacity returns to 0.
Narration: setting maximum uses to one makes it a one-off agent: no leftover login state, and no paying for idle time.
or reach a score of ≥ 70% on the quiz

Module 7 · Troubleshooting cloud deployments

45:00 – 54:00 · First ask “who am I and in which region,” then look at “which action, which resource, denied by whom”
9 minCloudTrail · decode-authorization-messageFault reproduction★★★★★
Learning objectives
  • Master the fixed troubleshooting order for Jenkins → AWS: Jenkins layer (plugins / credential ID / node) → credential chain → STS → IAM evaluation → service API → runtime.
  • Read the four elements of an AWS denial message: principal ARN, action, resource, and denial source (no allow / explicit deny / SCP / permission boundary / session policy).
  • Use CloudTrail lookup-events to find failed calls, and use sts decode-authorization-message to decode EC2’s encoded denial messages.
  • Handle Jenkins-specific problems: credential scope, network access from the controller to STS, session expiry in long builds, and IMDSv2 hop count inside agent containers.
Prerequisite knowledge: Modules 2–6. Importance:★★★★★

What: fault layers

LayerTypical symptomsFirst diagnostic command / location
JenkinsCould not find credentials entry with ID 'aws-lab-bootstrap',No such DSL method 'withAWS'credential folder / domain; whether the plugin is installed
Credential chain (agent)Unable to locate credentialsaws configure list; IMDS hop count; environment variables injected into the Pod
Credential chain (controller)binding-stage timeouts,Unable to execute HTTP request … stswhether the controller can reach STS (proxy / egress firewall); Jenkins system log
STSnot authorized to perform: sts:AssumeRole,AssumeRoleWithWebIdentity denials,ExpiredTokentrust policy, caller identity policy, session duration
IAM evaluation… is not authorized to perform: X on resource: Y, possibly with “with an explicit deny in a service control policy”permission policy, SCP, permission boundary; CloudTrail
serviceECR no basic auth credentials, ECS rollback, EKS Unauthorizedtroubleshooting pages of Modules 3–5
runtimeCannotPullContainerError,exec format errordescribe-tasks ’s stoppedReason, CloudWatch logs

Why: first confirm “who am I”

More than half of AWS permission problems are actually an identity that is not the one you think: the step is not inside a withCredentials block, and leftover different AWS_PROFILE from the agent environment, the controller’s identity used instead of the agent’s, or different default regions. So the first line of any AWS stage is recommended to be:

aws sts get-caller-identity --query Arn --output text; echo "region=${AWS_REGION:-unset}"

How: reading denial messages

  • “because no identity-based policy allows the X action”: no allow in the permission policy → add the permission.
  • “with an explicit deny in a service control policy / permissions boundary / session policy”: denied by an organization SCP, permission boundary or session policy → adding permissions has no effect; contact the platform team.
  • EC2’s “Encoded authorization failure message”: use aws sts decode-authorization-message --encoded-message … to decode it (requires sts:DecodeAuthorizationMessage permission; recommended for administrators only).
  • CloudTrail: management events from the last 90 days are available for lookup-events lookup; failed calls carry errorCode,userIdentity.arn ; the session name in it maps to the Jenkins build number.

When: four pitfalls specific to Jenkins

  1. Credential scope: the credential is created in folder A, the job is in folder B, reporting “credential not found.”
  2. Controller egress: STS calls for methods A / B happen on the controller; when the controller is restricted from egress but agents can reach the internet, binding fails while running manually on the agent works.
  3. Session expiry in long builds: the AWS Credentials plugin’s AssumeRole defaults to 3600 seconds; after a build runs longer than 1 hour, ExpiredToken. The STS token duration can be adjusted in the credential’s advanced options (the role’s maximum session duration must also be long enough); the better approach is to shorten individual stages or bind only when needed.
  4. IMDSv2 inside containers: agent { docker { … } } steps in the container access IMDS across one extra hop; they fail when the hop count is 1.
Common misconceptions① “On AccessDenied, just add AdministratorAccess and see”: if it is an explicit SCP deny, an administrator doesn’t help either, and it masks the real problem. ② “CloudTrail only records successful calls”: failed calls are recorded too, with errorCode and errorMessage. ③ “Keys are not visible in Jenkins logs, so output needs no care”: when troubleshooting, do not env print everything in full; use cut -d= -f1 to look only at variable names.

Troubleshooting roadmap

1 Jenkins layerplugin · credential ID · node 2 Who am Iget-caller-identity 3 STStrust policy · duration 4 IAM evaluationpermissions · SCP · boundary 5 ServiceECR/ECS/EKS Evidence sources Jenkins console output · Manage Jenkins → System Logaws configure list (credential source type)CloudTrail lookup-events (errorCode)ECS events / stoppedReason · kubectl describe Do not ✗ Print the full env / print tokens✗ Add AdministratorAccess first and worry later✗ Change the trust condition to a wildcard "*"✗ Edit resources by hand in the console and never write the change back to the repository
Figure 7-1: exclude layers one by one from left to right; each layer has a definite evidence source

Structure of a denial message

User: arn:aws:sts::111122223333:assumed-role/jenkins-myapp-deployer/jenkins-myapp-15 is not authorized to perform: iam:PassRole on resource: …role/myappTaskExecutionRole because no identity-based policy allows … Principalsession name → build number 15 Actioniam:PassRole ResourcemyappTaskExecutionRole Denial sourceno allow → just add the permission
Figure 7-2: when all four elements are present, the fix is nearly certain

Fault reproduction simulator

Choose a fault and step through “symptom → which layer it is in → diagnostic command → root cause → fix.” The red frame marks the layer where the fault is.

Jenkins layerplugins · credentials · nodes Credential chainenv · IMDS · Pod STStrust · duration IAM evaluationpermissions · SCP service / runtimeECR · ECS · EKS
Choose a fault first (default: the first one).

Troubleshooting command box

CommandQuestions answered
aws sts get-caller-identityWho am I (no permissions needed)
aws configure listWhere credentials come from (env / config / iam-role / container-role …), and what the region is
aws cloudtrail lookup-events --lookup-attributes AttributeKey=EventName,AttributeValue=…What happened in that call, and the error code
aws sts decode-authorization-message --encoded-message …Detailed reason for an EC2 encoded denial message
aws iam simulate-principal-policy --policy-source-arn … --action-names …Whether the identity policy allows it (not covering all cases of SCP and resource policies)
aws ec2 describe-instances --query '…MetadataOptions'Whether IMDSv2 is enforced, and the hop count
aws ecs describe-services … events / describe-tasks … stoppedReasonWhy the ECS deployment did not succeed
# find failed calls by jenkins-myapp-deployer in the last hour
aws cloudtrail lookup-events --start-time "$(date -u -d '-1 hour' +%Y-%m-%dT%H:%M:%SZ)" \
  --lookup-attributes AttributeKey=Username,AttributeValue=jenkins-myapp-15 \
  --query 'Events[].CloudTrailEvent' --output text \
  | jq -r 'select(.errorCode != null) | [.eventTime,.eventSource,.eventName,.errorCode,.errorMessage] | @tsv'
2026-11-16T10:21:07Z  ecs.amazonaws.com  RegisterTaskDefinition  AccessDenied  User: arn:aws:sts::111122223333:assumed-role/jenkins-myapp-deployer/jenkins-myapp-15 is not authorized to perform: iam:PassRole ...

In CloudTrail, the Username of an AssumeRole session is usually the session name (in this course, jenkins-myapp-<build number>), so giving sessions meaningful names is very important. Events may take a few minutes to appear in CloudTrail.

# check IMDSv2 on the agent (run the same comparison once inside the container)
TOKEN=$(curl -s -X PUT http://169.254.169.254/latest/api/token -H "X-aws-ec2-metadata-token-ttl-seconds: 60")
curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/iam/security-credentials/
# fix the hop count (without restarting the instance)
aws ec2 modify-instance-metadata-options --instance-id i-0a1b2c3d4e5f60789 \
  --http-tokens required --http-put-response-hop-limit 2
# simulate the evaluation: can the deployment role PassRole the execution role?
aws iam simulate-principal-policy \
  --policy-source-arn arn:aws:iam::111122223333:role/jenkins-myapp-deployer \
  --action-names iam:PassRole \
  --resource-arns arn:aws:iam::111122223333:role/myappTaskExecutionRole \
  --context-entries "ContextKeyName=iam:PassedToService,ContextKeyValues=ecs-tasks.amazonaws.com,ContextKeyType=string" \
  --query 'EvaluationResults[0].EvalDecision'

Lab 7: deliberately break PassRole and fix it (about 6 minutes)

Create the fault: remove the PassRole statement from the deployment role’s permissions
source ~/jenkinslab/aws-part4.env
jq 'del(.Statement[] | select(.Sid=="PassOnlyExecRoleToEcs"))' deployer-policy.json > broken.json
aws iam put-role-policy --role-name $DEPLOY_ROLE --policy-name deploy-myapp --policy-document file://broken.json
Run the myapp pipeline: the Deploy to ECS stage fails
An error occurred (AccessDeniedException) when calling the RegisterTaskDefinition operation: User: arn:aws:sts::111122223333:assumed-role/jenkins-myapp-deployer/jenkins-myapp-15 is not authorized to perform: iam:PassRole on resource: arn:aws:iam::111122223333:role/myappTaskExecutionRole because no identity-based policy allows the iam:PassRole action
ERROR: script returned exit code 254
Locate: read the four elements (principal = deployment role / build 15, action = PassRole, resource = execution role, source = no allow); use the commands from the “Commands” page simulate-principal-policy to confirm implicitDeny, and find the same event with CloudTrail.
Fix and re-run
aws iam put-role-policy --role-name $DEPLOY_ROLE --policy-name deploy-myapp --policy-document file://deployer-policy.json

IAM changes are eventually consistent and usually take effect within seconds; re-running immediately may occasionally still fail, so wait a moment and try again.

(Optional) reproduce the IMDS issue inside a container: if you built the EC2 agent from Module 6, change the instance hop count to 1 and run agent { docker { image 'public.ecr.aws/aws-cli/aws-cli:latest'; args '--entrypoint=' } } in the aws sts get-caller-identity, observe Unable to locate credentials, then change it back to 2.

Case 1: everything is AccessDenied in a new account

Problem: After the pipeline moved to a new account under the organization, the ECR push reported explicit deny in a service control policy. Root cause: The organization SCP only allows use in ca-central-1 and us-east-1 services, while the agent’s default region is us-west-2. Fix: The Jenkinsfile explicitly sets the region; the platform team provides an “allowed regions” list. Lesson: Adding IAM permissions does nothing when there is an “explicit deny in SCP.”

Case 2: all AWS stages hang after the controller upgrade

Problem: The controller moved to a new subnet with egress allowing only Git and plugin update sites; agents can reach AWS, but the method A binding calls STS on the controller and times out. Fix: Add an STS interface endpoint for the controller’s VPC or allow the egress; long term, switch to agent-side identity (methods C / D), so the controller no longer needs to access AWS.

Case 3: a 2-hour nightly integration test fails at the last step

Problem: The entire pipeline was wrapped in one withCredentials , the session expired after 1 hour, and the final update-service reported ExpiredToken. Fix: Bind only within the stages that need AWS (each binding re-runs AssumeRole); or under agent-side identity, let the SDK refresh automatically.

Common errors and fixes

ERROR: Could not find credentials entry with ID 'aws-lab-bootstrap'

Cause: Credential ID misspelled; the credential was created in another folder; or the credential type is not AWS Credentials (for example, it was created as “username and password”). Fix: Create a credential of the correct type in the job’s folder or the global domain.

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

Cause: The AssumeRole session (default 3600 seconds) expires during a long build. Fix: Narrow the binding scope and split stages; if longer is truly needed, raise the role’s maximum session duration and adjust the STS token duration in the credential’s advanced options.

An error occurred (AccessDeniedException) … with an explicit deny in a service control policy

Cause: An organization-level SCP denial (region, service, tag conditions, etc.). Fix: Confirm the region and tags; for exceptions, contact the organization administrator, since IAM cannot override it.

An error occurred (UnauthorizedOperation) when calling the RunInstances operation: You are not authorized to perform this operation. Encoded authorization failure message: …

Cause: EC2 encodes the denial details. Diagnosis:

aws sts decode-authorization-message --encoded-message "<paste encoded message>" --query DecodedMessage --output text | jq .
java.lang.NoSuchMethodError / No such DSL method 'withAWS' found among steps

Cause: Pipeline: AWS Steps is not installed, or the plugin and core / dependency versions are incompatible (the current version of that plugin requires core 2.541.1+, and the next version requires AWS Credentials 265+). Fix: Upgrade the dependencies, or switch to the withCredentials + AWS CLI approach from this course.

Command-line tasks
1. In a Jenkins sh step, print the current identity, region and credential source type, without leaking any keys.
aws sts get-caller-identity --query Arn --output text
echo "region=${AWS_REGION:-unset}"
aws configure list | sed -n '1,6p'      # show only the last 4 characters and the source type
env | grep -E '^AWS_' | cut -d= -f1
2. List calls named RegisterTaskDefinition within the last 30 minutes, along with their error codes.
aws cloudtrail lookup-events --start-time "$(date -u -d '-30 min' +%Y-%m-%dT%H:%M:%SZ)" \
  --lookup-attributes AttributeKey=EventName,AttributeValue=RegisterTaskDefinition \
  --query 'Events[].CloudTrailEvent' --output text | jq -r '[.eventTime,.userIdentity.arn,.errorCode] | @tsv'
Scenario analysis
The same Jenkinsfile succeeds on the static agent1 but reports Unable to locate credentials, on a new agent launched by EC2 Fleet, while logging in via SSH to that instance and running aws sts get-caller-identity works normally. What are the possible causes, and what is the troubleshooting order?

① The build steps run inside a Docker container (agent { docker } or docker.image().inside) and the IMDSv2 hop count is 1 → check MetadataOptions; ② the build runs as the jenkins user, and ~/.aws/config was written only under ec2-user , and the Jenkinsfile uses AWS_PROFILE=deployer → when the profile does not exist, the CLI reports The config profile (deployer) could not be found, which differs from this symptom and can be used to tell them apart; ③ the step explicitly sets empty AWS_ACCESS_KEY_ID and similar environment variables that override the default chain. Troubleshooting order: in the same sh step, run aws configure list + test with an IMDSv2 curl.

Verified instructional videos

▶
Remotely access your containers on ECS using ECS Exec! — Containers from the Couch
English · Troubleshooting a running ECS task
▶
Circuit Breakers for Amazon ECS — Containers from the Couch
English · Recognizing circuit-breaker rollbacks

No verified video specifically explaining Jenkins → AWS permission troubleshooting was found; see the storyboard below.

Official documentation

Video storyboard (about 60 seconds)

This courseware cannot generate video/MP3 directly; the storyboard and narration script below can be handed to a video tool.

Shot 1 · 0–20s
Visual: five checkpoints in a row: Jenkins, credential chain, STS, IAM, service. The detective first asks “who am I” at the first checkpoint.
Narration: the first step of troubleshooting is always to confirm the identity and region.
Shot 2 · 20–40s
Visual: a denial message is split into four cards: principal, action, resource, denial source.
Narration: reading the four elements of a denial message tells you which policy to change; if it says an explicit deny from an SCP, adding permissions is useless.
Shot 3 · 40–60s
Visual: on the CloudTrail timeline, a red event for session name jenkins-myapp-15 flashes.
Narration: name each session with the build number, and CloudTrail can match every AWS denial to a specific Jenkins build.
or reach a score of ≥ 70% on the quiz

Module 8 · Cost, cleanup & self-check

54:00 – 60:00 · Know where the money goes, delete in reverse dependency order, and finally delete that long-term key too
6 minCleanup script · troubleshooting treeMust do★★★★
Learning objectives
  • List the billing model for each type of resource in this course, and estimate the cost of “forgot to delete.”
  • Clean up in reverse dependency order: service → task definitions → cluster → logs → security groups; ASG → launch template; Lambda; ECR; IAM (policies → instance profiles → roles → access keys → users).
  • Clean up the Jenkins side: delete AWS credentials and the EC2 Fleet cloud, and confirm there is no leftover ~/.docker/config.json login state.
  • Use the interactive troubleshooting tree to review the fault paths of the whole course.
Importance:★★★★

What: billing models for this course’s resources (ca-central-1, estimated 2026-11; the AWS Pricing Calculator is authoritative)

ResourceBilling modelApproximate cost at this course’s scaleRisk of forgetting to delete
ECS cluster, task definitionsFree0None
Fargate task (0.25 vCPU / 0.5 GB)Per vCPU-hour + GB-hour, billed per secondAbout US$0.013 per hour per taskAbout US$10 per month
Public IPv4 address (task, EC2 agent)Per hourAbout US$0.005 per hour eachAbout US$3.6 per month each
ECR storagePer GB-monthAbout US$0.10 per GB-monthLow, but accumulates
CloudWatch LogsPer amount written and storedNegligible in labs3-day retention already set
EKS cluster (optional)US$0.10 per cluster per hour during standard support + nodes≥ US$0.10 per hour≥ US$73 per month
EC2 agent t3.medium (optional)Per second (minimum 60 seconds)About US$0.05 per hourLow risk when the ASG minimum capacity is 0
ALB (created by Express Mode)Per hour + LCUFrom about US$0.02–0.03 per hourAbout US$20 per month
Lambda / function URLRequests + GB-secondsWithin the free tierNone
IAM users, roles, OIDC providersFree0Security risk: leftover access keys

Why: cleanup order

AWS resources reference each other: the service holds the task’s ENI, and the ENI holds the security group; the instance profile references the role; the role carries inline policies. Deleting in reverse order avoids DependencyViolation and DeleteConflict. IAM goes last: delete resources first, then revoke the identities that can operate on them.

How: the Jenkins side must also be cleaned up

  • Manage Jenkins → Credentials: delete aws-lab-bootstrap,aws-lab-fleet,aws-oidc-idtoken (if created).
  • Manage Jenkins → Clouds: delete the Amazon EC2 Fleet cloud.
  • agent1: docker compose exec agent1 sh -c 'ls ~/.docker/config.json && cat ~/.docker/config.json | jq ".auths|keys"', if there are ECR entries, run docker logout.

When: when not to delete

If you are going straight on to Course 5, you may keep the ECR repository (the Kubernetes labs in Course 5 run on a local kind cluster and do not need AWS). Delete the other resources today; when needed, they can be rebuilt within 10 minutes with this course’s commands — which is also the reason “infrastructure should be written as code” (the Terraform course).

Common misconceptions① “Setting the ECS service desiredCount to 0 stops the cost”: tasks are no longer billed, but the service and ALB (if any) still exist; deleting them completely is cleaner. ② “Deleting an IAM user automatically deletes its access keys”: you must first delete access keys, inline policies, etc., otherwise DeleteConflict. ③ “An EKS cluster costs nothing if no Pods are running”: the control plane is billed hourly.

Resource dependencies and deletion order

1 ECS service myapp 2 Task definition revisions 3 Cluster · log group 4 Security group (after ENI release) 5 ASG (--force-delete) 6 Launch template · agent SG 7 Lambda function 8 ECR repository --force 9 EKS access entry /Pod Identity association (if any) 10 Instance profile → role(delete policies first) 11 Access key → userjenkins-lab-bootstrap 12 Jenkins credentials / cloudOIDC provider (if any) Red: continues to billYellow: depends on the formerBlue: identity (delete last) Each row has internal dependencies; rows are largely independent of each other, and IAM (the third row) goes last
Figure 8-1: stop billable resources first, then delete dependent resources, and finally revoke identities

Interaction: cost estimator

Estimated with approximate unit prices for this course (ca-central-1, estimated 2026-11; excludes tax, data transfer and free tier; only for a sense of scale).

One-click cleanup script cleanup-part4.sh

Run as administrator on your own computer. Every step tolerates “resource does not exist” (|| true), and it can be re-run.

#!/usr/bin/env bash
set -u
source ~/jenkinslab/aws-part4.env
export AWS_PAGER=""
echo "== 1 ECS =="
aws ecs update-service --cluster $CLUSTER --service $SERVICE --desired-count 0 >/dev/null 2>&1 || true
aws ecs delete-service --cluster $CLUSTER --service $SERVICE --force >/dev/null 2>&1 || true
aws ecs wait services-inactive --cluster $CLUSTER --services $SERVICE 2>/dev/null || true
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 ecs delete-task-definitions --task-definitions $(aws ecs list-task-definitions --family-prefix myapp \
  --status INACTIVE --query 'taskDefinitionArns[]' --output text) >/dev/null 2>&1 || true
aws ecs delete-cluster --cluster $CLUSTER >/dev/null 2>&1 || true
aws logs delete-log-group --log-group-name /ecs/myapp 2>/dev/null || true
echo "== 2 EC2 Fleet agents =="
aws autoscaling delete-auto-scaling-group --auto-scaling-group-name jenkins-agents --force-delete 2>/dev/null || true
aws ec2 delete-launch-template --launch-template-name jenkins-agent >/dev/null 2>&1 || true
echo "== 3 Lambda =="
aws lambda delete-function --function-name myapp-fn 2>/dev/null || true
echo "== 4 ECR =="
aws ecr delete-repository --repository-name $ECR_REPO --force >/dev/null 2>&1 || true
echo "== 5 Security groups (wait for ENI release; may need to re-run) =="
sleep 60
for sg in myapp-task-sg jenkins-agent-sg; do
  id=$(aws ec2 describe-security-groups --filters Name=group-name,Values=$sg --query 'SecurityGroups[0].GroupId' --output text 2>/dev/null)
  [ "$id" != "None" ] && aws ec2 delete-security-group --group-id $id 2>/dev/null || true
done
echo "== 6 IAM =="
del_role() {  # delete inline policies, detach managed policies, remove from instance profiles, delete the role
  local r=$1
  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
  for ip in $(aws iam list-instance-profiles-for-role --role-name $r --query 'InstanceProfiles[].InstanceProfileName' --output text 2>/dev/null); do
    aws iam remove-role-from-instance-profile --instance-profile-name $ip --role-name $r
    aws iam delete-instance-profile --instance-profile-name $ip; done
  aws iam delete-role --role-name $r 2>/dev/null && echo "deleted role $r" || true
}
for r in $DEPLOY_ROLE $EXEC_ROLE jenkins-ec2fleet-manager jenkins-agent-ec2 jenkins-agent-eks jenkins-myapp-oidc myapp-lambda-exec; do del_role $r; done
U=jenkins-lab-bootstrap
for k in $(aws iam list-access-keys --user-name $U --query 'AccessKeyMetadata[].AccessKeyId' --output text 2>/dev/null); do
  aws iam delete-access-key --user-name $U --access-key-id $k; done
for p in $(aws iam list-user-policies --user-name $U --query 'PolicyNames[]' --output text 2>/dev/null); do
  aws iam delete-user-policy --user-name $U --policy-name $p; done
aws iam delete-user --user-name $U 2>/dev/null && echo "deleted user $U" || true
echo "== Done. Optional: delete the OIDC provider, EKS access entries / Pod Identity associations, budget =="
# optional items (run only if the corresponding lab was done)
aws iam delete-open-id-connect-provider --open-id-connect-provider-arn arn:aws:iam::$ACCOUNT_ID:oidc-provider/jenkins.example.com/oidc
aws eks delete-access-entry --cluster-name jenkins-lab-eks --principal-arn arn:aws:iam::$ACCOUNT_ID:role/jenkins-myapp-deployer
aws eks list-pod-identity-associations --cluster-name jenkins-lab-eks --namespace jenkins \
  --query 'associations[].associationId' --output text \
  | xargs -n1 -I{} aws eks delete-pod-identity-association --cluster-name jenkins-lab-eks --association-id {}

Verify nothing is left over

aws resourcegroupstaggingapi get-resources --tag-filters Key=course,Values=jenkins-part4 \
  --query 'ResourceTagMappingList[].ResourceARN'
aws iam list-users --query "Users[?UserName=='jenkins-lab-bootstrap']"
aws ec2 describe-network-interfaces --filters Name=group-name,Values=myapp-task-sg --query 'NetworkInterfaces[].Status'
[]
[]
[]

The tagging API may have a short cache for deleted resources; IAM resources do not appear in that API, so check them separately.

Lab 8: run the cleanup and complete the self-check (about 5 minutes)

(if you want to do the capstone lab, do it first and come back to clean up) Save the script from the “Commands” page as ~/jenkinslab/cleanup-part4.sh and run it:
chmod +x ~/jenkinslab/cleanup-part4.sh && ~/jenkinslab/cleanup-part4.sh
== 1 ECS ==
== 2 EC2 Fleet agents ==
== 3 Lambda ==
== 4 ECR ==
== 5 Security groups (wait for ENI release; may need to re-run) ==
== 6 IAM ==
deleted role jenkins-myapp-deployer
deleted role myappTaskExecutionRole
deleted user jenkins-lab-bootstrap
== Done. Optional: delete the OIDC provider, EKS access entries / Pod Identity associations, budget ==
Jenkins-side cleanup: delete credentials aws-lab-bootstrap / aws-lab-fleet, the EC2 Fleet cloud; comment out the Deploy stage in the Jenkinsfile or add when { expression { false } }, otherwise the next build will fail.
Verify: run the three commands in “verify nothing is left over”; all should return empty arrays; the next day, check the cost allocation tags in Cost Explorer course=jenkins-part4 (cost allocation tags must be activated in the billing settings).
Self-test: complete this module’s “Quiz,” then review the troubleshooting tree on the “Troubleshooting” page.

Case 1: the forgotten EKS lab cluster

Problem: After the training, 3 EKS clusters and node groups were left behind, adding several hundred US dollars to the end-of-month bill. Fix: Uniformly tag lab resources with course / owner / expires tags; a scheduled job (which can simply be a scheduled Jenkins job) lists expired resources daily and sends notifications; set budget actions on the lab account.

Case 2: a departed employee’s access key is still in use

Problem: The IAM credential report shows an access key created 3 years ago was still in use yesterday, from a Jenkins job that nobody had maintained for a long time. Fix: Use aws iam generate-credential-report to find all long-term keys and their last-used times; migrate them one by one to methods B–E from Module 2; set SCP / check rules to prohibit creating new IAM user access keys (exceptions require approval).

Case 3: ECR storage grew quietly

Problem: Every commit pushed an image, with no lifecycle policy; a year later one repository occupied hundreds of GB. Fix: The Module 3 lifecycle policy + tag prefixes per branch (main kept longer, feature branches 7 days).

Interactive troubleshooting tree: Jenkins → AWS deployment failure

Step through from the symptom to get the diagnosis and fix commands. Covers the main faults of Modules 2–7.

Common errors during cleanup

An error occurred (DependencyViolation) when calling the DeleteSecurityGroup operation: resource sg-… has a dependent object

Cause: The ENI of an ECS task or EC2 instance has not been released yet. Fix: Wait 1–2 minutes and re-run; use aws ec2 describe-network-interfaces --filters Name=group-id,Values=sg-… to see what is occupying it.

An error occurred (DeleteConflict) when calling the DeleteRole operation: Cannot delete entity, must remove roles from instance profile first.

Cause: The role is still in an instance profile, or it still has inline or managed policies. Fix: Use the del_role function from the script, in this order: delete inline policies → detach managed policies → remove and delete the instance profile → delete the role.

An error occurred (ClusterContainsServicesException) when calling the DeleteCluster operation

Cause: The service has not yet entered INACTIVE. Fix:aws ecs wait services-inactive Then delete the cluster.

Command-line tasks
1. List the access keys of all IAM users in the account and their last-used times (to find long-term keys).
aws iam generate-credential-report >/dev/null; sleep 5
aws iam get-credential-report --query Content --output text | base64 -d \
  | cut -d, -f1,9,10,11 | column -t -s,
2. Delete the ECR repository myapp and all images in it.
aws ecr delete-repository --repository-name myapp --force
Scenario analysis
You need to write a “minimum security baseline for AWS on Jenkins” for the team, listing 5 items.

① Do not create new IAM user access keys; when Jenkins runs on AWS, use instance roles / Pod Identity; when it is not on AWS, prefer the OIDC Provider plugin; if absolutely necessary, a key may only AssumeRole one role and must be rotated regularly. ② Split deployment roles by application × environment, with minimal permissions,iam:PassRole precisely scoped to roles and with PassedToService conditions. ③ Production deployment agents use an independent node pool; the trust policy trusts only that pool’s identity or the OIDC of specific jobs sub. ④ Session names include the job and build number so that CloudTrail is traceable; ECR is immutable + deployment by digest. ⑤ One-off agents or DOCKER_CONFIG / KUBECONFIG isolation, with no login state left after the build ends; lab resources are tagged and cleaned up regularly.

Verified instructional videos

▶
Cost optimization on AWS Fargate — Containers from the Couch
English · Fargate cost optimization
▶
AWS re:Invent 2023 - Boosting efficiency: How to realize 70% cost reduction with AWS Fargate -CON318 — AWS Events
English · Fargate cost case study

Official documentation

Video storyboard (about 45 seconds)

This courseware cannot generate video/MP3 directly; the storyboard and narration script below can be handed to a video tool.

Shot 1 · 0–20s
Visual: meters tick next to Fargate, EKS and public IPs; the EKS meter is the fastest.
Narration: the most expensive item in this course is the optional EKS cluster; its control plane bills every hour.
Shot 2 · 20–45s
Visual: dominoes fall in reverse order: the service, the task definitions, the cluster, the security groups, and finally the bronze key is melted down.
Narration: clean up in reverse dependency order, and finally delete the access keys and the user, so the only long-term key the course left behind disappears too.
or reach a score of ≥ 70% on the quiz

Command cheat sheet

Quick reference for common Jenkins → AWS (ca-central-1) commands, Jenkinsfile snippets and quick troubleshooting
After-class review

1 Identity

aws sts get-caller-identity
aws configure list
aws iam create-role --role-name jenkins-myapp-deployer \
  --assume-role-policy-document file://trust.json
aws iam put-role-policy --role-name jenkins-myapp-deployer \
  --policy-name deploy-myapp --policy-document file://policy.json
aws iam update-assume-role-policy --role-name … --policy-document file://…

2 Jenkins credential binding

withCredentials([[$class: 'AmazonWebServicesCredentialsBinding',
  credentialsId: 'aws-lab-bootstrap',
  roleArn: 'arn:aws:iam::111122223333:role/jenkins-myapp-deployer',
  roleSessionName: "jenkins-myapp-${env.BUILD_NUMBER}"]]) { sh 'aws …' }

withCredentials([file(credentialsId: 'aws-oidc-idtoken',
  variable: 'AWS_WEB_IDENTITY_TOKEN_FILE')]) { sh 'aws …' } // + AWS_ROLE_ARN

3 ECR

aws ecr create-repository --repository-name myapp \
  --image-tag-mutability IMMUTABLE --image-scanning-configuration scanOnPush=true
aws ecr get-login-password --region ca-central-1 | docker login \
  --username AWS --password-stdin 111122223333.dkr.ecr.ca-central-1.amazonaws.com
aws ecr describe-images --repository-name myapp --image-ids imageTag=$TAG \
  --query 'imageDetails[0].imageDigest' --output text
export DOCKER_CONFIG=$WORKSPACE_TMP/docker   # login state belongs only to this build

4 ECS

TD=$(aws ecs register-task-definition --cli-input-json file://td.json \
  --query taskDefinition.taskDefinitionArn --output text)
aws ecs update-service --cluster myapp-lab --service myapp --task-definition $TD
aws ecs wait services-stable --cluster myapp-lab --services myapp
aws ecs describe-services --cluster myapp-lab --services myapp \
  --query "services[0].deployments[?status=='PRIMARY'] | [0].[taskDefinition,rolloutState]"

5 EKS

aws eks create-access-entry --cluster-name C --principal-arn ROLE_ARN
aws eks associate-access-policy --cluster-name C --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 C --kubeconfig $WORKSPACE_TMP/kubeconfig
kubectl -n myapp set image deployment/myapp myapp=$IMAGE_URI
kubectl -n myapp rollout status deployment/myapp --timeout=180s

6 Lambda

docker build --platform linux/amd64 --provenance=false -f Dockerfile.lambda …
V=$(aws lambda update-function-code --function-name myapp-fn \
  --image-uri $URI --publish --query Version --output text)
aws lambda wait published-version-active --function-name myapp-fn --qualifier $V
aws lambda update-alias --function-name myapp-fn --name live --function-version $OLD \
  --routing-config 'AdditionalVersionWeights={"'$V'"=0.1}'

7 Agents (EC2 Fleet / EKS)

aws autoscaling describe-auto-scaling-groups --auto-scaling-group-names jenkins-agents \
  --query 'AutoScalingGroups[0].[DesiredCapacity,Instances[].InstanceId]'
aws ec2 modify-instance-metadata-options --instance-id i-… \
  --http-tokens required --http-put-response-hop-limit 2
aws eks create-pod-identity-association --cluster-name C --namespace jenkins \
  --service-account jenkins-agent-aws --role-arn ROLE_ARN

8 Troubleshooting and cleanup

aws cloudtrail lookup-events --lookup-attributes AttributeKey=Username,AttributeValue=jenkins-myapp-15
aws sts decode-authorization-message --encoded-message "…"
aws iam simulate-principal-policy --policy-source-arn ROLE_ARN --action-names iam:PassRole
aws ecs delete-service --cluster myapp-lab --service myapp --force
aws ecr delete-repository --repository-name myapp --force

Quick troubleshooting table

SymptomMost likely causeFirst step
Unable to locate credentialsNot inside a binding block / agent has no role / IMDS hop count 1 inside a containeraws configure list
not authorized to perform: sts:AssumeRoleTrust policy or caller identity policy mismatchaws iam get-role … AssumeRolePolicyDocument
InvalidIdentityToken: Couldn't retrieve verification keySTS cannot reach the Jenkins issuer / JWKS mismatchcurl …/oidc/.well-known/openid-configuration
no basic auth credentialsdocker is not logged in to this registry (different DOCKER_CONFIG / different nodes)Check the auths in config.json
tag invalid … repository is immutableRepeated push of the same tagSkip the push if it exists
iam:PassRole deniedDeployment role lacks PassRole or conditions do not matchsimulate-principal-policy
Build is green but production runs the old versionservices-stable still succeeds after the circuit-breaker rollbackVerify the PRIMARY task definition
kubectl UnauthorizedNo access entry / kubectl outside the binding blockaws eks list-access-entries
Lambda unsupported manifest media typeMulti-manifest index (provenance)--provenance=false --platform linux/amd64
ExpiredTokenSession expires after 1 hourNarrow the binding scope

Recommended config snippet: deployment role trusts the EC2 agent role (no long-term keys)

{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": { "AWS": "arn:aws:iam::111122223333:role/jenkins-agent-ec2" },
    "Action": "sts:AssumeRole"
  }]
}

Recommended config snippet: Jenkins OIDC (trust only myapp’s main branch)

{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": { "Federated": "arn:aws:iam::111122223333:oidc-provider/jenkins.example.com/oidc" },
    "Action": "sts:AssumeRoleWithWebIdentity",
    "Condition": { "StringEquals": {
      "jenkins.example.com/oidc:aud": "sts.amazonaws.com",
      "jenkins.example.com/oidc:sub": "https://jenkins.example.com/job/myapp-multibranch/job/main/" } }
  }]
}

Capstone lab + final quiz

One Jenkinsfile: test → push immutable image → deploy to ECS (failure is detectable) → smoke test → cleanup; use as few long-term keys as possible
About 30 minutesca-central-1Run cleanup when finished

Scenario

You are responsible for moving myapp’s releases from “manual docker push + console updates” to Jenkins. Requirements: ① every merge into main is automatically tested and pushes an immutable image; ② deploy to the ECS Fargate service myapp, a circuit-breaker rollback must make the build fail; ③ Jenkins keeps at most one long-term key that can only AssumeRole (in the local lab environment), and you write out the steps for migrating to a keyless approach; ④ CloudTrail can map each deployment to a build number; ⑤ after the lab, resources return to zero.

Base resources: following Module 1’s lab, create the cluster, log group, security group and execution role; following Module 3, create the ECR repository (IMMUTABLE, scanOnPush, lifecycle policy).
source ~/jenkinslab/aws-part4.env
aws ecs describe-clusters --clusters $CLUSTER --query 'clusters[0].status'
aws ecr describe-repositories --repository-names myapp --query 'repositories[0].imageTagMutability'
Identities: following Module 2, create jenkins-lab-bootstrap (AssumeRole only) and jenkins-myapp-deployer (ECR push + ECS deployment + precise PassRole), and create the aws-lab-bootstrap credential in Jenkins.
Complete Jenkinsfile (commit to lab/myapp root directory)
pipeline {
  agent { label 'linux docker' }
  options { disableConcurrentBuilds(); timeout(time: 30, unit: 'MINUTES') }
  environment {
    AWS_REGION = 'ca-central-1'
    ACCOUNT_ID = '111122223333'
    REGISTRY   = '111122223333.dkr.ecr.ca-central-1.amazonaws.com'
    DEPLOY_ROLE_ARN = 'arn:aws:iam::111122223333:role/jenkins-myapp-deployer'
  }
  stages {
    stage('Build') {
      steps {
        script { env.IMAGE_TAG = '1.1-' + sh(returnStdout: true, script: 'git rev-parse --short=7 HEAD').trim() }
        sh 'docker build --pull -t myapp:$IMAGE_TAG .'
      }
    }
    stage('Test') { steps { sh 'docker run --rm myapp:$IMAGE_TAG python -m pytest -q' } }
    stage('Push & Deploy') {
      when { branch 'main' }
      environment { DOCKER_CONFIG = "${env.WORKSPACE_TMP}/docker" }
      steps {
        withCredentials([[$class: 'AmazonWebServicesCredentialsBinding', credentialsId: 'aws-lab-bootstrap',
                          roleArn: env.DEPLOY_ROLE_ARN, roleSessionName: "jenkins-myapp-${env.BUILD_NUMBER}"]]) {
          sh '''
            set -eu
            aws sts get-caller-identity --query Arn --output text
            aws ecr get-login-password --region "$AWS_REGION" | docker login --username AWS --password-stdin "$REGISTRY"
            if aws ecr describe-images --repository-name myapp --image-ids imageTag=$IMAGE_TAG >/dev/null 2>&1; then
              echo "Image already exists, skipping push"
            else
              docker tag myapp:$IMAGE_TAG $REGISTRY/myapp:$IMAGE_TAG
              docker push $REGISTRY/myapp:$IMAGE_TAG
            fi
            DIGEST=$(aws ecr describe-images --repository-name myapp --image-ids imageTag=$IMAGE_TAG \
                     --query 'imageDetails[0].imageDigest' --output text)
            IMAGE_URI=$REGISTRY/myapp@$DIGEST
            jq --arg img "$IMAGE_URI" --arg exec "arn:aws:iam::$ACCOUNT_ID:role/myappTaskExecutionRole" \
               '.containerDefinitions[0].image=$img | .executionRoleArn=$exec' deploy/ecs-taskdef.json > td.json
            TD=$(aws ecs register-task-definition --cli-input-json file://td.json \
                 --query taskDefinition.taskDefinitionArn --output text)
            aws ecs update-service --cluster myapp-lab --service myapp --task-definition "$TD" >/dev/null
            aws ecs wait services-stable --cluster myapp-lab --services myapp
            OUT=$(aws ecs describe-services --cluster myapp-lab --services myapp \
                  --query "services[0].deployments[?status=='PRIMARY'] | [0].[taskDefinition,rolloutState]" --output text)
            echo "$OUT"
            [ "$(echo "$OUT" | cut -f1)" = "$TD" ] && [ "$(echo "$OUT" | cut -f2)" = "COMPLETED" ] || {
              aws ecs describe-services --cluster myapp-lab --services myapp \
                --query 'services[0].events[:5].message' --output text; exit 1; }
          '''
        }
      }
      post { always { sh 'docker logout $REGISTRY || true' } }
    }
  }
}
First creation of the service: following step 2 of the Module 4 lab, the administrator creates the service (with the circuit breaker + rollback enabled); afterwards only Jenkins updates it.
Traceability verified: after one successful deployment, query CloudTrail by session name:
aws cloudtrail lookup-events --lookup-attributes AttributeKey=Username,AttributeValue=jenkins-myapp-<build number> \
  --query 'Events[].[EventTime,EventName]' --output table
Failed verification is recognizable: on a temporary branch, add "command": ["sh","-c","exit 1"] and temporarily remove when, confirm that the build fails and prints the ECS events; then delete the branch.
Write out a keyless migration plan (text is sufficient): move the controller to EC2 and switch to method B, or switch the agents to EC2 Fleet + instance profile (method C, Module 6), or configure the OIDC Provider plugin (method E); delete aws-lab-bootstrap.
Cleanup: run the cleanup-part4.sh from Module 8 and verify that nothing is left over.
Acceptance checklist

Open-ended self-test (answer on your own first, then expand)

1. Why is “AWS Credentials plugin with the key left empty + role ARN” not “using the agent’s instance role”?

The credential is bound and resolved on the controller: the plugin creates an STS client in the controller JVM using the SDK default credential chain and calls AssumeRole, so the identity used is that of the environment the controller runs in (EC2 instance role, the controller Pod’s Pod Identity, etc.). The agent’s instance role is used only when the AWS CLI / SDK runs directly on the agent (not through the binding).

2. What are the similarities and differences between Jenkins’ OIDC and GitHub Actions’ OIDC?

Same: both use JWTs + an IAM OIDC provider + AssumeRoleWithWebIdentity, and the trust policy constrains via aud/sub conditions. Different: GitHub’s issuer is hosted by GitHub and publicly reachable; Jenkins needs the OpenID Connect Provider plugin, and your own Jenkins signs the tokens, so the issuer must be reachable by AWS (or the two static JSON files must be hosted), and you are responsible for protecting and rotating the signing private key; the default sub is the job URL rather than the repository/branch. Compare with GitHub Course 4.

3. Why does the ECR docker login state need extra attention?

The token is valid for 12 hours and is independent of the STS session lifetime; once it is written into the agent’s ~/.docker/config.json , other builds on the same agent can use it directly. Use DOCKER_CONFIG to isolate it, log out in post, or use one-off agents.

4. When deploying to EKS, what is each of IAM and Kubernetes responsible for?

IAM: authentication (who) and eks:DescribeCluster; the access entry maps the IAM principal to Kubernetes permissions (access policy or groups + RBAC); Kubernetes authorization decides whether it can patch a Deployment. Missing any layer fails: a missing access entry gives Unauthorized; a wrong scope gives Forbidden.

5. What do the EC2 Fleet plugin and the Kubernetes plugin have in common regarding identity?

Both move identity out of Jenkins credentials and onto the infrastructure that runs the agent: an EC2 instance profile / Pod service account (Pod Identity or IRSA). In both cases the isolation granularity is “node pool / Pod template,” so Jenkins authorization must be combined to control who can use which label or template.

6. If the organization prohibits all long-term keys while Jenkins must stay on the internal network, what is your approach?

OpenID Connect Provider plugin + alternate issuer: host the two static files (discovery and JWKS) on public HTTPS (e.g. S3 + CloudFront), register the issuer in IAM, and restrict the trust policy by job URL; the agent needs to be able to reach STS (via a VPC endpoint or an egress proxy). You can also evaluate IAM Roles Anywhere (exchanging certificates for temporary credentials).

Sources & version notes

All versions and behaviors were verified against official pages on 2026-11-16; command outputs that were not actually run are labeled “example”
Verified 2026-11-16

Source table

TopicVerified conclusionSource (date accessed)
Jenkins LTSLatest LTS 2.580.2 (2026-10-28); from 2.555.1 Java 21+ is required, tested with JDK 21 / 25; the Docker documentation recommends jenkins/jenkins:lts-jdk21jenkins.io/changelog-stable · Installing Jenkins in Docker(2026-11-16)
AWS Credentials plugin265.v8422a_f384cd9, requires core 2.479.3; binding AmazonWebServicesCredentialsBinding supports roleArn / roleSessionName, injects (when a role is present) AWS_SESSION_TOKEN; source code: when the key is empty and a role is configured, the SDK default credential chain is used (“delegation to instance profile”); the default STS duration is 3600 seconds; supports external ID and MFAplugins.jenkins.io/aws-credentials · GitHub source AWSCredentialsImpl.java(2026-11-16)
Pipeline: AWS Steps767.v48d5c10b_1899, requires core 2.541.1; withAWS supports role / roleAccount / externalId / duration / SAML / useNode, looks up credentials on the controller by default; the documentation does not list Web Identity; provides ecrLogin; the next version migrates to AWS SDK v2plugins.jenkins.io/pipeline-aws(2026-11-16)
OpenID Connect Provider plugin234.vca_b_26b_f4b_dda_, requires core 2.568.1; two kinds of credentials (id token / id token as file), default issuer https://HOST/oidc, default sub is the job URL, customizable via the claim template; AWS example: AWS_ROLE_ARN + AWS_WEB_IDENTITY_TOKEN_FILE; AWS fetches the public key from the issuer on every AssumeRole; an alternate issuer can be set and two static JSON files hosted; non-global credential domains are not supportedplugins.jenkins.io/oidc-provider · README(2026-11-16)
EC2 Fleet plugin4.5.2.571.v0932f9cd1039; supports ASG / EC2 Fleet / Spot Fleet (Spot Fleet is a legacy API; ASG is recommended); IAM permission list; leaving credentials empty uses the EC2 instance role; the documentation describes the SSH connectionplugins.jenkins.io/ec2-fleet(2026-11-16; the minimum core version in the page sidebar and in the body text differ: 2.555.3 / 2.541.3)
Amazon EC2 plugin2068.vd80935072db_b_, requires core 2.479.3; the configuration example includes useInstanceProfileForCredentialsplugins.jenkins.io/ec2(2026-11-16)
Kubernetes plugin4560.vc25b_83890c34, requires core 2.516.3; Pod templates support serviceAccount; optional WebSocket; agent Pods should not use a service account with permissions on their own namespaceplugins.jenkins.io/kubernetes(2026-11-16)
Amazon ECR plugin1.175.ve233e80e56fd,looking for a maintainer (adopt-this-plugin); docker.withRegistry(url, 'ecr:region:id')plugins.jenkins.io/amazon-ecr(2026-11-16)
ECR authenticationget-login-password | docker login --username AWS --password-stdin; tokens last 12 hours; the permission scope equals the principal that obtained the token; the Credential Helper does not yet support MFAECR User Guide: private registry authentication(2026-11-16)
EKS Pod IdentityTrust principal pods.eks.amazonaws.com; the agent is a DaemonSet (169.254.170.23, ports 80 / 2703); does not support Pods on Fargate, Windows EC2 nodes; up to 5000 associations per cluster; Auto Mode does not require installing the agentEKS User Guide: Pod Identity(2026-11-16)
EKS access entriesofficially described as the best way to grant access to the Kubernetes API; two authorization methods: access policies or Kubernetes groupsEKS User Guide: access entries(2026-11-16)
IAM OIDC providerURL must be https with no port; discovery and JWKS are required; AWS validates the JWKS endpoint certificate using its trusted root CA library, and falls back to the thumbprint only for untrusted CAs / when the certificate cannot be retrieved / when TLS 1.3 is requiredIAM User Guide(2026-11-16)
Lambda container imagesmust implement the Runtime API; Linux only; multi-architecture images are not supported; uncompressed maximum 10 GB; ECR and the function must be in the same region; the function enters Failed after its image is deletedLambda Developer Guide(2026-11-16)
Lambda Web AdapterREADME Quick Start uses public.ecr.aws/awsguru/aws-lambda-adapter:1.1.0; AWS_LWA_PORT (default 8080),AWS_LWA_READINESS_CHECK_PATHGitHub README(2026-11-16)
App RunnerNo longer accepts new customers; existing customers may continue using it; ECS Express Mode is recommended (it is itself free of charge)App Runner availability change(2026-11-16)
PricesAll amounts in this course are approximate estimates for ca-central-1, meant only to give a sense of scaleAWS Pricing Calculator

Video verification notes

All videos listed in this course had their titles and channels verified on 2026-11-16 through the YouTube oEmbed endpoint (https://www.youtube.com/oembed?url=…&format=json), verified titles and channels on 2026-11-16:

Video IDTitleChannelModule
Nv7s-N8ZxQADeploying a Modern Application Stack to AWS Fargate with Amazon ECS - AWS Online Tech TalksAWS DevelopersM1
7fjJqokRlKIServerless for container fans via Amazon ECS and AWS LambdaBret FisherM1 / M5
T-fFyEsLXXEAWS re:Invent 2024 - Unleashing the power of Amazon ECS for platform teams (SVS330)AWS EventsM1
aUjJSorBE70EKS Pod Identity vs IRSA | Securely Connect Kubernetes Pods to AWS ServicesContainers from the CouchM2 / M6
FeUsAU_5mMMHow to Give AWS IAM Role in Jenkins | AWS IAM Role Training | Jenkins IAM Role TutorialDorothy ScottM2
GtbTmvMcKRgAmazon Elastic Container Registry (Amazon ECR) Explained | Amazon Web ServicesAmazon Web ServicesM3
PHuKrcsAaDwAWS re:Invent 2023 - Dive deep into Amazon ECR (CON405)AWS EventsM3
UBGeWf3PKOMHow to Push a Docker Image from Jenkins to Amazon Elastic Container Registry (ECR)iQuantM3
Y2Ez9M7A95YCircuit Breakers for Amazon ECSContainers from the CouchM4 / M7
o7s-eigrMAIHow to Setup AWS ECS Fargate with a Load Balancer | Step by StepBe A Better DevM4
xnHD_dCzE_EThe Complete Guide to ECS Blue/Green Deployments on AWSAWS DevelopersM4
p6xDCz00TxUAWS EKS - Create Kubernetes cluster on Amazon EKS | the easy wayTechWorld with NanaM5
s9d61eYkGzsAmazon EKS Auto Mode | Fully Automated Kubernetes ClustersAWS DevelopersM5
DCkzdsffeh0Jenkins World 2017: Scaling Jenkins with KubernetesCloudBeesTVM6
IwRa_qLywvgHow to Configure Jenkins to Use Kubernetes Pods as Build AgentsLinuxTechiM6
NyiMoyx_xj4Remotely access your containers on ECS using ECS Exec!Containers from the CouchM7
Cnmejv98sv0Cost optimization on AWS FargateContainers from the CouchM8
WVGxnUEr1OUAWS re:Invent 2023 - Boosting efficiency: How to realize 70% cost reduction with AWS Fargate -CON318AWS EventsM8

No verified videos were found for: Jenkins OpenID Connect Provider plugin + AWS, the EC2 Fleet plugin topic, and Jenkins → AWS permission troubleshooting; storyboard scripts are provided for the corresponding modules. Third-party videos (Dorothy Scott, iQuant, LinuxTechi) are for UI reference only; if they use long-term access keys or mutable tags, follow this course’s approach. oEmbed can only confirm titles and channels; it cannot confirm durations or content details.

Voice narration notes

The “Voice” page uses the browser’s built-in Web Speech API (speechSynthesis), reading Chinese with the zh-CN voice and English terms with the en-US voice. This courseware is a single offline HTML file,cannot embed or generate MP3; the narration script can be copied directly into a TTS tool or used for recording. When no Chinese voice pack is installed, the page shows installation instructions, and the narration script is still readable.

Known limitations

  • Command outputs are all “examples”: the environment in which this courseware was written had no real AWS account and no public Jenkins; all AWS / Jenkins commands were written from official documentation and plugin source code and were not actually run; account numbers 111122223333, IDs and digests are all example values.
  • The advanced OIDC Provider plugin lab has not been run: it requires a publicly reachable HTTPS issuer; the IAM provider URL and sub formats follow the values shown on the plugin’s “Update” page.
  • AWS Credentials plugin “key left empty + role” behavior comes from source code, not documentation; after upgrading the plugin, verify it yourself.
  • EC2 Fleet plugin UI field names (maximum idle minutes, maximum uses, etc.) are summarized from the plugin page descriptions; UI wording may differ between versions; for the full options see the CONFIGURATION-OPTIONS document in the plugin repository.
  • Prices are approximate estimates for ca-central-1 and exclude tax, data transfer and the free tier; please refer to the AWS Pricing Calculator.
  • myapp’s test command (python -m pytest runs inside the image) assumes the image contains the test dependencies; if the production image from the Docker course does not include pytest, use a test target of a multi-stage build instead.
  • Lambda Web Adapter is an AWS open-source project rather than a core Lambda feature; follow its README for the version; a Flask app on Lambda cannot connect to the Redis that this course does not deploy, so a page showing Redis unavailable is normal.
  • Courses 1–3 were written in parallel with this course; this course depends only on the shared course conventions (~/jenkinslab,agent1 tag linux docker, Gitea lab/myapp, credential ID gitea-myapp / registry-creds).