Jenkins Hour 4: Moving to the Cloud Platform (AWS)
- 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-passwordto push to immutable tags in the ECR repositorymyapp, 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 credentialsand other typical errors.
1-hour time allocation table
| # | Time | Module | Core content | Animation / interaction | Lab (AWS account · ca-central-1) |
|---|---|---|---|---|---|
| 0 | Before class | Warm-up & AWS setup | AWS CLI v2, budget alerts, install the AWS CLI on agent1, install plugins, variables file | Prerequisite self-check | aws sts get-caller-identity |
| 1 | 00–05 | Choosing a deployment architecture on AWS | ECS Fargate / Express Mode / EKS / Lambda; App Runner status; Jenkins has no “official deployment plugin,” so it relies on the AWS CLI | Deployment target selector | Create ECS cluster, log group, security group |
| 2 | 05–13 | Jenkins identity on AWS | Access keys + AssumeRole, instance profiles, Pod Identity / IRSA, OIDC Provider plugin; controller-side vs. agent-side resolution | Core animation: how credentials reach AWS (5 paths) | Create deployment role jenkins-myapp-deployer, pipeline prints identity |
| 3 | 13–21 | Build and push to ECR | ECR login token lasts 12 hours, IMMUTABLE, scan on push, digest, lifecycle policy; why not registry-creds | ECR API sequence of docker push | Pipeline push myapp:1.1-<sha> |
| 4 | 21–29 | Deploy to ECS on Fargate | Task definition rendering, update-service, services-stable, deployment circuit breaker, iam:PassRole | Rolling deployment + circuit-breaker state machine | Pipeline deploys the myapp service |
| 5 | 29–37 | Deploy to EKS and Lambda | EKS access entries,aws eks get-token, kubectl; Lambda container image + Web Adapter, versions and aliases | kubectl → IAM → K8s RBAC authentication chain; weighted aliases | (Optional) Lambda function URL |
| 6 | 37–45 | Jenkins agents on AWS | EC2 Fleet plugin + auto scaling group + instance profile; Kubernetes plugin pod agent on EKS + Pod Identity | Queue-driven scaling simulation | (Optional) ASG agent, without access keys |
| 7 | 45–54 | Troubleshooting cloud deployments | Credential chain, AssumeRole denials, IMDS hop count, ECR login, ECS stuck, EKS Unauthorized, Lambda multi-architecture manifest | Fault reproduction simulator | Deliberately break PassRole and fix it |
| 8 | 54–60 | Cost, cleanup & self-check | Cost breakdown, cleanup order, revoking keys and roles; interactive troubleshooting tree | Cost estimator | One-click cleanup script |
| — | After class | Cheat sheet · Capstone lab | Jenkins (no long-term keys) → ECR (immutable) → ECS (circuit-breaker rollback) → cleanup | Final quiz (12 questions) | Capstone lab |
Knowledge Coverage Matrix
| Target skills | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands / plugins | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Choosing an AWS compute service by scenario | ✓ | · | · | ✓ | ✓ | · | · | ✓ | Decision table | M1 |
| Choosing an identity method for Jenkins → AWS | · | ✓ | ✓ | · | ✓ | ✓ | ✓ | ✓ | AWS Credentials, OpenID Connect Provider | M2 / M6 |
| Least-privilege deployment role + trust policy | · | ✓ | ✓ | ✓ | · | ✓ | ✓ | · | aws iam create-role,iam:PassRole | M2 |
| Push immutable images and reference them by digest | · | · | ✓ | ✓ | ✓ | · | ✓ | · | aws ecr get-login-password | M3 |
| ECS deployment, waiting for stability, circuit-breaker rollback | · | · | · | ✓ | · | · | ✓ | · | aws ecs update-service,wait services-stable | M4 / Capstone |
| EKS access entries and kubectl deployment | · | · | · | · | ✓ | ✓ | ✓ | · | aws eks create-access-entry | M5 (reading / optional) |
| Lambda container images, versions and aliases | ✓ | · | · | · | ✓ | · | ✓ | · | aws lambda update-alias | M5 (optional) |
| Dynamic agents on AWS | · | ✓ | · | · | · | ✓ | ✓ | ✓ | EC2 Fleet, Kubernetes plugin | M6 (optional) |
| Locating cloud deployment failures | · | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | CloudTrail,describe-services | M7 |
| Cost control & complete cleanup | · | · | ✓ | · | · | ✓ | · | ✓ | aws ecs delete-service --force | M8 |
What this course does not cover (and where to learn it)
| Topic | Why it is not in this course | Where to learn |
|---|---|---|
| Deploying to AWS with OIDC from GitHub Actions (configure-aws-credentials, ECS Action) | This course covers only Jenkins’ approach; compare, don’t repeat | GitHub Course 4 (AWS) |
| AWS service connections and OIDC in Azure Pipelines | Same as above | Azure DevOps Course 4 (AWS) |
| Dockerfile, multi-stage builds, ECS task definition fields and ALB details | Containers themselves are covered in the Docker course | Docker Course 4 (AWS) |
| EKS cluster creation, VPC CNI, Karpenter, Auto Mode | Belongs to Kubernetes platform operations | K8s Course 7 (EKS) |
| Managing roles, ECR and ECS with Terraform | This course uses the CLI so that every step is “visible”; production should use IaC instead | Terraform Course 4 (AWS) |
| Jenkins Helm chart, JCasC declaring the cloud and credentials | Course 5 topics | Jenkins Course 5 |
| Azure managed identity, workload identity and ACR | Covered in the previous course; this course maps to it one-to-one | Jenkins Course 3 (Azure) |
How to use this courseware
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.
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).
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.
jenkins-lab-bootstrap) may only be allowed sts:AssumeRole to one role, and deleted in Module 8. Prices are based on AWS Pricing Calculator .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.~/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)
- Completed Courses 1 and 2:
~/jenkinslabundercompose.yamlstartedjenkins(127.0.0.1:8080),agent1(labellinux docker, able to rundocker build),gitea(127.0.0.1:3000, repositorylab/myapp, credential IDgitea-myapp). - myapp: Flask + gunicorn, listening on 5000,
/healthzdoes 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 identity | EKS Pod Identity / IRSA | Kubernetes pod agent exchanges a service account for a cloud identity |
| Entra federated credential + Jenkins OIDC token | IAM OIDC identity provider + AssumeRoleWithWebIdentity | both depend on the OpenID Connect Provider plugin; the issuer must be reachable by the cloud vendor |
| ACR / Container Apps / AKS | ECR / ECS Fargate / EKS | Image 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
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.
Module 1 · Choosing a deployment architecture on AWS
- 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.
What: four mainstream landing targets
| ECS on Fargate | ECS Express Mode | EKS | Lambda | |
|---|---|---|---|---|
| What you deliver | Image + task definition JSON + service configuration | Image + two IAM roles (one API call) | Image + Kubernetes manifests / Helm chart | Container image (requires the Lambda runtime interface) or zip |
| What AWS manages for you | Servers, scheduling, rolling deployments | Automatically creates the ALB, autoscaling and networking on top of ECS | Control plane (Auto Mode also manages nodes) | All servers and scaling; billed per request |
| Core commands in the Jenkinsfile | aws ecs register-task-definition → update-service → wait services-stable | aws ecs create-express-gateway-service / update | aws eks update-kubeconfig → kubectl / helm | aws lambda update-function-code → publish-version → update-alias |
| Core permissions needed by the deployment identity | ecs:RegisterTaskDefinition,ecs:UpdateService,ecs:DescribeServices,iam:PassRole | Express service create/update + iam:PassRole | eks:DescribeCluster + EKS access entry | lambda:UpdateFunctionCode,PublishVersion,UpdateAlias |
| Typical cost starting points | Billed by task vCPU/memory-seconds | Express Mode itself is free; you pay only for underlying resources (Fargate, ALB, etc.) | Cluster US$0.10 per hour (standard support) + nodes | Requests + 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-definitionand 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 ECRThe plugin (docker.withRegistry('…', 'ecr:region:id')) is currently marked “looking for a maintainer” on plugins.jenkins.io, so this course uses the official documentation’saws 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).
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
Decision flow
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.
Core commands: survey the “foundation” of the account
| Command | Purpose | Notes |
|---|---|---|
aws ec2 describe-vpcs --filters Name=is-default,Values=true | Find default VPC | This lab uses public subnets in the default VPC, which saves NAT gateway costs |
aws ecs create-cluster --cluster-name myapp-lab | Create ECS cluster | The cluster itself is free; first use automatically creates the ECS service-linked role |
aws logs create-log-group --log-group-name /ecs/myapp | Create log group | A task definition that references a non-existent log group will cause task startup to fail |
aws service-quotas list-service-quotas --service-code fargate | Check Fargate quota | New accounts may have lower quotas |
aws ecs create-express-gateway-service … | Express Mode creates the full stack in one step | Requires --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)
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
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).
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/AmazonECSTaskExecutionRolePolicycat >> ~/jenkinslab/aws-part4.env <<EOF export VPC_ID=$VPC_ID SUBNETS=$SUBNETS TASK_SG=$TASK_SG EOF source ~/jenkinslab/aws-part4.env
aws 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).
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
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
Official documentation
- AWS App Runner availability change (including the migration guide to ECS Express Mode)
- Amazon ECS Express Mode
- Amazon ECS on AWS Fargate
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.
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.
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.
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.
Module 2 · Identity from Jenkins to AWS: IAM roles, instance profiles & OIDC
- 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, throughAmazonWebServicesCredentialsBindingtheroleArnto 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.”
withCredentials. Importance:★★★★★What: overview of the five approaches (verified 2026-11)
| # | Approach | Credential source | Who requests credentials from STS | Long-term keys? | Isolation granularity |
|---|---|---|---|---|---|
| A | AWS Credentials plugin: access keys + roleArn | IAM user access keys, encrypted and stored in JENKINS_HOME | controller (the plugin calls STS in the controller JVM sts:AssumeRole, default 3600 seconds) | Yes | Per Jenkins credential (folder-level credentials can limit scope) |
| B | AWS Credentials plugin: access keys left empty + roleArn | the controller’s own default credential chain (such as the instance profile of the EC2 instance hosting the controller) | controller | None | Per Jenkins credential; but the controller’s own role must be able to AssumeRole all target roles |
| C | agent-side default credential chain: EC2 instance profile (agents launched by the EC2 Fleet / Amazon EC2 plugin) | agent host’s IMDSv2 | agent the AWS CLI / SDK on the | None | Per agent (label / node pool) — all jobs on the same agent share this role |
| D | EKS Pod Identity / IRSA: Pod agent created by the Kubernetes plugin on EKS | Pod’s service account (Pod Identity Agent or projected service account token) | agent Pod the CLI / SDK on the | None | Per Pod template’s serviceAccountName |
| E | OpenID Connect Provider plugin + AssumeRoleWithWebIdentity | JWT signed by Jenkins with its own private key for each build (default sub = job URL) | agent the CLI on the | None (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’smainbranch. But AWS fetches the public key from the issuer on every AssumeRoleWithWebIdentity call, so the issuer URL must be reachable by AWS; a local127.0.0.1:8080Jenkins 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
| Scenario | Why | Mitigation |
|---|---|---|
| This course’s local Jenkins (Docker Compose, 127.0.0.1) | Not on AWS (no instance profile), and the issuer is not publicly reachable | IAM 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 PKI | Same as above | Consider 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.
Comparison of the five identity chains
What trust policies look like (three kinds of Principal)
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.
Commands and configuration at a glance
| Command / configuration | Purpose | Key points |
|---|---|---|
aws iam create-role --assume-role-policy-document | Create deployment role and trust policy | Users/roles referenced in the trust policy must already exist |
aws iam put-role-policy | Inline permission policy | ECR push, ECS deployment,iam:PassRole (restricted to iam:PassedToService) |
[$class: 'AmazonWebServicesCredentialsBinding', credentialsId, roleArn, roleSessionName] | AWS Credentials plugin binding | injects AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY (add AWS_SESSION_TOKEN when there is a roleArn) |
withAWS(role:…, roleAccount:…, region:…) | Pipeline: AWS Steps | By 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.com | Register Jenkins issuer | When 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)
jenkins-myapp-deployer; do not copy this into production; Module 8 deletes it. Requires your administrator identity (IAM write permissions).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.jsoncat > 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 pageaws 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.
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 presentAWS_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
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.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 "*".
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.jsonThe 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
No verified video explaining the Jenkins OpenID Connect Provider plugin + AWS was found; see the storyboard below.
Official documentation
- AWS Credentials plugin · Source code and README
- OpenID Connect Provider plugin (with AWS examples)
- Pipeline: AWS Steps
- IAM: create an OIDC identity provider
- EKS Pod Identity · IRSA
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.
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.
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.
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.
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.
Module 3 · Build and push to ECR
- Explain
aws ecr get-login-passwordbehind theGetAuthorizationToken: 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_CONFIGisolation). - Create immutable tags, scan-on-push, and a repository with a lifecycle policy
myapp, and in the Jenkinsfile build, test, push and obtain digest.
What: several key facts about ECR (verified)
- One private registry per account per region:
111122223333.dkr.ecr.ca-central-1.amazonaws.com, repositoriesmyapp. - The Docker CLI does not support IAM authentication. ECR uses
GetAuthorizationTokenreturns a base64 “usernameAWS+ password,”valid for 12 hours, with a permission scope equal to the IAM principal that obtained it;aws ecr get-login-passwordonly decodes it for you. - One
docker pushcorresponding IAM actions:BatchCheckLayerAvailability→InitiateLayerUpload→UploadLayerPart→CompleteLayerUpload→PutImage. Layers that already exist are skipped (Layer already exists). - Tag mutability:
IMMUTABLEWhen set to IMMUTABLE, the same tag cannot be repointed to a new digest; a repeated push reportstag 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
| Method | Applicable to | Notes |
|---|---|---|
get-login-password | docker login | All 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 pipelines | Plugin 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’smyapp: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
latestto an immutable repository — the second push would fail, and you do not need it.
Build → push data flow
Lifetime comparison of tokens and credentials
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.
Command overview
| Command | Purpose | Key parameters |
|---|---|---|
aws ecr create-repository | Create repository | --image-tag-mutability IMMUTABLE,--image-scanning-configuration scanOnPush=true |
aws ecr put-lifecycle-policy | automatically clean up old images | --lifecycle-policy-text file://… |
aws ecr get-login-password | docker login | docker login | username 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-complete | wait for the scan to finish | afterwards describe-image-scan-findings |
aws ecr batch-delete-image | delete image | used 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)
create-repository and put-lifecycle-policy.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
+ 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...
aws ecr describe-images --repository-name myapp \ --query 'imageDetails[].[imageTags[0],imageDigest,imageScanStatus.status]' --output table
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.
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
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
Official documentation
- ECR private registry authentication (get-login-password, 12-hour token, Credential Helper)
- Image tag mutability
- Lifecycle policies
- Image scanning
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.
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.
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.
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.
Module 4 · Deploy to ECS on Fargate
- Put the task definition template in the repository, and use
jqto render the image digest,register-task-definitionto obtain a new revision. - Use
update-serviceto trigger a rolling deployment, and understandminimumHealthyPercent/maximumPercentand the deployment circuit breaker (automatic rollback). - Know
aws ecs wait services-stablein also returns successfully after a rollback completes, and you must additionally verify that the task definition of the PRIMARY deployment matchesrolloutState, otherwise Jenkins will mark the failed release green.
IMAGE_URI produced in Module 3; the ECS object model from Docker Course 4. Importance:★★★★★What: which APIs make up one ECS deployment
| Step | API / CLI | Result |
|---|---|---|
| 1 Render | (local) jq replace image, execution role | taskdef.rendered.json |
| 2 Register | ecs:RegisterTaskDefinition | new revision myapp:7 (revision numbers only increase and are never changed; old revisions remain available for rollback) |
| 3 Update service | ecs:UpdateService (requires permission on the execution role iam:PassRole) | the new deployment becomes PRIMARY; the old deployment becomes ACTIVE |
| 4 Wait | aws ecs wait services-stable (polls every 15 seconds DescribeServices, up to 40 times) | runningCount = desiredCount and only one deployment remains |
| 5 Verify | DescribeServices 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
| Method | Suitable for | Jenkins side |
|---|---|---|
| Rolling update + circuit breaker (this course) | The vast majority of stateless services | The 5 steps above |
| ECS native blue/green deployment | Needs test traffic, lifecycle hooks, fast switch-back | Set the service’s deployment strategy to blue/green; Jenkins is still only update-service |
| Express Mode | Minimal configuration is the priority | See Module 1 |
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.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
Circuit breaker state machine
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.
Command overview
| Command | Purpose | Notes |
|---|---|---|
aws ecs register-task-definition --cli-input-json file://… | Register new revision | returns 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 ARN | Deploy | Each pipeline run |
aws ecs wait services-stable | Wait | Up to about 10 minutes; exit code 255 on timeout |
aws ecs describe-services --query 'services[0].deployments' | View deployment and rolloutState | Verify PRIMARY |
aws ecs describe-tasks --query 'tasks[].stoppedReason' | See why tasks stopped | First 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)
deploy/ecs-taskdef.json to lab/myapp.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 stableTASK=$(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
"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.
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
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
Official documentation
- ECS deployment circuit breaker
- Rolling update deployment
- aws ecs wait services-stable
- Task execution role
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.
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.
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.
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.
Module 5 · Deploy to EKS and Lambda
- Explain
kubectlThe authentication chain for accessing EKS:aws eks get-token(presigned STSGetCallerIdentity) → 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-aliasfor release and canary.
What: the two layers of permissions in EKS
| Layer | Who manages it | What the Jenkins deployment role needs |
|---|---|---|
AWS API (eks:DescribeCluster) | IAM permission policy | Allow 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 policy | Access 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 | |
|---|---|---|
| Authentication | IAM deployment role → aws eks get-token | agent Pod’s service account token (in-cluster config) |
| Authorization | Access entry + access policy (namespace scope) | K8s Role + RoleBinding (myapp namespace) |
| AWS permissions (push to ECR) | same deployment role | Pod Identity / IRSA (Module 6) |
| Note | Every cluster needs its own access entry | The 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-adapterand useAWS_LWA_PORT=5000,AWS_LWA_READINESS_CHECK_PATH=/healthzto tell it the application port and readiness path (default port 8080). - Release:
update-function-code --publishGenerate an immutable version number; an aliaslivepoints to a version and can be usedrouting-configto 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
Failedstate (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.
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
Lambda versions and aliases
Animation: two deployment chains
EKS: one kubectl set image goes through authentication, authorization and rolling update; Lambda: one version release plus an alias canary.
EKS: access entry and deployment
| Command | Purpose |
|---|---|
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=myapp | Bind an access policy and restrict it to a namespace |
aws eks update-kubeconfig --name … --kubeconfig $WORKSPACE_TMP/kubeconfig | Generate a separate kubeconfig for this build |
kubectl set image / kubectl rollout status --timeout | Update the image and wait |
kubectl auth can-i update deployments -n myapp | Verify 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)
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 pushcat > 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.jsonlive: 1 90% / 2 10%.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.
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={}'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
Official documentation
- EKS access entries
- Access policy permissions
- Create a Lambda function from a container image (single architecture, 10 GB, same region)
- Lambda alias weighted routing
- AWS Lambda Web Adapter (GitHub)
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.
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.
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.
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.
Module 6 · Jenkins agents on AWS: EC2 Fleet and EKS
- 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 usecredential_source = Ec2InstanceMetadatafor role chaining. - On EKS, use the Kubernetes plugin’s Pod template +
serviceAccountName+ Pod Identity to obtain an AWS identity.
What: three plugins for running agents on AWS
| Plugin | Mechanism | Suited to | Notes (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 instances | Needs mixed instance types, Spot, warm pools, or the team already manages AMIs with ASGs | Version 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 label | Simple scenarios, when you do not want to maintain ASGs | Version 2068; the configuration includes “obtain credentials using instance profile” |
Kubernetes (kubernetes) | One Pod per build, deleted when finished | Already have an EKS platform | Version 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
| Identity | Who uses it | Permissions (listed in the plugin documentation) | Source |
|---|---|---|---|
| Fleet management identity | the plugin in the controller | EC2: 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 identity | on 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.
EC2 Fleet architecture
Pod agent identity on EKS
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.
Command overview
| Command | Purpose |
|---|---|
aws iam create-instance-profile / add-role-to-instance-profile | Create the instance profile for the agent |
aws ec2 create-launch-template … MetadataOptions | AMI, instance type, IMDSv2, user data |
aws autoscaling create-auto-scaling-group --min-size 0 | ASG (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-association | Service account ↔ IAM role |
aws eks create-addon --addon-name eks-pod-identity-agent | Install 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)
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).
ssh-keygen -t ed25519 -f jenkins-agent generated .pub). And add jenkins-agent-ec2 to the deployment role’s trust policy.- credential: AWS Credentials, ID
aws-lab-fleet, the same bootstrap key,IAM Role To Use fill inarn: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, usernamejenkins. - Manage Jenkins → Clouds → New cloud → Amazon EC2 Fleet: in AWS Credentials choose
aws-lab-fleet, Regionca-central-1, in EC2 Fleet choosejenkins-agents(ASG), Launcher choose SSH (credentialjenkins-agent-ssh), Labelaws-deploy, Max Idle Minutes Before Scaledown5, Minimum/Maximum Cluster Size0/2, Number of Executors1, Maximum Total Uses1. Exact field names follow the plugin version’s UI.
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.
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}'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'
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
No verified video specifically on the EC2 Fleet plugin was found; see the storyboard below.
Official documentation
- EC2 Fleet plugin (including the IAM permission list)
- Amazon EC2 plugin
- Kubernetes plugin
- EKS: assign an IAM role to a service account (Pod Identity association)
- EC2 instance metadata service (IMDSv2)
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.
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.
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.
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.
Module 7 · Troubleshooting cloud deployments
- 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-eventsto find failed calls, and usests decode-authorization-messageto 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.
What: fault layers
| Layer | Typical symptoms | First diagnostic command / location |
|---|---|---|
| Jenkins | Could 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 credentials | aws configure list; IMDS hop count; environment variables injected into the Pod |
| Credential chain (controller) | binding-stage timeouts,Unable to execute HTTP request … sts | whether the controller can reach STS (proxy / egress firewall); Jenkins system log |
| STS | not authorized to perform: sts:AssumeRole,AssumeRoleWithWebIdentity denials,ExpiredToken | trust 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 |
| service | ECR no basic auth credentials, ECS rollback, EKS Unauthorized | troubleshooting pages of Modules 3–5 |
| runtime | CannotPullContainerError,exec format error | describe-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 (requiressts:DecodeAuthorizationMessagepermission; recommended for administrators only). - CloudTrail: management events from the last 90 days are available for
lookup-eventslookup; failed calls carryerrorCode,userIdentity.arn; the session name in it maps to the Jenkins build number.
When: four pitfalls specific to Jenkins
- Credential scope: the credential is created in folder A, the job is in folder B, reporting “credential not found.”
- 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.
- 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. - IMDSv2 inside containers:
agent { docker { … } }steps in the container access IMDS across one extra hop; they fail when the hop count is 1.
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
Structure of a denial message
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.
Troubleshooting command box
| Command | Questions answered |
|---|---|
aws sts get-caller-identity | Who am I (no permissions needed) |
aws configure list | Where 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 … stoppedReason | Why 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)
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
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
simulate-principal-policy to confirm implicitDeny, and find the same event with CloudTrail.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.
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.
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= -f12. 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'
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
No verified video specifically explaining Jenkins → AWS permission troubleshooting was found; see the storyboard below.
Official documentation
- IAM: troubleshooting access denied errors
- CloudTrail: viewing events with the CLI
- STS DecodeAuthorizationMessage
- ECS stopped task errors
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.
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.
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.
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.
Module 8 · Cost, cleanup & self-check
- 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.jsonlogin state. - Use the interactive troubleshooting tree to review the fault paths of the whole course.
What: billing models for this course’s resources (ca-central-1, estimated 2026-11; the AWS Pricing Calculator is authoritative)
| Resource | Billing model | Approximate cost at this course’s scale | Risk of forgetting to delete |
|---|---|---|---|
| ECS cluster, task definitions | Free | 0 | None |
| Fargate task (0.25 vCPU / 0.5 GB) | Per vCPU-hour + GB-hour, billed per second | About US$0.013 per hour per task | About US$10 per month |
| Public IPv4 address (task, EC2 agent) | Per hour | About US$0.005 per hour each | About US$3.6 per month each |
| ECR storage | Per GB-month | About US$0.10 per GB-month | Low, but accumulates |
| CloudWatch Logs | Per amount written and stored | Negligible in labs | 3-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 hour | Low risk when the ASG minimum capacity is 0 |
| ALB (created by Express Mode) | Per hour + LCU | From about US$0.02–0.03 per hour | About US$20 per month |
| Lambda / function URL | Requests + GB-seconds | Within the free tier | None |
| IAM users, roles, OIDC providers | Free | 0 | Security 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, rundocker 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).
DeleteConflict. ③ “An EKS cluster costs nothing if no Pods are running”: the control plane is billed hourly.Resource dependencies and deletion order
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)
~/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 ==
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.course=jenkins-part4 (cost allocation tags must be activated in the billing settings).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.
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
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
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.
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.
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.
Command cheat sheet
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_ARN3 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
| Symptom | Most likely cause | First step |
|---|---|---|
| Unable to locate credentials | Not inside a binding block / agent has no role / IMDS hop count 1 inside a container | aws configure list |
| not authorized to perform: sts:AssumeRole | Trust policy or caller identity policy mismatch | aws iam get-role … AssumeRolePolicyDocument |
| InvalidIdentityToken: Couldn't retrieve verification key | STS cannot reach the Jenkins issuer / JWKS mismatch | curl …/oidc/.well-known/openid-configuration |
| no basic auth credentials | docker is not logged in to this registry (different DOCKER_CONFIG / different nodes) | Check the auths in config.json |
| tag invalid … repository is immutable | Repeated push of the same tag | Skip the push if it exists |
| iam:PassRole denied | Deployment role lacks PassRole or conditions do not match | simulate-principal-policy |
| Build is green but production runs the old version | services-stable still succeeds after the circuit-breaker rollback | Verify the PRIMARY task definition |
| kubectl Unauthorized | No access entry / kubectl outside the binding block | aws eks list-access-entries |
| Lambda unsupported manifest media type | Multi-manifest index (provenance) | --provenance=false --platform linux/amd64 |
| ExpiredToken | Session expires after 1 hour | Narrow 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
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.
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'
jenkins-lab-bootstrap (AssumeRole only) and jenkins-myapp-deployer (ECR push + ECS deployment + precise PassRole), and create the aws-lab-bootstrap credential in Jenkins.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' } }
}
}
}aws cloudtrail lookup-events --lookup-attributes AttributeKey=Username,AttributeValue=jenkins-myapp-<build number> \ --query 'Events[].[EventTime,EventName]' --output table
"command": ["sh","-c","exit 1"] and temporarily remove when, confirm that the build fails and prints the ECS events; then delete the branch.aws-lab-bootstrap.cleanup-part4.sh from Module 8 and verify that nothing is left over.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
Source table
| Topic | Verified conclusion | Source (date accessed) |
|---|---|---|
| Jenkins LTS | Latest 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-jdk21 | jenkins.io/changelog-stable · Installing Jenkins in Docker(2026-11-16) |
| AWS Credentials plugin | 265.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 MFA | plugins.jenkins.io/aws-credentials · GitHub source AWSCredentialsImpl.java(2026-11-16) |
| Pipeline: AWS Steps | 767.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 v2 | plugins.jenkins.io/pipeline-aws(2026-11-16) |
| OpenID Connect Provider plugin | 234.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 supported | plugins.jenkins.io/oidc-provider · README(2026-11-16) |
| EC2 Fleet plugin | 4.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 connection | plugins.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 plugin | 2068.vd80935072db_b_, requires core 2.479.3; the configuration example includes useInstanceProfileForCredentials | plugins.jenkins.io/ec2(2026-11-16) |
| Kubernetes plugin | 4560.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 namespace | plugins.jenkins.io/kubernetes(2026-11-16) |
| Amazon ECR plugin | 1.175.ve233e80e56fd,looking for a maintainer (adopt-this-plugin); docker.withRegistry(url, 'ecr:region:id') | plugins.jenkins.io/amazon-ecr(2026-11-16) |
| ECR authentication | get-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 MFA | ECR User Guide: private registry authentication(2026-11-16) |
| EKS Pod Identity | Trust 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 agent | EKS User Guide: Pod Identity(2026-11-16) |
| EKS access entries | officially described as the best way to grant access to the Kubernetes API; two authorization methods: access policies or Kubernetes groups | EKS User Guide: access entries(2026-11-16) |
| IAM OIDC provider | URL 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 required | IAM User Guide(2026-11-16) |
| Lambda container images | must 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 deleted | Lambda Developer Guide(2026-11-16) |
| Lambda Web Adapter | README Quick Start uses public.ecr.aws/awsguru/aws-lambda-adapter:1.1.0; AWS_LWA_PORT (default 8080),AWS_LWA_READINESS_CHECK_PATH | GitHub README(2026-11-16) |
| App Runner | No 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) |
| Prices | All amounts in this course are approximate estimates for ca-central-1, meant only to give a sense of scale | AWS 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 ID | Title | Channel | Module |
|---|---|---|---|
| Nv7s-N8ZxQA | Deploying a Modern Application Stack to AWS Fargate with Amazon ECS - AWS Online Tech Talks | AWS Developers | M1 |
| 7fjJqokRlKI | Serverless for container fans via Amazon ECS and AWS Lambda | Bret Fisher | M1 / M5 |
| T-fFyEsLXXE | AWS re:Invent 2024 - Unleashing the power of Amazon ECS for platform teams (SVS330) | AWS Events | M1 |
| aUjJSorBE70 | EKS Pod Identity vs IRSA | Securely Connect Kubernetes Pods to AWS Services | Containers from the Couch | M2 / M6 |
| FeUsAU_5mMM | How to Give AWS IAM Role in Jenkins | AWS IAM Role Training | Jenkins IAM Role Tutorial | Dorothy Scott | M2 |
| GtbTmvMcKRg | Amazon Elastic Container Registry (Amazon ECR) Explained | Amazon Web Services | Amazon Web Services | M3 |
| PHuKrcsAaDw | AWS re:Invent 2023 - Dive deep into Amazon ECR (CON405) | AWS Events | M3 |
| UBGeWf3PKOM | How to Push a Docker Image from Jenkins to Amazon Elastic Container Registry (ECR) | iQuant | M3 |
| Y2Ez9M7A95Y | Circuit Breakers for Amazon ECS | Containers from the Couch | M4 / M7 |
| o7s-eigrMAI | How to Setup AWS ECS Fargate with a Load Balancer | Step by Step | Be A Better Dev | M4 |
| xnHD_dCzE_E | The Complete Guide to ECS Blue/Green Deployments on AWS | AWS Developers | M4 |
| p6xDCz00TxU | AWS EKS - Create Kubernetes cluster on Amazon EKS | the easy way | TechWorld with Nana | M5 |
| s9d61eYkGzs | Amazon EKS Auto Mode | Fully Automated Kubernetes Clusters | AWS Developers | M5 |
| DCkzdsffeh0 | Jenkins World 2017: Scaling Jenkins with Kubernetes | CloudBeesTV | M6 |
| IwRa_qLywvg | How to Configure Jenkins to Use Kubernetes Pods as Build Agents | LinuxTechi | M6 |
| NyiMoyx_xj4 | Remotely access your containers on ECS using ECS Exec! | Containers from the Couch | M7 |
| Cnmejv98sv0 | Cost optimization on AWS Fargate | Containers from the Couch | M8 |
| WVGxnUEr1OU | AWS re:Invent 2023 - Boosting efficiency: How to realize 70% cost reduction with AWS Fargate -CON318 | AWS Events | M8 |
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
subformats 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 pytestruns 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,agent1taglinux docker, Gitealab/myapp, credential IDgitea-myapp/registry-creds).