Linux Hour 4: Towards the cloud platform (AWS)

Move myapp (systemd native service myapp.service + Redis protocol cache) from the first three lessons to AWS EC2: Select AMI and instance type → user data / cloud-init First Boot → IMDSv2 with Instance Profile Credentials → EBS and NVMe → SSM Access without Inbound Port → CloudWatch Agent → Patches → Serial Console Troubleshooting → Cost and Cleanup
Amazon Linux 2023(2023.12.20261112)Default Kernel 6.18cloud-init 22.2.2Region ca-central-1Verified by docs.aws.amazon.com · 2026-11-17
Overall learning objectives
  • Explain clearly the relationship between AMI, instance type, architecture (x86_64 / arm64) and use SSM Public parameters (/aws/service/ami-amazon-linux-latest/…, /aws/service/canonical/ubuntu/…) resolve the "latest" AMI instead of hardcoding the ami- ID in the script.
  • Understand the complete link of EC2 instance first startup: firmware → GRUB → kernel → systemd → cloud-init four stages → read metadata and user data through IMDSv2 (first PUT to get the token, then GET) → execute script deployment myapp + Valkey → SSM Agent registration → can log in.
  • Understand how the temporary credentials of instance profile reach the process through IMDSv2, and explain why hop limit prevents the SDK in the container from getting the credentials.
  • Distinguish between EBS volumes and Instance storage, correctly identify the NVMe device on the Nitro instance (/dev/nvme1n1 ≠ /dev/sdf in the console), complete mounting, formatting, /etc/fstab (UUID + nofail) and online expansion.
  • Use SSM Session Manager to log in and forward ports without opening any inbound ports; know the applicable scenarios and risks of EC2 Instance Connect and traditional SSH.
  • Use CloudWatch Agent to collect journald logs, file logs and memory/disk metrics; use SSM Patch Manager and AL2023 versioned repository to make controllable patches; use status check, console output, EC2 serial console to troubleshoot instances that cannot start/cannot connect; press tag Name=linux-lab Estimate the cost and clean thoroughly.

1-hour time allocation table

#TimeModuleCore contentAnimation/InteractionExperiment (AWS ca-central-1)
0Before classWarm-up and AWS preparationAWS CLI v2, Session Manager plug-in, SSO profile, IAM role + Instance profile, security group without inbound rules, budget alertEnvironment self-check listaws sts get-caller-identity
100–05AMI, instance type and AL2023AMI composition, SSM public parameters, AL2023 vs Ubuntu, instance family/generation/size, Graviton, burst instancesAMI parser: Parameters → AMI → Architecture matches instance typeParse latest AMI, query instance type, --dry-run
205–13user data, cloud-init and IMDSv2cloud-init four phases, user data only runs once, IMDSv2 token, hop limit, instance profile credentialsCore Animation: EC2 first startup process + credentials via IMDSv2 Reaching the process (including container hop limit failure)Deploy myapp + Valkey with user data, and observe IMDS
313–21EBS, instance storage and file systemgp3 / io2 / st1, instance storage life cycle, NVMe Naming, udev symbolic link, fstab, online expansionAttachVolume → NVMe hot plug → udev → mkfs → mount; instance storage is lost after stopping/startingAdd a gp3 volume to Valkey as a data disk, and then expand the capacity
421–29Access: SSM / EC2 Instance Connect / SSHSession Manager architecture, port forwarding, SSH over SSM, EIC 60-second temporary public key, EIC Endpoint, key pairData flow comparison of three access pathsZero inbound port login + port forwarding access 5000
529–37CloudWatch Agentjournald / file log, memory and disk indicators, CWAgent namespace, retention period, IAM permissionsPipeline of logs and metrics from instances to CloudWatchCollect myapp logs and memory metrics, create alarms
637–45SSM Patch ManagerAL2023 versioned repository, dnf check-release-update, patch baseline, Scan / Install, restart strategyWarehouse version timeline: Lock → Scan → UpgradeScan compliance + manual --releasever upgrade
745–54Cloud debuggingSystem / instance / Mount EBS status check, console output and screenshots, EC2 serial console, common faultsFault injection simulator: which check failed, what tool to useDeliberately write bad fstab, and then use the serial console to repair
854–60Cost, cleanup and self-testHour/GB Billing items, public network IPv4 fees, log fees, cleaning by tags, residual scanningCost Calculator + Interactive Troubleshooting TreePress Name=linux-lab for one-click cleanup
—After classCheatsheet · Comprehensive labDeliver a myapp instance with "no SSH, with data disk, monitoring and patching" from scratch, and then clean it upFinal test (12 questions)Comprehensive experiment (about 0.1–0.2 USD)

Knowledge Coverage Matrix

Target skillsM1M2M3M4M5M6M7M8Key commands/resourcesExperiment
Select AMI and instance type✓····✓·✓resolve:ssm:, describe-instance-typesM1
First boot and cloud-init·✓····✓·cloud-init status --long, /var/log/cloud-init-output.logM2
IMDSv2 and instance credentials·✓·✓✓·✓·PUT /latest/api/token, modify-instance-metadata-optionsM2
Block storage and file system··✓·✓·✓✓lsblk -o +SERIAL, ebsnvme-id, xfs_growfsM3
Secure Access (Zero Inbound)···✓·✓✓·aws ssm start-session, ec2-instance-connect sshM4
Logs and Metrics····✓·✓✓amazon-cloudwatch-agent-ctl, aws logs tailM5
Patches and Compliance✓····✓··dnf check-release-update, AWS-RunPatchBaselineM6
Cloud Troubleshooting·✓✓✓··✓✓describe-instance-status, get-console-output, serial consoleM7
Cost and cleanup✓·✓·✓··✓terminate-instances, resourcegroupstaggingapiM8

What this lesson does not cover (and where to learn)

TopicsWhy not in this lessonWhere to learn
Azure VM, managed identity, Azure Monitor AgentHas been taught in the previous lesson; this lesson uses comparison table mapping for each moduleLesson 3: Moving towards the cloud platform (Azure)
VPC design, private subnet + NAT, complete construction of VPC interface endpointsBelongs to the network architecture; this lesson uses the default VPC and only explains which endpoints are required for private instancesTerraform Lesson 4 (AWS Network)
Use Terraform / CloudFormation to code the CLI steps of this lessonFocus of this lesson Linux-side mechanism, use AWS CLI to make every step visibleTerraform 8-hour course
Configuration management (unified configuration of multiple instances)Requires Ansible / SSM State Manager System explanationAnsible 8-hour course, Lesson 5 (automated operation and maintenance)
Prometheus / Grafana monitoring systemThis course only uses the CloudWatch native solutionPrometheus & Grafana Lesson
Container (ECS / EKS) and MirroringThis lesson myapp runs as a native systemd service; only in hop limit Temporarily use the container once in the experimentDocker class, Kubernetes class
Auto Scaling, load balancing, AMI Baking Pipeline (EC2 Image Builder)Belongs to Architecture and AutomationLessons 5 and 6

How to use this courseware

10 paginations for each module
Principle · Diagram · Animation · Command · Experiment · Production case · Troubleshooting · Test · Voice · Video. First read the "principle" and "animation" to understand the mechanism, and then do the "experiment". All commands are executed in the linuxlab (user labadmin), and variables are saved in ~/linuxlab/aws directory of the local lab VM ~/linuxlab/aws/hour4.env.
Learning Progress
Test score ≥ 70% or click "Mark this module complete" to count the progress and save it in the localStorage of this browser (it will be cleared after refreshing when in privacy mode or disabling storage).
Cost awareness
This lesson only creates 1 t3.small instance, 1 8 GiB root volume and 1 10 GiB data volume, the whole process costs about 0.1–0.2 USD. Public IPv4 addresses are billed by the hour, and CloudWatch logs are billed by the GB. Clean up as per Module 8 when you're done, don't stay overnight.
Release Notes (verified 2026-11-17)Amazon Linux 2023 Currently 12th quarter release 2023.12, latest build 2023.12.20261112; AL2023 Standard support is until 2027-06-30, and the maintenance period is until 2029-06-30. Since 2026-08-17 al2023-ami-kernel-default the default kernel has been changed from 6.1 to 6.18 (version-specific AMIs for 6.1 / 6.12 / 6.18 are still available). In the AL2023 repository: systemd 252, dnf 4.14, cloud-init 22.2.2, amazon-ssm-agent 3.3.5828.0, amazon-cloudwatch-agent 1.300071.0, ec2-instance-connect 1.1, docker 25.0.16. Note: AL2023's redis6 software package has ended support on 2026-01-31. This lesson uses the same repository valkey 9.0.6 (Redis The protocol is compatible, and the service name valkey.service) is used as myapp's cache; myapp's Python client and REDIS_HOST configuration do not need to be changed. Ubuntu uses Canonical public parameters 26.04 (resolute) and 24.04 (noble). Prices are approximate ca-central-1,Subject to AWS pricing page.

Module 0 · Warm-up and AWS preparation (completed before class)

Prepare lab account, AWS CLI v2 + Session Manager plug-in, SSO Logins, IAM roles and instance profiles, zero-inbound security groups, budget alerts, and mapping Lesson 3 Azure concepts to AWS
Pre-course ≈ 15 minutesAWS CLI v2A small fee will apply
Prerequisites
  • Completed Lesson 1 to Lesson 3: know how to use shell, permissions, package management, systemd unit (myapp.service created in Lesson 2), journald, cloud-init (Lesson 3 is in used on Azure).
  • Local lab VM linuxlab (Ubuntu Server current LTS, user labadmin), working directory ~/linuxlab. All AWS CLI commands in this lesson are executed on this machine.
  • A AWS account dedicated to experiments (a sandbox account under AWS Organizations is recommended), which can be logged in using IAM Identity Center, and has at least the permissions to manage EC2, EBS, IAM roles, Systems Manager, and CloudWatch (the AdministratorAccess permission set is available for experiments; please tighten it for production).

Concept comparison with Lesson 3 (Azure)

ConceptsAzure (Lesson 3)AWS (this lesson)
Virtual MachineVM vm-linux-lab, resource group rg-linux-labEC2 instance, label Name=linux-lab (AWS There is no "resource group deletes the boundary", cleaning depends on tags)
MirrorImage URN (Publisher: Product: SKU: Version)AMI ID (different for each region) + SSM public parameters
First startup configurationcustom data → cloud-inituser data → cloud-init
Metadata serviceIMDS 169.254.169.254, request header Metadata: trueIMDS 169.254.169.254, IMDSv2 PUT first to get the token
Machine identityManaged identityIAM role + instance profile
No public IP loginAzure Bastion / az ssh vm(Entra ID)SSM Session Manager / EC2 Instance Connect Endpoint
Monitoring agentAzure Monitor Agent + DCRCloudWatch Agent + JSON configuration (can be stored in SSM parameters)
PatchAzure Update ManagerSSM Patch Manager
Startup troubleshootingStartup diagnostics + serial consoleConsole output/screenshot + EC2 serial console
Temporary diskTemporary disk (/mnt, lost on redeployment)Instance storage (missed on stop/hibernate/terminate)

Step 1: Install AWS CLI v2 with Session Manager plug-in (on linuxlab)

mkdir -p ~/linuxlab/aws && cd ~/linuxlab/aws
# AWS CLI v2 (x86_64; ARM machines replace x86_64 with aarch64)
curl -sSLo awscliv2.zip "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip"
sudo apt-get install -y unzip && unzip -q awscliv2.zip && sudo ./aws/install --update
aws --version

# Session Manager plugin (required for aws ssm start-session)
curl -sSLo session-manager-plugin.deb "https://s3.amazonaws.com/session-manager-downloads/plugin/latest/ubuntu_64bit/session-manager-plugin.deb"
sudo dpkg -i session-manager-plugin.deb
session-manager-plugin --version
rm -rf aws awscliv2.zip session-manager-plugin.deb
aws-cli/2.x.y Python/3.13.x Linux/6.x exe/x86_64.ubuntu.26
1.2.x.0

Step 2: SSO Sign in and save variables

aws configure sso --profile linux-lab      # Fill in the SSO start URL, region, account, and permission set as prompted; fill in ca-central-1 for the default region
aws sso login --profile linux-lab
cat > ~/linuxlab/aws/hour4.env <<'EOF'
export AWS_PROFILE=linux-lab
export AWS_REGION=ca-central-1
export LAB=linux-lab
export ROLE=linux-lab-ec2-role
export IPROFILE=linux-lab-ec2-profile
export SG_NAME=linux-lab-sg
EOF
source ~/linuxlab/aws/hour4.env
aws sts get-caller-identity
{
    "UserId": "AROAEXAMPLEID:labadmin",
    "Account": "111122223333",
    "Arn": "arn:aws:sts::111122223333:assumed-role/AWSReservedSSO_AdministratorAccess_0123abcd/labadmin"
}

Step 3: IAM role + instance profile (the instance's "managed identity")

Credentials are required for both the SSM Agent and the CloudWatch Agent on the instance. We not put any Access Key on the instance, but let EC2 hand the role's temporary credentials to the instance via IMDS (Module 2's Core Animation will demonstrate this in detail).

cat > trust-ec2.json <<'EOF'
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": { "Service": "ec2.amazonaws.com" },
    "Action": "sts:AssumeRole"
  }]
}
EOF
aws iam create-role --role-name $ROLE --assume-role-policy-document file://trust-ec2.json \
  --tags Key=Name,Value=$LAB
aws iam attach-role-policy --role-name $ROLE --policy-arn arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore
aws iam attach-role-policy --role-name $ROLE --policy-arn arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy
aws iam create-instance-profile --instance-profile-name $IPROFILE
aws iam add-role-to-instance-profile --instance-profile-name $IPROFILE --role-name $ROLE
aws iam get-instance-profile --instance-profile-name $IPROFILE --query 'InstanceProfile.Roles[].RoleName'
[
    "linux-lab-ec2-role"
]
Role ≠ Instance configuration fileIAM role is "permission + trust policy"; instance configuration file is the "container" that installs the role into EC2, and only one role can be placed in one configuration file. When the console creates an EC2 role, it will automatically create a configuration file with the same name. The CLI requires two manual steps. IAM is a global service. It may take a few seconds for the newly created configuration file to be visible in EC2 (eventual consistency). Immediately run-instances occasionally reports Invalid IAM Instance Profile name. Just wait 10 seconds and try again.

Step 4: Security group with zero inbound rules (default VPC)

export VPC_ID=$(aws ec2 describe-vpcs --filters Name=is-default,Values=true --query 'Vpcs[0].VpcId' --output text)
export SG_ID=$(aws ec2 create-security-group --group-name $SG_NAME --description "linux-lab: no inbound" \
  --vpc-id $VPC_ID --tag-specifications "ResourceType=security-group,Tags=[{Key=Name,Value=$LAB}]" \
  --query GroupId --output text)
echo "export VPC_ID=$VPC_ID SG_ID=$SG_ID" >> ~/linuxlab/aws/hour4.env
aws ec2 describe-security-groups --group-ids $SG_ID --query 'SecurityGroups[0].{in:IpPermissions,out:IpPermissionsEgress[0].IpRanges}'
{
    "in": [],
    "out": [ { "CidrIp": "0.0.0.0/0" } ]
}

Inbound is empty, outbound is all allowed: SSM Agent actively connects outbound to port 443, so no inbound rules are required. The subnet of the default VPC will allocate public IPv4 to the instance (for outbound access to SSM and software repository), which will incur public IPv4 charges (about 0.005 USD/hour). For accounts that do not have a default VPC, please refer to Terraform Lesson 4 to build your own VPC.

Step 5: Budget alert (strongly recommended)

ACCOUNT=$(aws sts get-caller-identity --query Account --output text)
aws budgets create-budget --account-id $ACCOUNT \
  --budget '{"BudgetName":"linux-lab-5usd","BudgetLimit":{"Amount":"5","Unit":"USD"},"TimeUnit":"MONTHLY","BudgetType":"COST"}' \
  --notifications-with-subscribers '[{"Notification":{"NotificationType":"ACTUAL","ComparisonOperator":"GREATER_THAN","Threshold":80},"Subscribers":[{"SubscriptionType":"EMAIL","Address":"you@example.com"}]}]'

Pre-course self-check list






Security reminderDon't open it to the security group for "convenience" 22/tcp 0.0.0.0/0. Scanners on the internet will start brute force attempts to SSH within minutes. The default access method for this lesson is Session Manager (zero inbound port). SSH is only available in Module 4 as a control and is only open to the prefix list of EC2 Instance Connect.

Module 1 · Linux on AWS: AMIs, Instance Types, and Amazon Linux 2023

00:00 – 05:00 · One EC2 = AMI (disk snapshot + startup properties) × instance type (CPU architecture, memory, network, storage) × startup parameters
5 minutesAL2023 2023.12Default kernel 6.18★★★★
Learning objectives
  • Tell me what the AMI contains (root volume snapshot, block device mapping, schema, boot mode, properties such as ImdsSupport) and why the AMI ID is different in each region.
  • Use SSM public parameters to resolve the latest AL2023 and Ubuntu AMI, and use resolve:ssm: to directly reference them in run-instances.
  • Understand the instance type names (t3.small, m7g.large, c7i.xlarge) and select according to architecture and workload; tell the main differences between AL2023 and Ubuntu in Linux management.
Prerequisite knowledge:Package management and kernel concepts in Lesson 1, Azure image URN in Lesson 3. Importance:★★★★ (choose the wrong AMI or architecture, all the rest will be in vain)

What: What are AMI and instance types

AMI (Amazon Machine Image) is a template for launching an instance, which is essentially: one or more EBS snapshots (root volume, and optional data volume) + Block device mapping (snapshot → /dev/xvda and other device names, volume type, size) + Startup properties (architecture x86_64/arm64, boot mode uefi/legacy-bios/uefi-preferred, ENA support, ImdsSupport) + Launch permissions (public/shared to which accounts). AMI is a regional resource: the same AL2023 version has two different ami- IDs in ca-central-1 and us-east-1.

Instance type determines the hardware shape: vCPU number and architecture (Intel/AMD is x86_64, Graviton is arm64), memory, network bandwidth, EBS bandwidth, and whether to have instance storage. Name rule: family + generation + processor/feature + . + size, for example m7g.large = general purpose m, 7th generation, g = Graviton (arm64), large = 2 vCPU / 8 GiB.

Why: Why can't the AMI ID be hardcoded

  • AMIs are constantly updated (AL2023 releases new builds almost every week, and Ubuntu also refreshes regularly), hardcoded IDs expire quickly, and new instances are missing dozens of security updates as soon as they are launched.
  • ID varies from region to region, and the script will become invalid when changing regions.
  • Both AWS and Canonical publish the parameters of the "latest AMI" in the public namespace of the SSM Parameter Store, which can be read by any account. This is an officially recommended practice.

How: SSM public parameters (verified)

Release versionParameter pathDescription
AL2023 Standard Edition/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64arm64 Replace the end with arm64; default kernel 2026-08-17 Starting from 6.18
AL2023 minimal version/aws/service/ami-amazon-linux-latest/al2023-ami-minimal-kernel-default-x86_64Fewer packages; not pre-installed Many tools other than SSM Agent, EC2 Instance Connect need to be installed manually
AL2023 fixed kernel…/al2023-ami-kernel-6.1-x86_64, …-6.12-…, …-6.18-…Use when the kernel line needs to be fixed (such as third-party kernel modules, FIPS)
Ubuntu 26.04 LTS/aws/service/canonical/ubuntu/server/26.04/stable/current/amd64/hvm/ebs-gp3/ami-idCanonical release; 26.04 can also write the code name resolute; arm64 replace amd64 with arm64
Ubuntu 24.04 LTS/aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-idCode name noble; Canonical account ID 099720109477

Two usages: first aws ssm get-parameters to take out the ID and then pass it in; or directly --image-id resolve:ssm:/aws/service/…, resolved by EC2 at the moment of startup (the ImageId of the instance records the resolved real ID).

Linux differences between AL2023 and Ubuntu on EC2

Amazon Linux 2023Ubuntu Server 26.04 / 24.04
Default userec2-userubuntu
Package managementdnf 4.14 (RPM); Versioned repository, locked to the repository version when AMI was built by default (module 6)apt (deb822 .sources); unattended-upgrades turns on security updates by default
Mandatory access controlSELinux (default permissive)AppArmor
Logonly journald (rsyslog not pre-installed)journald + rsyslog
SSM AgentRPM Pre-installed (amazon-ssm-agent.service)snap pre-installed (snap.amazon-ssm-agent.amazon-ssm-agent.service); the pre-installed list of AWS documents is written to 24.04 / 25.04, 26.04 please use snap list Self-check
Support periodStandard support until 2027-06-30, maintenance until 2029-06-30LTS standard support for 5 years (Ubuntu Pro extended)
Root file systemXFSext4

When: How to choose the instance type

ScenarioRecommendedReason
Experimental, low-load Web (this lesson myapp)t3.small (x86_64, 2 vCPU / 2 GiB) or t4g.small (arm64)Burst type, cheap; CPU points system, t3/t4g default unlimited mode, continuous high CPU Additional charges will apply
General-purpose services with stable loadm7i / m7g / m8g and other general-purpose servicesare not subject to CPU credit restrictions
CPU-intensive (compilation, encoding)c7i / c7gLess memory per vCPU, high cost performance
In-memory database, cacher7i / r7g8 GiB per vCPU
Requires local high-speed temporary diskWith d suffix, such as m7gd, c6id Comes with NVMe Instance storage (Module 3)
Common misunderstandings① "AMI is an ISO" - No, AMI is a disk snapshot of the installed system. The root volume is created directly from the snapshot during startup, without an installation process. ② "arm64 AMI can run on any instance" - the AMI architecture must be consistent with the instance type architecture, otherwise run-instances report directly InvalidParameterValue. ③ "The new AMI will automatically update my instances" - No, running instances will only need to be patched (module 6) or replaced on their own. ④ "If the t3 instance is cheap, keep using it" - when the CPU is 100% for a long time, the unlimited mode will be charged extra per vCPU hour, and the cost may exceed the m series of the same size.

Architecture diagram: what the AMI consists of and how instances are created from it

AMI ami-0abc… (region: ca-central-1) EBS snapshot snap-… (root volume content)Kernel, systemd, cloud-init, SSM Agent... Block device mapping/dev/xvda ← snap-…, gp3, 8 GiB Startup propertiesarm64 | x86_64 · uefi · ENA · ImdsSupport=v2.0 Startup permissions: public / designated account RunInstances Instance type t3.small 2 vCPU(x86_64)2 GiB memoryNitro · ENA · NVMeEBS optimizationCPU credits (unlimited)Architecture must be consistent with AMI Instance i-0123… Root volume vol-… (created from snapshot)→ /dev/nvme0n1ENI + private/public IPInstance profile (role)user data · TagIMDS option (v2 / hop=2)
Figure 1-1 AMI = snapshot + mapping + attributes; instance type provides hardware; RunInstances combines the two with network, role, user data into one instance

Flow chart: using SSM Public parameter resolution "Latest AMI"

AWS / CanonicalUpdated after releasing new AMIThe value of the public parameter SSM Parameter Store/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64 resolve:ssm:…RunInstances is resolved by EC2 to ami-… InstanceImageId = real IDIt will not change after that Production suggestion: parse once in CI and record the AMI ID (reproducible), and then replace it on a rolling basis; in the experiment, just resolve:ssm directly
Figure 1-2 Parsing chain for "latest AMI": parameter values are updated with releases, and their AMIs are fixed after instance creation

Interaction: AMI parser and architecture match check

Select a release, architecture, and instance type, and play. The animation is demonstrated in true order: Spelling out parameter names → SSM GetParameters → EC2 DescribeImages Reading AMI properties → DescribeInstanceTypes Reading supported architectures → RunInstances Verification. When the architecture is inconsistent, you will see the actual error type of RunInstances.

Parameter name/aws/service/… SSMGetParameters AMI attributeDescribeImages Instance typeDescribeInstanceTypes RunInstancesVerify and start

Core Command

CommandFunctionKey parameters/description
aws ssm get-parameters --names …Read the latest AMI ID in public parameters--query 'Parameters[0].Value'
aws ssm get-parameters-by-path --path /aws/service/ami-amazon-linux-latestList all Amazon Linux parametersOnly return the next level of the path, combined with --query filtering
aws ec2 describe-images --image-ids …View AMI name, architecture, startup mode, IMDS supportArchitecture, BootMode, ImdsSupport
aws ec2 describe-instance-typesInstance type vCPU, memory, architecture, network--filters Name=processor-info.supported-architecture,Values=arm64
aws ec2 describe-instance-type-offeringsWhether an instance type is provided in an availability zone--location-type availability-zone
aws ec2 run-instances --dry-runOnly verify permissions and parameters, do not create resourcesReturn DryRunOperation error code on success

Parse the latest AMI of AL2023 and Ubuntu

source ~/linuxlab/aws/hour4.env
aws ssm get-parameters --names \
  /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64 \
  /aws/service/canonical/ubuntu/server/26.04/stable/current/amd64/hvm/ebs-gp3/ami-id \
  /aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id \
  --query 'Parameters[].[Name,Value,LastModifiedDate]' --output table
-----------------------------------------------------------------------------------------------
|                                        GetParameters                                        |
+---------------------------------------------------------------------+------------------------+
|  /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64 | ami-0a1b2c3d4e5f60718 | 2026-11-13T… |
|  /aws/service/canonical/ubuntu/server/26.04/stable/current/amd64/…    | ami-0123456789abcdef0 | 2026-11-…    |
|  /aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/…    | ami-0fedcba9876543210 | 2026-11-…    |
+---------------------------------------------------------------------+------------------------+

View AMI properties (note ImdsSupport and BootMode)

AMI=$(aws ssm get-parameters --names /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64 --query 'Parameters[0].Value' --output text)
aws ec2 describe-images --image-ids $AMI \
  --query 'Images[0].{Name:Name,Arch:Architecture,Boot:BootMode,Imds:ImdsSupport,Root:BlockDeviceMappings[0].Ebs.[VolumeSize,VolumeType]}'
{
    "Name": "al2023-ami-2023.12.20261112.0-kernel-6.18-x86_64",
    "Arch": "x86_64",
    "Boot": "uefi-preferred",
    "Imds": "v2.0",
    "Root": [ 8, "gp3" ]
}

How to verify: Imds is v2.0 which means that the instance launched with it defaults to "IMDSv2 + hop limit 2 only" (module 2). Common mistakes: Misspelled parameter names will appear in the InvalidParameters list instead of exiting with an error. The script must check whether the return value is empty. Production use: Use resolve:ssm: in Launch Template, or write version records after parsing in CI.

Select instance type: architecture, memory and availability zone

aws ec2 describe-instance-types --instance-types t3.small t4g.small m7i.large m7g.large \
  --query 'InstanceTypes[].[InstanceType,ProcessorInfo.SupportedArchitectures[0],VCpuInfo.DefaultVCpus,MemoryInfo.SizeInMiB,BurstablePerformanceSupported]' \
  --output table
aws ec2 describe-instance-type-offerings --location-type availability-zone \
  --filters Name=instance-type,Values=t3.small --query 'InstanceTypeOfferings[].Location'
|  t3.small   |  x86_64 |  2 |  2048 |  True  |
|  t4g.small  |  arm64  |  2 |  2048 |  True  |
|  m7i.large  |  x86_64 |  2 |  8192 |  False |
|  m7g.large  |  arm64  |  2 |  8192 |  False |
[ "ca-central-1a", "ca-central-1b", "ca-central-1d" ]

Experiment 1: Parse AMI, compare releases, and use dry-run to verify startup parameters (about 4 minutes, cost 0)

Save AMI parameter names to variable files(Subsequent modules use it):
cd ~/linuxlab/aws && source hour4.env
cat >> hour4.env <<'EOF'
export AL2023_PARAM=/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64
export UBUNTU_PARAM=/aws/service/canonical/ubuntu/server/26.04/stable/current/amd64/hvm/ebs-gp3/ami-id
export ITYPE=t3.small
EOF
source hour4.env
aws ssm get-parameters --names $AL2023_PARAM $UBUNTU_PARAM --query 'Parameters[].Value' --output text
List all AL2023 related parameters, experience the combination of "standard/minimum, default kernel/fixed kernel, x86_64/arm64":
aws ssm get-parameters-by-path --path /aws/service/ami-amazon-linux-latest \
  --query "Parameters[?contains(Name,'al2023')].Name" --output text | tr '\t' '\n' | sort
/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-6.1-arm64
/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-6.1-x86_64
/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-6.12-x86_64
/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-6.18-x86_64
/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-arm64
/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64
/aws/service/ami-amazon-linux-latest/al2023-ami-minimal-kernel-default-x86_64
…
Use dry-run Verify: Permissions, AMI, instance type, security group, instance profile are all available (no instance will be created):
aws ec2 run-instances --dry-run --image-id resolve:ssm:$AL2023_PARAM --instance-type $ITYPE \
  --security-group-ids $SG_ID --iam-instance-profile Name=$IPROFILE 2>&1 | tail -1
An error occurred (DryRunOperation) when calling the RunInstances operation: Request would have succeeded, but DryRun flag is set.
Intentional architecture mismatch: x86_64 AMI + Graviton instance type:
aws ec2 run-instances --dry-run --image-id resolve:ssm:$AL2023_PARAM --instance-type t4g.small \
  --security-group-ids $SG_ID 2>&1 | tail -1
An error occurred (InvalidParameterValue) when calling the RunInstances operation: The architecture 'arm64' of the specified instance type does not match the architecture 'x86_64' of the specified AMI. …

Fix: Change the parameter to al2023-ami-kernel-default-arm64. Graviton instances in ca-central-1 are typically about 20% cheaper than x86 of the same size, but make sure your software has an arm64 build (Python-only myapp has no problem).

Cleaning: This experiment did not create resources and does not require cleaning. Keep the new variables in hour4.env .

Case 1: The hard-coded AMI in the Launch Template causes the new instance to lack patches

Problem: The Auto Scaling group's Launch Template hardcoded the AMI ID 8 months ago. Every time the capacity is expanded, a system with a known CVE is started, and security scans continue to generate alarms. Method: Change the ImageId of Launch Template to resolve:ssm:/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64, and trigger an instance refresh (Instance Refresh) once a week; or use EC2 Image Builder to bake your own based on the latest AL2023 AMI, and then write your own SSM parameters. Limitations: Fully automatic "up-to-date" will make instance versions in the same group inconsistent. When troubleshooting, you must first look at ImageId; environments that need to be reproducible should be locked to the baked AMI.

Case 2: Migrate to Graviton to save costs

Problem: A group of m6i.large web servers have low CPU utilization and high cost pressure. Method: First use arm64 AMI on m7g.large to run the same user data for stress testing; there are precompiled binaries (such as some Python wheels and monitoring agents) in the dependencies to confirm the arm64 version one by one; after passing the test, switch to Launch Template. Limitations: Third-party commercial software may not have arm64 versions; the AMI architecture and instance type must be switched at the same time.

Case 3: Driver problems caused by kernel line changes

Problem: Newly started AL2023 instances after 2026-08-17 run the 6.18 kernel by default. The kernel module of a certain security agent only supports 6.1, causing the agent to fail to load. Method: Switch to the al2023-ami-kernel-6.1-x86_64 parameter-fixed kernel line in the short term; and contact the manufacturer to obtain the new version. Limitations: Fixed that old kernel lines will miss the performance and hardware support of new kernels and should set a deadline for returning to the default kernel.

Common errors and solutions

InvalidParameterValue: The architecture 'arm64' of the specified instance type does not match the architecture 'x86_64' of the specified AMI

Cause: The AMI is inconsistent with the instance type schema.

aws ec2 describe-images --image-ids $AMI --query 'Images[0].Architecture'
aws ec2 describe-instance-types --instance-types t4g.small --query 'InstanceTypes[0].ProcessorInfo.SupportedArchitectures'

Fix: Change the parameters of the corresponding architecture (…-arm64 or Ubuntu's arm64), or change the instance type.

ParameterNotFound / InvalidParameters: ["/aws/service/canonical/ubuntu/server/26.04/stable/current/amd64/hvm/ebs-gp2/ami-id"]

Cause:The parameter path is misspelled. Ubuntu 23.10 and later only release ebs-gp3 volume type parameters; arm64 is written as aarch64; or an unreleased version number is used.

aws ssm get-parameters-by-path --path /aws/service/canonical/ubuntu/server/26.04/stable/current/amd64/hvm --recursive --query 'Parameters[].Name'

Fix: Corrected according to the real path listed above.

Unsupported: Your requested instance type (m7i.large) is not supported in your requested Availability Zone (ca-central-1d)

Reason: Not all instance types are available in all Availability Zones (the default subnet has one in each Availability Zone).

aws ec2 describe-instance-type-offerings --location-type availability-zone --filters Name=instance-type,Values=m7i.large --query 'InstanceTypeOfferings[].Location'

Fix: Use --subnet-id to specify the subnet in the Availability Zone that offers this type.

InsufficientInstanceCapacity: We currently do not have sufficient t3.small capacity in the Availability Zone you requested

Reason: The Availability Zone does not have enough capacity at the moment (this also happens with On-Demand instances, especially with new/large instance types). Fix: Change the availability zone, change to the same instance type (such as t3a.small), or try again later; the Auto Scaling group in production is configured with multiple instance types and multiple availability zones.

VcpuLimitExceeded: You have requested more vCPU capacity than your current vCPU limit of 5 allows

Reason: The new account has a lower On-Demand instance vCPU quota (calculated by instance family grouping). Fix: Check "Running On-Demand Standard (A, C, D, H, I, M, R, T, Z) instances" in Service Quotas and apply for an increase or terminate unused instances first.

aws service-quotas get-service-quota --service-code ec2 --quota-code L-1216C47A --query 'Quota.Value'
Command line operation questions
1. Write a command to get the ID and name of the latest AL2023 arm64 standard AMI of ca-central-1.
AMI=$(aws ssm get-parameters --region ca-central-1 --names /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-arm64 --query 'Parameters[0].Value' --output text)
aws ec2 describe-images --region ca-central-1 --image-ids $AMI --query 'Images[0].[ImageId,Name]' --output text
2. Find all current-generation instance types with 2 vCPUs, memory ≥ 4 GiB, and arm64 support.
aws ec2 describe-instance-types \
  --filters Name=processor-info.supported-architecture,Values=arm64 Name=vcpu-info.default-vcpus,Values=2 Name=current-generation,Values=true \
  --query 'InstanceTypes[?MemoryInfo.SizeInMiB>=`4096`].InstanceType' --output text
Scenario Analysis Question
The team wants all new instances to "always use the latest AL2023", and also requires that the system version of a certain instance can be accurately reproduced when a problem occurs. How to balance it?

① Use resolve:ssm: to obtain the latest AMI at startup. The instance's ImageId will record the parsed real ID, which can be found through describe-instances; ② In user data, combine /etc/amazon-linux-release with rpm -q system-release writes logs or tags; ③ The versioned repository of AL2023 is locked to the corresponding version of the AMI by default, so the software package version obtained by "same AMI + same user data" is the same; ④ In the production environment, it is recommended that Image Builder bakes its own AMI, writes the AMI ID into its own SSM parameters and makes version records, and changes are subject to approval.

Verified teaching video

▶
What is Amazon Linux 2023 | Amazon Web Services — Amazon Web Services
English · AWS official channel · AL2023 positioning, support cycle and the concept of versioned repository
▶
AWS re:Invent 2025 - Amazon Linux: latest features and AWS optimizations (CMP303) — AWS Events
English · Conference speech · Amazon Linux’s latest features and optimization for AWS (specific version information is verified in this lesson 2026-11 Facts shall prevail)
▶
UPDATED - Amazon/AWS EC2 Basics | Create an EC2 Instance | AWS Tutorials for Beginners — Tiny Technical Tutorials
English · Console operation demonstration · Select AMI, instance type, key pair and security group (this lesson uses CLI + zero inbound security group)

Official document

Video storyboard script (about 75 seconds)

This courseware cannot directly generate video/MP3. Storyboards and explanation scripts have been provided, which can be generated by video tools.

Shot 1 · 0–15s
Screen: An AMI box is opened, inside are three cards: "Snapshot", "Block Device Mapping" and "Architecture/Boot Mode/IMDS Attributes".
Narration: AMI is not an installation CD, but a disk snapshot of the installed system, plus a set of startup attributes.
Shot 2 · 15–35s
Screen: The SSM parameter path is lit segment by segment, with an arrow pointing to an ami-ID, which is continuously replaced with a new ID along the timeline.
Narration: AWS and Canonical release the latest AMI in public parameters. The script only references the parameter name and parses it at startup.
Shot 3 · 35–55s
Screen: The x86_64 AMI puzzle piece tries to insert into the arm64 Graviton instance slot, is bounced, and InvalidParameterValue appears.
Narration: The AMI architecture must be consistent with the instance type, and Graviton requires an arm64 image.
Shots 4 · 55–75s
Screenshot: AL2023 vs. Ubuntu side-by-side: ec2-user vs. ubuntu, dnf vs. apt, SELinux vs. AppArmor, versioned repositories vs. unattended-upgrades.
Narration: Both distributions can be used, but the user name, package management and update methods are different, and the scripts must be processed separately.
Or score ≥ 70% on the Quiz

Module 2 · user data, cloud-init and IMDSv2

05:00 – 13:00 · When the instance is powered on for the first time, who goes where to get the configuration? How did the role credentials appear in the instance "out of thin air"?
8 minutescloud-init 22.2.2(AL2023)IMDSv2 required · hop limit 2★★★★★
Learning objectives
  • Name the stages of EC2 first boot in order: firmware → GRUB → kernel → systemd → cloud-init's local / network / config / final four stages → agent registration → can log in and know where the logs of each stage are.
  • Write reusable user data and use it to deploy myapp (myapp.service, user myapp, /opt/myapp, /etc/myapp/myapp.env, port 5000) and Valkey to AL2023.
  • Use IMDSv2 (PUT /latest/api/token → with token GET) to read metadata and instance configuration file credentials, explain the role of HttpTokens, HttpPutResponseHopLimit, and diagnose "credentials not available in the container".
Prerequisite knowledge:Lesson 2 systemd unit and journald; Lesson 3 Azure custom data and cloud-init. Importance:★★★★★ (the foundation of Linux automation and security on the cloud)

What: the relationship between user data, cloud-init and IMDS

  • user data: A piece of data that is included when the instance is launched (original size limit 16 KB, transmitted as base64 in the API), which can be a shell script (starting with #!), #cloud-config YAML, or a MIME multipart combination.
  • IMDS (Instance Metadata Service): A link-local HTTP service that each instance can access 169.254.169.254 (Nitro instances are also available in IPv6 subnets [fd00:ec2::254]), providing instance ID, network, user data, role temporary credentials, etc.
  • cloud-init: Initializer preinstalled in the AMI (22.2.2 for AL2023). Access IMDS through Ec2 data source when booting, retrieve metadata and user data, and then execute in stages: set host name, expand root partition, inject SSH public key, execute user data script...

Why: Why should you understand these mechanisms

  • Wrong writing of user data will not cause RunInstances Failure - The instance is "running normally", but the application is not installed. You must know to check /var/log/cloud-init-output.log and cloud-init status.
  • IMDS is a classic target for SSRF attacks: if a web application can be induced to request http://169.254.169.254/…, IMDSv1 will spit out the role credentials directly. IMDSv2's PUT + token + reject X-Forwarded-For + hop limit is designed for this.
  • There should be no long-term Access Key on the instance; all AWS SDK, CLI, SSM Agent, CloudWatch Agent obtain automatic rotation temporary credentials for instance profiles through IMDS.

How: The four phases of cloud-init (systemd unit name for AL2023)

Phasessystemd unitWhat to doWith IMDS Interaction
Localcloud-init-local.serviceRun when the network is not ready: identify the data source and generate network configurationThe Ec2 data source will temporarily establish a DHCP connection, PUT the token and then read the metadata (including network information)
Networkcloud-init.serviceThe network is ready: run cloud_init_modules (growpart, resizefs, set hostname, user and SSH public key, etc.)Read user data, public-keys
Configcloud-config.serviceRun cloud_config_modules (such as runcmd Write the script to be executed, time zone, mount)—
Finalcloud-final.serviceRun cloud_final_modules: install software package, execute user data script (scripts-user), runcmd, final messageThe script needs to get its own token when calling IMDS

Newer cloud-init (Ubuntu 26.04, etc.) renames the Network stage unit to cloud-init-network.service, based on the actual output of systemctl list-units 'cloud*'.

  • Run only once: User data in the form of a shell script is executed only once per instance by default (first startup). cloud-init logs "executed" with a semaphore file under /var/lib/cloud/instances//sem/. Modifying user data requires stopping the instance first, and restarting it after modification will not re-execute the script (unless you use the #cloud-config's cloud_final_modules frequency configuration or the per-boot script in MIME, or manually cloud-init clean).
  • Run as root without sudo or loading the interactive shell environment; commands in the script must use absolute paths or set PATH at the beginning.
  • Output: The stdout/stderr of the script is written to /var/log/cloud-init-output.log; cloud-init's own log is in /var/log/cloud-init.log; a copy of the script is in /var/lib/cloud/instance/scripts/part-001, and the original user data is in /var/lib/cloud/instance/user-data.txt.

How: IMDSv2 session and instance profile credentials (verified)

  1. PUT http://169.254.169.254/latest/api/token, request header X-aws-ec2-metadata-token-ttl-seconds: 21600(1 second – 6 hours) → Returns the token. The token is only valid in this instance.
  2. Subsequent GET requests carry X-aws-ec2-metadata-token: . HttpTokens=required, if there is no token or the token expires, 401 Unauthorized will be returned.
  3. PUT requests with X-Forwarded-For header will be rejected (to prevent exploitation via reverse proxy).
  4. hop limit: PUT's response is sent with IP TTL = HttpPutResponseHopLimit. The default is 1; but when starting with an AMI (AL2023 is AL2023) using ImdsSupport: v2.0, it defaults to only IMDSv2 + hop limit 2, so that containers in the Docker bridge network can also get the token.
  5. Credentials: GET /latest/meta-data/iam/security-credentials/ returns the role name; then GET .../security-credentials/ returns AccessKeyId / SecretAccessKey / Token / Expiration. AWS provides new credentials at least 5 minutes before expiration, and the SDK automatically refreshes them.
IMDSv1IMDSv2Azure IMDS (Lesson 3)
Request methodDirect GETPUT first to get the token, GET with the tokenGET + Metadata: true Header
Anti-SSRFWeak (any vulnerability that can send GET can obtain credentials)Strong (requires PUT + custom header, rejects X-Forwarded-For, hop limit)Medium (requires custom header, rejects Default
Credential path/latest/meta-data/iam/security-credentials/<role>/metadata/identity/oauth2/token (managed identity)
AL2023 defaultDisabledRequired, hop limit 2—

When: Choose shell script or #cloud-config

RequiredRecommended
A small number of commands, the team knows bashshell script (used in this lesson), starting with set -euxo pipefail
Declarative: user, file, software package, mount#cloud-config(users, write_files, packages, mounts, runcmd)
Exceeds 16 KB or contains large filesuser data only bootstrapping: download the installation package from S3 / CodeArtifact, or bake it into your own AMI
Long-term consistency of multiple instancesuser data only installs the agent, and leaves the configuration to SSM State Manager / Ansible (Lesson 5)
Common misunderstandings① "Modifying user data will take effect after restarting" - No, by default it will only be executed on the first startup. ② "User data is confidential" - No, any process that can access IMDS and anyone with ec2:DescribeInstanceAttribute permissions can read it. Don't put the password (use Secrets Manager / SSM SecureString). ③ "The larger the hop limit, the more convenient it is" - hop limit 2 allows all containers on the instance to obtain the credentials of the instance role; on multi-tenant nodes such as EKS, it should usually be set to 1 and use Pod-level identities instead. ④ "IMDS can only be accessed through IPv4" - Nitro instances can also be used in IPv6 subnetsAll containerscan get the credentials for the instance role; on multi-tenant nodes such as EKS it should usually be set to 1 and use pod-level identities instead. ④ "IMDS is only accessible via IPv4" - Nitro instances are also available in IPv6 subnets [fd00:ec2::254] (need to be enabled HttpProtocolIpv6).

Architecture diagram: interaction between cloud-init and IMDS during first startup

EC2 Instance (Nitro) · AL2023 UEFI Firmware GRUB2 Kernel 6.18+ initramfs systemd(PID 1) localIdentify Data SourceNetwork Configuration networkgrowpartHost name/SSH public key configruncmd/mountsTime zone, etc. finalscripts-userExecute user data user data script resultsvalkey.service · myapp.service/opt/myapp · /etc/myapp/myapp.envLog: /var/log/cloud-init-output.log amazon-ssm-agentRegistered to SSM with instance role credentialsOutbound 443 → ssm / ssmmessages /ec2messages IMDS 169.254.169.254 PUT /latest/api/tokenGET /latest/meta-data/…GET /latest/user-dataGET …/public-keys/0/openssh-keyGET …/iam/security-credentials/HttpTokens = requiredHopLimit = 2InstanceMetadataTags (Powered by Nitro The card is provided locally) Local phase: PUT token + read metadata Credentials
Figure 2-1 cloud-init obtains metadata through IMDSv2 in the local phase; the final phase executes user data; SSM Agent obtains metadata from IMDS Obtain role credentials and then register externally

Flowchart: Instance profile credentials arrive at the process (host vs container) via IMDSv2

Host processaws CLI / SSM Agent Container processdocker bridge Network1 more hop (docker0 + NAT) ① PUT tokenTTL 21600 secondsResponse IP TTL =hop limit ② GET role name③ GET credentials JSONAccessKeyId / TokenExpiration ④ SDK cache and signSigV4 calls AWS APIAutomatically refresh before expiration(new credentials available ≥5 minutes ago) hop limit = 1: The PUT response received by the container is discarded when the TTL is reset to zero when forwarded by the host → Token request times out → SDK cannot find the credentials hop limit = 2 (AL2023 default): the container can get the token; when isolation is required, set it to 1 or let the container use an independent identity other than --network host
Figure 2-2 Credential chain: token → role name → temporary credentials → SDK cache; hop limit determines how many network hops the PUT response can pass through

Core Animation A: The whole process of EC2 first startup (each stage of cloud-init is configured through IMDSv2)

Step by step demonstration of real components and logs. If you check "user data has errors", you can see that the instance is still "running" and the status check has passed, but the application has not started - this is the most common first-time startup failure on the cloud.

UEFINitro Firmware GRUB2BLS Entry KernelNVMe/ENA Driver systemdPID 1 ci-localData Source Ec2 ci-networkgrowpart/ssh ci-configruncmd/mounts ci-finalscripts-user SSM AgentRegister LoginOnline / 2/2 Check IMDS 169.254.169.254Waiting for request...

Core Animation B: How instance profile credentials reach the process via IMDSv2

Select the caller location, hop limit and HttpTokens, and observe whether the PUT response reaches the caller, how the SDK gets the credentials, and when it will fall back to IMDSv1.

CallerHost process Network path0 Jump forward IMDSToken/Metadata SDK Credential CachingExpiration STSGetCallerIdentity

Core command

CommandFunctionInstructions
aws ec2 run-instances --user-data file://user-data.shWith user data at startupCLI automatically does base64; modify-instance-attribute does not
--metadata-options HttpTokens=required,HttpPutResponseHopLimit=2,InstanceMetadataTags=enabledExplicitly set IMDS at startupDoes not rely on AMI default values and facilitates auditing
aws ec2 modify-instance-metadata-optionsModify the IMDS options of a running instanceTake effect immediately without restarting
aws ec2 modify-instance-metadata-defaultsSet the IMDS default value of the account in this regionOnly affects newly created instances
cloud-init status --long --waitWait and view the cloud-init resultsstatus: done / error
cloud-init analyze blame / showEach module takes timeFind out which stage is slow
ec2-metadata -i -z -tAL2023's own IMDS Query tool (ec2-utils package)IMDSv2 token processed internally
aws ec2 get-console-output --latestView instance serial port output from the local machineNo need to log in to the instance

Manually walk through IMDSv2 on the instance

TOKEN=$(curl -sS -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
H="X-aws-ec2-metadata-token: $TOKEN"
curl -sS -H "$H" http://169.254.169.254/latest/meta-data/instance-id; echo
curl -sS -H "$H" http://169.254.169.254/latest/meta-data/placement/availability-zone; echo
curl -sS -H "$H" http://169.254.169.254/latest/meta-data/tags/instance/Name; echo     # Requires InstanceMetadataTags=enabled
curl -sS -H "$H" http://169.254.169.254/latest/meta-data/iam/info; echo
ROLE=$(curl -sS -H "$H" http://169.254.169.254/latest/meta-data/iam/security-credentials/)
curl -sS -H "$H" http://169.254.169.254/latest/meta-data/iam/security-credentials/$ROLE | sed 's/"SecretAccessKey" : ".*"/"SecretAccessKey" : "***"/; s/"Token" : ".*"/"Token" : "***"/'
# Without token (IMDSv1 style):
curl -s -o /dev/null -w "%{http_code}\n" http://169.254.169.254/latest/meta-data/instance-id
i-0123456789abcdef0
ca-central-1a
linux-lab
{ "Code" : "Success", "LastUpdated" : "2026-11-17T14:02:11Z",
  "InstanceProfileArn" : "arn:aws:iam::111122223333:instance-profile/linux-lab-ec2-profile",
  "InstanceProfileId" : "AIPAEXAMPLE" }
{
  "Code" : "Success",
  "LastUpdated" : "2026-11-17T14:02:12Z",
  "Type" : "AWS-HMAC",
  "AccessKeyId" : "ASIAEXAMPLEEXAMPLE",
  "SecretAccessKey" : "***",
  "Token" : "***",
  "Expiration" : "2026-11-17T20:17:43Z"
}
401

How to verify: The last line 401 indicates that IMDSv1 is disabled. Common errors: GET will also be 401 when the token variable is empty (PUT failed) - first check whether the PUT has timed out (hop limit) or been intercepted by the proxy (http_proxy is set but not no_proxy=169.254.169.254). Production use: Prefer using SDK/CLI or ec2-metadata in scripts, which handle tokens and refreshes automatically; Never print credentials JSON to the log.

Modify IMDS options and account defaults

aws ec2 describe-instances --instance-ids $IID --query 'Reservations[0].Instances[0].MetadataOptions'
aws ec2 modify-instance-metadata-options --instance-id $IID --http-tokens required --http-put-response-hop-limit 1
aws ec2 modify-instance-metadata-defaults --http-tokens required --http-put-response-hop-limit 2   # Account level (this region)
aws ec2 get-instance-metadata-defaults
{
    "State": "applied",
    "HttpTokens": "required",
    "HttpPutResponseHopLimit": 2,
    "HttpEndpoint": "enabled",
    "HttpProtocolIpv6": "disabled",
    "InstanceMetadataTags": "enabled"
}

cloud-init diagnostics

sudo cloud-init status --long
sudo cloud-init analyze blame | head
systemctl list-units 'cloud*' --all --no-pager
sudo tail -n 30 /var/log/cloud-init-output.log
sudo cat /var/lib/cloud/instance/user-data.txt | head -5
ls /var/lib/cloud/instance/sem/
status: done
extended_status: done
boot_status_code: enabled-by-generator
last_update: Tue, 17 Nov 2026 14:03:20 +0000
detail:
DataSourceEc2Local
errors: []
-- Boot Record 01 --
     41.20300s (modules-final/config-scripts_user)
      2.10100s (init-network/config-growpart)
…
config_scripts_user  config_ssh  config_users_groups  …

Experiment 2: Deploy myapp + Valkey with user data and observe IMDSv2 (about 8 minutes, cost ≈ 0.01 USD)

Write user data (save as ~/linuxlab/aws/user-data.sh, consistent with the myapp.service convention in Lesson 2; the Redis protocol service uses the valkey):
#!/bin/bash
# linux-lab hour 4 · myapp + Valkey on Amazon Linux 2023
set -euxo pipefail
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin

# 1) Software package: Python 3.12 + Valkey (redis6 has ended support on 2026-01-31)
dnf install -y python3.12 python3.12-pip valkey
systemctl enable --now valkey

# 2) System users and directories (idempotent)
id myapp &>/dev/null || useradd --system --home-dir /opt/myapp --shell /sbin/nologin myapp
install -d -o myapp -g myapp -m 0755 /opt/myapp /opt/myapp/app
install -d -o root -g myapp -m 0750 /etc/myapp

# 3) Application code and virtual environment
cat > /opt/myapp/app/app.py <<'EOF'
import os, socket
from flask import Flask
import redis

app = Flask(__name__)
r = redis.Redis(
    host=os.getenv("REDIS_HOST", "127.0.0.1"),
    port=int(os.getenv("REDIS_PORT", "6379")),
    password=os.getenv("REDIS_PASSWORD") or None,
    ssl=os.getenv("REDIS_SSL", "false").lower() == "true",
    socket_connect_timeout=1,
)
VERSION = os.getenv("APP_VERSION", "dev")

@app.route("/")
def index():
    try:
        hits = r.incr("hits")
    except redis.exceptions.RedisError:
        hits = "N/A (redis is not connected)"
    return f"[{VERSION}] Hello from {socket.gethostname()}, hits={hits}\n"

@app.route("/healthz")
def healthz():
    return "ok"
EOF
[ -x /opt/myapp/venv/bin/python ] || python3.12 -m venv /opt/myapp/venv
cat > /opt/myapp/app/requirements.txt <<'EOF'
flask==3.1.*
gunicorn==23.*
redis>=5
EOF
/opt/myapp/venv/bin/pip install --quiet -r /opt/myapp/app/requirements.txt
chown -R myapp:myapp /opt/myapp

# 4) Configuration file (do not keep secrets)
cat > /etc/myapp/myapp.env <<'EOF'
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
APP_VERSION=aws-1.0
EOF
chown root:myapp /etc/myapp/myapp.env && chmod 0640 /etc/myapp/myapp.env

# 5) systemd unit (written in the same way as Lesson 2)
cat > /etc/systemd/system/myapp.service <<'EOF'
[Unit]
Description=myapp (Flask + gunicorn)
Wants=network-online.target
After=network-online.target valkey.service
Requires=valkey.service

[Service]
User=myapp
Group=myapp
EnvironmentFile=/etc/myapp/myapp.env
WorkingDirectory=/opt/myapp/app
ExecStart=/opt/myapp/venv/bin/gunicorn --bind 0.0.0.0:5000 -w 2 --graceful-timeout 8 app:app
Restart=on-failure
RestartSec=3
SyslogIdentifier=myapp
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes

[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable --now myapp

# 6) Self-test: Failure will cause cloud-init to report error, easy to find
for i in $(seq 1 20); do curl -fsS http://127.0.0.1:5000/healthz && break; sleep 1; done
echo "linux-lab user data finished"

in the AL2023 repository instead, consistent with Lesson 2's Correspondence of Lesson 3 Azure cloud-init: unit contents (User=myapp, venv, EnvironmentFile, port 5000, /healthz, SyslogIdentifier=myapp) are exactly the same; the difference is only in the software package: Ubuntu's redis-server → AL2023's valkey (service valkey.service, client valkey-cli); the rsyslog installed in Lesson 3 on Ubuntu is not required on AL2023 - AL2023 only uses journald by default, and the logs are collected directly from journald by the CloudWatch Agent of module 5; Python uses the AL2023 repository python3.12 (System python3 is 3.9).

Key points: set -euxo pipefail aborts on any failure and displays the command in the log; each step is repeatable (id … ||, install -d, venv if exists), it is convenient for you to manually sudo bash /var/lib/cloud/instance/scripts/part-001 and rerun

Start the instance (explicitly write out the IMDS options, root volume encryption and label):
cd ~/linuxlab/aws && source hour4.env
IID=$(aws ec2 run-instances \
  --image-id resolve:ssm:$AL2023_PARAM --instance-type $ITYPE \
  --security-group-ids $SG_ID --iam-instance-profile Name=$IPROFILE \
  --metadata-options HttpTokens=required,HttpPutResponseHopLimit=2,HttpEndpoint=enabled,InstanceMetadataTags=enabled \
  --block-device-mappings 'DeviceName=/dev/xvda,Ebs={VolumeSize=8,VolumeType=gp3,Encrypted=true,DeleteOnTermination=true}' \
  --user-data file://user-data.sh \
  --tag-specifications "ResourceType=instance,Tags=[{Key=Name,Value=$LAB}]" "ResourceType=volume,Tags=[{Key=Name,Value=$LAB}]" \
  --query 'Instances[0].InstanceId' --output text)
echo "export IID=$IID" >> hour4.env && echo $IID
aws ec2 wait instance-status-ok --instance-ids $IID && echo "2/2 checks passed"
i-0123456789abcdef0
2/2 checks passed
Do not log in, look at the console output first (cloud-init will print the progress to the serial port):
aws ec2 get-console-output --instance-id $IID --latest --output text | grep -E "cloud-init|linux-lab" | tail -5
[   12.84] cloud-init[1650]: Cloud-init v. 22.2.2 running 'modules:config' at Tue, 17 Nov 2026 14:02:31 +0000. Up 12.71 seconds.
[   58.10] cloud-init[1890]: linux-lab user data finished
[   58.15] cloud-init[1890]: Cloud-init v. 22.2.2 finished at Tue, 17 Nov 2026 14:03:20 +0000. Datasource DataSourceEc2Local.  Up 58.12 seconds
Log in with Session Manager (Module 4 explains the principle in detail) and verify:
aws ssm start-session --target $IID
# —— The following is executed in the example——
sudo cloud-init status --long | head -3
systemctl is-active valkey myapp
curl -s http://127.0.0.1:5000/ ; curl -s http://127.0.0.1:5000/
valkey-cli ping
sudo journalctl -u myapp -n 5 --no-pager
status: done
active
active
[aws-1.0] Hello from ip-172-31-5-23.ca-central-1.compute.internal, hits=1
[aws-1.0] Hello from ip-172-31-5-23.ca-central-1.compute.internal, hits=2
PONG
Manual IMDSv2: Execute the IMDSv2 script in the "Command" tab, confirm that IMDSv1 returns 401, can read tags/instance/Name = linux-lab, and can see the credential expiration time of the role linux-lab-ec2-role , and then let the CLI. Use these credentials:
aws sts get-caller-identity --region ca-central-1
{ "Account": "111122223333",
  "Arn": "arn:aws:sts::111122223333:assumed-role/linux-lab-ec2-role/i-0123456789abcdef0" }

The session name is the instance ID - this can be traced back to the instance in CloudTrail

(Optional) Reproduce the hop limit failure in the container:
sudo dnf install -y docker && sudo systemctl start docker
sudo docker run --rm public.ecr.aws/aws-cli/aws-cli:latest sts get-caller-identity --region ca-central-1 --query Arn
# Return to linuxlab local machine: change hop limit to 1
aws ec2 modify-instance-metadata-options --instance-id $IID --http-put-response-hop-limit 1
# Return to instance: run again
sudo docker run --rm public.ecr.aws/aws-cli/aws-cli:latest sts get-caller-identity --region ca-central-1 --query Arn
sudo docker run --rm --network host public.ecr.aws/aws-cli/aws-cli:latest sts get-caller-identity --region ca-central-1 --query Arn
"arn:aws:sts::111122223333:assumed-role/linux-lab-ec2-role/i-0123456789abcdef0"
(hop limit 1, bridge network: wait a few seconds)
Unable to locate credentials. You can configure credentials by running "aws configure".
(--network host)
"arn:aws:sts::111122223333:assumed-role/linux-lab-ec2-role/i-0123456789abcdef0"

Recovery: aws ec2 modify-instance-metadata-options --instance-id $IID --http-put-response-hop-limit 2, and sudo dnf remove -y docker.

Clean: Preserve instance, module 3–7 Continue to use. If you do not want to continue today, terminate the instance according to the cleanup steps in Module 8.

Case 1: SSRF leaks role credentials via IMDSv1

Issue:An image proxy service accepts the URL passed by the user and crawls it on the server side. http://169.254.169.254/latest/meta-data/iam/security-credentials/web-role, after obtaining the temporary credentials, list the S3 bucket. Method: Change the account-level IMDS default to HttpTokens=required; use the MetadataNoToken CloudWatch indicator to find out whether IMDSv1 is still used. instances and upgrade the SDK one by one; use the SCP / IAM condition key ec2:MetadataHttpTokens to prohibit starting non-IMDSv2 instances; the application layer prohibits access to link-local addresses. Restrictions:IMDSv2 cannot protect against attackers who can execute arbitrary commands on the instance; role permissions still need to be minimized.

Case 2: user data Silent failure causes ASG to scale out "empty shell" instances

Problem: After a certain release, the status checks of the newly expanded instances are all 2/2, but all load balancing health checks fail. The reason is that pip install in user data fails due to an upstream package version conflict, and the script does not have set -e. Subsequent steps continue to be executed, and finally systemd Unit startup failed. How to:Add set -euxo pipefail and end self-check; ELB health check + ASG lifecycle hook; depend on locked version or baked into AMI. Limitations: Cloud-init failure will not stop the instance and must be replaced by health check.

Case 3: Pod on EKS node Obtained node role credentials

Problem: The self-managed EKS node group uses the default hop limit 2, and any Pod can obtain the node IAM role credentials (including some ECR and EC2 permissions) through IMDS. Method: Set the node Launch Template to HttpPutResponseHopLimit=1, and the application uses EKS Pod instead. Identity / IRSA get their respective roles. Restrictions: Pods using hostNetwork: true can still access IMDS and need to be restricted by admission policies.

Common errors and solutions

cloud-init status: error · /var/log/cloud-init-output.log: Error: Unable to find a match: valky

Cause:The package name is misspelled, or the package is not in the currently locked repository version. The command in set -e causes the script to abort, and the cloud-init flag scripts_user fails. Also note: Although the redis6 package is still in the repository, it has ended support on 2026-01-31 (no more security updates), dnf supportinfo --pkg redis6 can be viewed, and new deployments should be used instead. valkey.

sudo cloud-init status --long
sudo grep -n -E "Error|Traceback|failed" /var/log/cloud-init-output.log | tail
dnf list --available 'valkey*' 'redis*'

Fix: Correct the package name valkey; manually rerun the script sudo bash -x /var/lib/cloud/instance/scripts/part-001; also update the Launch Template / script source code

curl: (28) Connection timed out after … milliseconds (PUT http://169.254.169.254/latest/api/token, in the container)

Reason: The hop limit is 1, the container has one more hop through the bridge network, and the PUT response is discarded when the TTL is exhausted on the host.

aws ec2 describe-instances --instance-ids $IID --query 'Reservations[0].Instances[0].MetadataOptions.HttpPutResponseHopLimit'

Fix: Set to 2 when the container is really required to use the instance role; otherwise, keep it as 1 to provide an independent identity for the container (ECS task role, EKS Pod Identity)

HTTP 401 Unauthorized from http://169.254.169.254/latest/meta-data/…

Cause:HttpTokens=required The request did not come with a token (old script, old SDK), or the token has expired. Diagnostics: CloudWatch metrics MetadataNoToken, MetadataNoTokenRejected. Fix: The script is changed to PUT + token; upgrade SDK (AWS CLI ≥ 1.16.289, boto3 ≥ 1.12.6, etc. support IMDSv2).

Unable to locate credentials (aws CLI on the instance)

Reason: The instance has no associated instance configuration file; or there is no role in the configuration file; or IMDS is turned off by HttpEndpoint=disabled; or the proxy is set but not excluded 169.254.169.254.

aws ec2 describe-instances --instance-ids $IID --query 'Reservations[0].Instances[0].[IamInstanceProfile.Arn,MetadataOptions.HttpEndpoint]'
env | grep -i _proxy

Fixed:aws ec2 associate-iam-instance-profile --instance-id $IID --iam-instance-profile Name=$IPROFILE (can be associated while running, no need to restart); export no_proxy=169.254.169.254.

Modified user data and restarted, but the script was not executed again

Reason: The script frequency is once-per-instance, /var/lib/cloud/instances//sem/config_scripts_user already exists. Fix: The test environment can be sudo cloud-init clean --logs && sudo reboot to make cloud-init think it is a new instance (SSH host key will be regenerated, etc., use with caution in production); it is recommended to replace it with a new instance in production.

Command line operation questions
1. Use a curl combination command on the instance to retrieve the current availability zone through IMDSv2.
curl -s -H "X-aws-ec2-metadata-token: $(curl -s -X PUT http://169.254.169.254/latest/api/token -H 'X-aws-ec2-metadata-token-ttl-seconds: 60')" http://169.254.169.254/latest/meta-data/placement/availability-zone
2. Locally find all instances in the current region that still allow IMDSv1.
aws ec2 describe-instances --filters Name=metadata-options.http-tokens,Values=optional \
  --query 'Reservations[].Instances[].[InstanceId,Tags[?Key==`Name`]|[0].Value]' --output table
Scenario analysis question
New instance status check 2/2 passed, Online is also displayed in SSM, but curl localhost:5000 connection was refused. Write down the troubleshooting steps in order.

① sudo cloud-init status --long: Whether it is error and which module it is stuck in; ② tail /var/log/cloud-init-output.log: Which line of user data failed (set -x will print the command); ③ systemctl status myapp valkey and journalctl -u myapp -b: whether the unit exists and whether it failed due to Requires=valkey.service; ④ ss -ltnp | grep 5000: whether to monitor; ⑤ After repair, use the new instance to verify the user data, instead of just manually repairing the old instance.

Verified teaching video

▶
Transition to IMDSv2 on EC2 - Introduction, Preparation, Pitfalls — cloudonaut
English · IMDSv1 → IMDSv2 migration, MetadataNoToken indicators and common pitfalls
▶
Understanding Amazon EC2 Instance Metadata Service v2 Hop Limit — StratusGrid
English · The relationship between hop limit and container access to IMDS (corresponding to animation B of this module)
▶
Getting Started with cloud-init — Learn Linux TV
English · Basic concepts of cloud-init and #cloud-config examples (not AWS-specific, the mechanism is common)

Official documentation

Video storyboard script (about 100 seconds)

This courseware cannot directly generate video/MP3. Storyboards and explanation scripts have been provided, which can be generated by video tools.

Shot 1 · 0–20s
Screen: In the black screen, the four icons of UEFI, GRUB, kernel, and systemd light up in sequence, and the time code goes from 0 seconds to 6 seconds.
Narration: An EC2 instance boots up just like a local machine: firmware, bootloader, kernel, and then systemd takes over.
Shot 2 · 20–45s
Screen: In the cloud-init local stage, a hand is extended to issue a PUT to 169.254.169.254, a key is taken back, and the key is used to open the drawer with meta-data and user-data.
Narration: cloud-init first exchanges PUT for a session token, and then uses the token to read metadata and user data. This is IMDSv2.
Shot 3 · 45–70s
Screen: The script is executed in the final stage, the terminal scrolls quickly dnf install valkey, useradd myapp, systemctl enable --now myapp, and finally the green ok.
Narration: user data is executed as root in the final stage and is executed only once. All output is in the cloud-init-output log.
Shot 4 · 70–100s
Screen: The aws CLI in a container issues a PUT, and when the return packet passes through docker0, the TTL changes from 1 to 0 and turns into smoke; after adjusting the hop limit to 2, the return packet arrives smoothly.
Narration: The IP TTL of the token response is equal to the hop limit. If the container has one more hop and the hop limit is one, it will not be able to get the token and the credentials.
Or score ≥ 70% on the Quiz

Module 3 · EBS volume, instance storage and file system

13:00 – 21:00 · The console writes /dev/sdf, but what is seen in the system is /dev/nvme1n1 - Correct writing of block devices, persistence and fstab on Nitro
8 minutesgp3 · NVMe · XFSData persistence★★★★★
Learning Objectives
  • Distinguish between EBS volumes (network block storage, independent of instance existence, snapshottable) and instance storage (local NVMe, stop/hibernate/terminate and lose), and choose based on data durability requirements.
  • Use lsblk -o +SERIAL, ebsnvme-id, /dev/disk/by-id on the Nitro instance to find the correct volume, complete formatting, mounting, /etc/fstab (UUID + nofail).
  • Online expansion of the EBS volume and root partition (modify-volume → growpart → xfs_growfs), and migration of the Valkey data directory to an independent data disk.
Prerequisite knowledge:Lesson 2 LVM / file system / fstab, systemd mounting unit. Importance:★★★★★ (disk problems will directly lead to failure to start or data loss)

What: Two types of block storage on EC2

EBS volumesInstance store
Physical locationEBS storage cluster, connected via network (Nitro card presents it as an NVMe device)Host local NVMe SSD (some older models are HDD)
Life cycleIndependent of the instance; can be detached and remounted to other instances in the same availability zoneBound to the instance: retained on restart; lost when stopping, hibernating, and terminating
Availability rangeOne availability zone; crossing availability zones requires snapshotsOne host
BackupSnapshot (incremental, stored in S3), can be copied across regionsNone, you need to copy to persistent storage yourself
Typical typegp3 (general-purpose SSD, baseline 3000 IOPS / 125 MiB/s, can be purchased separately IOPS/throughput), io2 (high IOPS, multiple mounts possible), st1/sc1 (HDD throughput) are provided with instance types, such as m7gd, c6id, i4i
BillingBased on preset GB·month + additional IOPS/throughput; regardless of whether it is mounted or fullIncluded in the instance price
Suitable for placementRoot volume, database, application state, logsCache, temporary files, rebuildable data, Shuffle

Why: Why Linux administrators must understand NVMe naming

On Nitro instances, all EBS volumes and instance storage are named The NVMe device appears. The /dev/sdf written in the block device mapping is just a "prompt name". The kernel names /dev/nvme0n1, /dev/nvme1n1 according to the order in which the device responds to enumeration... The order may change when starting again. If /etc/fstab writes /dev/nvme1n1, one day it may point to another disk, or it may not exist at all, causing the mount to fail and the system to enter emergency mode (module 7 will deliberately create this failure).

How: Stable identification and assistance with AL2023

  • Volume ID is the serial number: The serial number of the EBS NVMe device is the volume ID with the hyphens removed (vol0123…), lsblk -o +SERIAL Visible; /dev/disk/by-id/nvme-Amazon_Elastic_Block_Store_vol0123… is a stable link.
  • Block device mapping name: The mapping name is saved in the vendor-defined field of the NVMe controller. AL2023's udev rules (ec2-utils package) read it and create a /dev/sdf → nvme1n1 symlink; sudo ebsnvme-id /dev/nvme1n1 can be viewed directly. For other distributions, use sudo nvme id-ctrl -V /dev/nvme1n1 (nvme-cli).
  • File system UUID / LABEL: Generated when mkfs is used, following the file system, it is the recommended way of writing fstab.
  • nofail: Does not block startup when the volume does not exist; cooperate with x-systemd.device-timeout=10s to avoid long waiting. systemd will convert fstab lines into data.mount units, and services can declare dependencies using RequiresMountsFor=/data.
  • Root volume: The root file system of AL2023 is XFS, the root volume mapping name is /dev/xvda, and the system is /dev/nvme0n1p1 (there are also boot partitions such as p127/p128). cloud-init's growpart will expand the root partition to the entire disk when booting for the first time.

When: Where to put

DataLocationReason
Operating system, myapp code (/opt/myapp)Root volume gp3Rebuildable from AMI + user data
Valkey persistent data (RDB/AOF)Independent gp3 data volume /dataCan be individually snapshotted, expanded, and migrated to new instances
Temporary cache, compilation of intermediate productsInstance storage (if any)Free and fastest, loss is acceptable
Multi-instance shared filesEFS / FSx (not EBS)EBS can generally only be mounted to one instance (io2 multi-mounting requires a cluster file system)
Common misunderstandings① "Instance storage will be lost after restarting" - retained after restarting, stop/hibernate/terminate; however, the stop caused by host failure will also be lost. ② "Terminating the instance will delete all volumes" - only the volumes of DeleteOnTermination=true are deleted (the default is true for the root volume, and the default is false for the data volumes attached later), so the data volumes must be deleted separately during cleanup (Module 8). ③ "The file system automatically becomes larger after the volume is expanded" - only the block device becomes larger, but also growpart (when there is a partition) + xfs_growfs / resize2fs. ④ "EBS volumes can be shrunk" - No, you can only create a new small volume and copy the data.

Architecture diagram: EBS and instance storage in Nitro instance

Host (Nitro) Instance i-0123 (AL2023) /dev/nvme0n1 → nvme0n1p1 /(XFS)/dev/nvme1n1 → /data(XFS, LABEL=valkeydata)udev: /dev/xvda → nvme0n1, /dev/sdf → nvme1n1/dev/nvme2n1 → Instance Storage (d-type instances only)fstab: UUID=… /data xfs defaults,nofail Nitro CardNVMe Controller × N Local NVMe SSDInstance StorageRestart PreservedStop/Terminate Lost EBS (Available Zone ca-central-1a) vol-root gp3 8 GiBDeleteOnTermination = true vol-data gp3 10→20 GiBDeleteOnTermination = false Snapshot snap-… (S3, incremental)Recoverable across Availability Zones/Regions Network
Figure 3-1 EBS is stored locally via the network and the instance is stored locally, both presented to the instance as an NVMe device via Nitro card

Flowchart: New volume from creation to use by the service

CreateVolumeSame Availability Zone · Encryption AttachVolume--device /dev/sdf NVMe Hot Plug/dev/nvme1n1 udev/dev/sdf, by-id mkfs.xfsUUID/LABEL fstabnofail ServiceRequiresMounts AWS API (two steps on the left) → Kernel and udev (two steps in the middle) → Administrator operations (three steps on the right)
Figure 3-2 Mount a new EBS Full link to volume

Animation: "Lifetime" of an EBS volume and loss of instance storage

Demonstrates API state changes (creating → available → attaching → in-use), kernel NVMe enumeration, udev symlinks, filesystems and fstab. Check the option to observe the changes after stop/start.

AWS API perspective
—
Kernel/udev perspective
—
File system/service
—

Core Command

CommandFunctionKey parameters/description
aws ec2 create-volumeCreate volume--availability-zone must be the same as the instance; --volume-type gp3 --size 10 --encrypted
aws ec2 attach-volume / detach-volumeMount/detach--device /dev/sdf (prompt name); before detaching, umount
aws ec2 modify-volumeModify size, type, IOPS, throughput onlineThere is a cooling time between two modifications of the same volume (subject to documentation, usually 6 hours)
lsblk -o NAME,SIZE,TYPE,MOUNTPOINTS,SERIAL,MODELList block device and serial numberSERIAL = volume ID (no hyphen)
sudo ebsnvme-id /dev/nvme1n1AL2023: NVMe → Volume ID + Mapping nameUbuntu uses nvme id-ctrl -V
sudo mkfs.xfs -L valkeydata /dev/nvme1n1Format (will be cleared!)First sudo file -s to confirm it is data (empty disk)
sudo growpart /dev/nvme0n1 1 + sudo xfs_growfs -d /Expand root partition and file systemext4 Use resize2fs
findmnt --verifyCheck fstab syntax and equipmentFinish changing fstab Must be executed, and then mount -a

Identify new volume (AL2023)

lsblk -o NAME,SIZE,TYPE,MOUNTPOINTS,SERIAL
sudo ebsnvme-id /dev/nvme1n1
ls -l /dev/sdf /dev/disk/by-id/ | grep -E "sdf|Elastic_Block_Store_vol" | head
sudo file -s /dev/nvme1n1
NAME          SIZE TYPE MOUNTPOINTS SERIAL
nvme0n1         8G disk             vol0aaaabbbbccccdddd0
├─nvme0n1p1     8G part /
├─nvme0n1p127   1M part
└─nvme0n1p128  10M part /boot/efi
nvme1n1        10G disk             vol0123456789abcdef0
Volume ID: vol-0123456789abcdef0
/dev/sdf
lrwxrwxrwx 1 root root 7 Nov 17 14:20 /dev/sdf -> nvme1n1
lrwxrwxrwx 1 root root 13 Nov 17 14:20 nvme-Amazon_Elastic_Block_Store_vol0123456789abcdef0 -> ../../nvme1n1
/dev/nvme1n1: data

How to verify: The serial number after removing vol corresponds to the ID of aws ec2 describe-volumes (add a hyphen). Common mistakes: Executing mkfs on a disk with existing data——file -s stops when XFS filesystem data is displayed. Production use: Locate device by volume ID in script: /dev/disk/by-id/nvme-Amazon_Elastic_Block_Store_${VOL//-/}.

Recommended fstab lines and systemd dependencies

UUID=3f1c9a8e-1b2c-4d5e-8f90-0123456789ab  /data  xfs  defaults,nofail,x-systemd.device-timeout=10s  0  2
[Unit]
RequiresMountsFor=/data

[Service]
ReadWritePaths=/data/valkey

Experiment 3: Add a gp3 data disk to Valkey and expand it online (about 8 minutes, cost ≈ 0.01 USD)

Create and mount the volume in the availability zone where the instance is located(linuxlab native):
cd ~/linuxlab/aws && source hour4.env
AZ=$(aws ec2 describe-instances --instance-ids $IID --query 'Reservations[0].Instances[0].Placement.AvailabilityZone' --output text)
VOL=$(aws ec2 create-volume --availability-zone $AZ --volume-type gp3 --size 10 --encrypted \
  --tag-specifications "ResourceType=volume,Tags=[{Key=Name,Value=$LAB},{Key=Role,Value=valkey-data}]" \
  --query VolumeId --output text)
echo "export VOL=$VOL" >> hour4.env
aws ec2 wait volume-available --volume-ids $VOL
aws ec2 attach-volume --volume-id $VOL --instance-id $IID --device /dev/sdf
aws ec2 wait volume-in-use --volume-ids $VOL
aws ec2 describe-volumes --volume-ids $VOL --query 'Volumes[0].[State,Attachments[0].Device,Attachments[0].DeleteOnTermination]'
"attaching"
[ "in-use", "/dev/sdf", false ]
Execute after identifying, formatting and mounting(aws ssm start-session --target $IID in the instance):
DEV=$(readlink -f /dev/sdf); echo $DEV
sudo file -s $DEV                      # data (empty disk) must be displayed
sudo mkfs.xfs -L valkeydata $DEV
sudo mkdir -p /data
UUID=$(sudo blkid -s UUID -o value $DEV)
echo "UUID=$UUID  /data  xfs  defaults,nofail,x-systemd.device-timeout=10s  0  2" | sudo tee -a /etc/fstab
sudo findmnt --verify && sudo systemctl daemon-reload && sudo mount -a
df -hT /data
/dev/nvme1n1
/dev/nvme1n1: data
meta-data=/dev/nvme1n1           isize=512    agcount=4, agsize=655360 blks
…
Success, no errors or warnings detected
Filesystem     Type  Size  Used Avail Use% Mounted on
/dev/nvme1n1   xfs    10G  104M  9.9G   2% /data
Migrate the Valkey data directory to /data (confirm the configuration file location and current directory first):
rpm -qc valkey | grep valkey.conf
sudo grep -n '^dir ' /etc/valkey/valkey.conf
sudo systemctl stop myapp valkey
sudo install -d -o valkey -g valkey -m 0750 /data/valkey
sudo cp -a /var/lib/valkey/. /data/valkey/ 2>/dev/null || true
sudo sed -i 's#^dir .*#dir /data/valkey#' /etc/valkey/valkey.conf
sudo mkdir -p /etc/systemd/system/valkey.service.d
printf '[Unit]\nRequiresMountsFor=/data\n\n[Service]\nReadWritePaths=/data/valkey\n' | sudo tee /etc/systemd/system/valkey.service.d/10-data.conf
sudo systemctl daemon-reload && sudo systemctl start valkey myapp
valkey-cli CONFIG GET dir; valkey-cli SAVE; ls -l /data/valkey
curl -s localhost:5000/
/etc/valkey/valkey.conf
… dir /var/lib/valkey
1) "dir"
2) "/data/valkey"
OK
-rw-r-----. 1 valkey valkey 112 Nov 17 14:26 dump.rdb
[aws-1.0] Hello from ip-172-31-5-23…, hits=3

AL2023's SELinux defaults to permissive, so there is no need to relabel; if you set SELinux to enforcing, you need semanage fcontext + restorecon to set the correct context for the new directory. ReadWritePaths has no side effects when the unit does not have sandbox restrictions, but is required when ProtectSystem is present.

Online expansion to 20 GiB(Execute modify locally, expand the file system in the instance; the data disk has no partition, directly xfs_growfs):
aws ec2 modify-volume --volume-id $VOL --size 20
aws ec2 describe-volumes-modifications --volume-ids $VOL --query 'VolumesModifications[0].[ModificationState,Progress]'
# ——In Example——
lsblk /dev/nvme1n1
sudo xfs_growfs /data && df -h /data
[ "optimizing", 12 ]
NAME    MAJ:MIN RM SIZE RO TYPE MOUNTPOINTS
nvme1n1 259:4    0  20G  0 disk /data
data blocks changed from 2621440 to 5242880
/dev/nvme1n1     20G  175M   20G   1% /data

The file system can be expanded after the state enters optimizing, no need to wait. completed. One more step to expand the root volume: sudo growpart /dev/nvme0n1 1 && sudo xfs_growfs -d /.

Restart verification persistence: sudo reboot, reconnect after about 1 minute, and confirm that findmnt /data, valkey-cli GET hits still has a value.
Clean: Preserve the volume, which Module 7 will use to cause an fstab fault. Note its DeleteOnTermination=false, module 8 must be removed separately.

Case 1: fstab writes device name and cannot start after kernel upgrade

Problem: The two data disks are written as /dev/nvme1n1 /data and /dev/nvme2n1 /logs respectively. After a stop/start, the enumeration order was reversed, /data was mounted on the log disk, and the application wrote the data to the wrong location; the other one entered emergency mode because it could not find the device. How to do it: Change everything to UUID= + nofail; add RequiresMountsFor= to the service unit; use AWS Config rules or startup scripts to check fstab. Limitations:nofail will cause the "disk not mounted" situation to occur silently, and services that depend on it must fail through RequiresMountsFor and be monitored (disk indicators in module 5).

Case 2: Running the database on instance storage

Problem: For performance, the team placed the PostgreSQL data directory on the instance storage of i4i. A host maintenance event triggers a stop/start and all data is lost. Method: Only store rebuildable data (such as temporary table space, cache) in the instance store; use io2 or gp3 + appropriate IOPS for the database; or use a built-in replication solution (master-slave + continuous WAL archiving to S3). Limitations: The low latency of instance storage cannot be completely replaced by EBS, and "nodes can be lost" needs to be accepted in the architecture.

Case 3: Snapshot for backup, but consistency is not applied

Problem:Valkey data disk takes daily snapshots, but after recovery, it is found that the end of the AOF is damaged. How to do: Execute valkey-cli BGSAVE before taking a snapshot and wait for completion, or use fsfreeze -f /data to freeze the file system and then take a snapshot (Data Lifecycle Manager / AWS Backup supports pre- and post-scripts); perform regular drills to restore from snapshots to new volumes. Limitations: Snapshots are crash consistent only; multi-volume applications require multi-volume consistent snapshots.

Common errors and solutions

InvalidVolume.ZoneMismatch: The volume 'vol-…' is not in the same availability zone as instance 'i-…'

Cause: The EBS volume belongs to a single availability zone. Fixed: Create a new volume in the instance availability zone; if there is existing data, take a snapshot first, and then create the volume from the snapshot in the target availability zone.

aws ec2 create-snapshot --volume-id $VOL --description "move az" --tag-specifications "ResourceType=snapshot,Tags=[{Key=Name,Value=linux-lab}]"
mount: /data: wrong fs type, bad option, bad superblock on /dev/nvme1n1, missing codepage or helper program

Cause: The volume has not been formatted; or it was formatted as ext4 but xfs was written in fstab; or the wrong device was mounted (such as using the entire disk as a partition).

sudo file -s /dev/nvme1n1; sudo blkid /dev/nvme1n1; sudo dmesg | tail

Fix: Confirm that the disk is empty before mkfs; the fstab type is consistent with the TYPE of blkid.

You are in emergency mode. After logging in, type "journalctl -xb" to view system logs

Cause: There is a line of device in fstab that does not exist and is not added nofail (the volume is detached, the name is changed, the UUID is written incorrectly), local-fs.target fails. SSM Agent will not start and login with Session Manager is not possible.

Fix: See Module 7: Log in with the EC2 serial console (password user needs to be set in advance) to comment out this line; or stop the instance, mount the root volume to the rescue instance and modify fstab.

xfs_growfs: … data size unchanged, skipping (the space has not changed after expansion)

Reason: The block device has not become larger (the modification is still modifying), or this is a disk with partitions (root volume), which needs to be growpart first.

aws ec2 describe-volumes-modifications --volume-ids $VOL
lsblk; sudo growpart /dev/nvme0n1 1; sudo xfs_growfs -d /
VolumeModificationRateExceeded / You've reached the maximum modification rate per volume limit

Reason: A cooling time is required between two modifications of the same volume. Fix: Plan the size and performance at once; create a large volume to migrate data in an emergency.

Command line operation questions
1. The volume ID is known vol-0abc123def4567890, and in the example, use a command to get the corresponding device path (does not rely on the /dev/sdf link).
readlink -f /dev/disk/by-id/nvme-Amazon_Elastic_Block_Store_vol0abc123def4567890
# or
lsblk -o NAME,SERIAL | awk '$2=="vol0abc123def4567890"{print "/dev/"$1}'
2. After the root volume is expanded from 8 GiB to 16 GiB, write out the commands that need to be executed in the instance.
lsblk /dev/nvme0n1
sudo growpart /dev/nvme0n1 1
sudo xfs_growfs -d /
df -h /
Scenario analysis question
You want to migrate the Valkey instance to a new instance in another availability zone, and the data is in /data (independent EBS volume). Design the steps and explain where the downtime window is.

① valkey-cli BGSAVE on the old instance and confirm completion; ② Stop writing (stop myapp) - the shutdown begins; ③ Create a snapshot of the data volume (you can do a pre-snapshot first to reduce the increment); ④ Create a gp3 volume from the snapshot in the target availability zone; ⑤ Start the new instance with the same user data and mount the new volume to /data (fstab presses UUID, the volume UUID restored by the snapshot remains unchanged); ⑥ Start valkey and myapp, verify hits; ⑦ Switch traffic - the shutdown ends; ⑧ Delete the old volume and temporary snapshot after confirmation. The downtime window is mainly ③~⑦, which can be shortened by "pre-snapshot + final incremental snapshot".

Verified teaching video

▶
AWS EBS vs. EC2 Instance Store: Differences, Performance, and Use Cases Explained — Cloud Explainers
English · The difference and applicable scenarios between EBS and instance storage
▶
AWS Storage Explained | EBS vs EFS vs S3 | AWS Training — KodeKloud
English · Comparison of block/file/object storage to help determine "EBS should not be used for shared files"
▶
AWS EBS Volumes Explained - Create, Attach, Snapshot & Backup — DheerajTechInsight
English · Console demonstration creation, mounting and snapshot (this lesson uses CLI and NVMe identification)

Official Document

Video storyboard script (about 90 seconds)

This courseware cannot directly generate video/MP3. Storyboards and explanation scripts have been provided, which can be generated by video tools.

Lens 1 · 0–20s
Screen: A disk labeled vol- is connected to the instance via a network cable, and another SSD is soldered directly to the host; after the stop button is pressed, the soldered SSD turns gray and is cleared.
Narration: EBS is connected through the network and exists independently of the instance; the instance is stored locally and will be cleared when it is stopped.
Shot 2 · 20–45s
Screen: The console says /dev/sdf, the camera cuts to lsblk output nvme1n1, udev pulls out an arrow to connect the two, and the serial number vol0123 is highlighted.
Aside: On Nitro, all volumes are NVMe devices. The mapping name is just a hint, it's the volume ID and file system UUID that are truly stable.
Lens 3 · 45–70s
Screen: Comparison of two lines in fstab. The device name line on the left turns red, and the system enters emergency mode; the UUID plus nofail line on the right turns green, and the system starts normally.
Narration: Write the UUID to fstab and add nofail, and the startup will not freeze even if the volume is missing.
Shot 4 · 70–90s
Screen: Volume stretched from 10G to 20G, followed by xfs_growfs to make the file system larger.
Narration: Expansion is a two-step process: first change the volume, and then expand the file system. Volumes can only grow larger, not smaller.
Or score ≥ 70% on the Quiz

Module 4 · Access: SSM Session Manager, EC2 Instance Connect and SSH

21:00 – 29:00 · Not open 22 The port can also log in: who actively connects to whom, where the identity is verified, and where the audit record is
8 minutesSSM Agent 3.3.xec2-instance-connect 1.1★★★★★
Learning objectives
  • Clear the connection direction of the Session Manager (SSM Agent on the instance Active Outbound 443) and the identity verification point (IAM) ssm:StartSession), so zero inbound port, no SSH key is possible.
  • Use Session Manager login, port forwarding (local access to the instance's 5000 port), SSH over SSM; know which VPC endpoints are required for the private subnet.
  • Understand the 60-second temporary public key mechanism of EC2 Instance Connect (issued by IMDS and read by sshd AuthorizedKeysCommand), as well as the applicable scenarios and risks of EIC Endpoint and traditional key pair SSH.
Prerequisite knowledge:Lesson 1 SSH and public key authentication, Lesson 2 sshd configuration; module 2 instance configuration file and IMDS. Importance:★★★★★ (The login method determines the attack surface)

What: three access methods

SSM Session ManagerEC2 Instance Connect(EIC)Key pair + SSH
Connection directionInstance → External (Agent outbound 443), User → SSM APIUser → Instance 22 port (or via EIC Endpoint)User → Instance 22 Ports
Inbound RulesNot requiredRequired 22 (Source: your IP, EIC service prefix list, or EIC Endpoint security group)Required 22
IdentityIAM (ssm:StartSession, can be restricted by tag)IAM (ec2-instance-connect:SendSSHPublicKey, can be restricted by ec2:osuser)Person holding private key
CredentialsNo long-term keyOne-time public key, valid for 60 secondsLong-term private key (easy to leak, difficult to rotate)
Instance-side componentamazon-ssm-agent + instance role (AmazonSSMManagedInstanceCore)ec2-instance-connect package (AL2023 standard AMI, Ubuntu 20.04+ pre-installed)sshd + cloud-init injected authorized_keys
Logged in userDefault ssm-user (with sudo), configurable Run AsThe OS user you specify (ec2-user / ubuntu)The user corresponding to the key
AuditCloudTrail StartSession + optional session logs (CloudWatch Logs/S3)CloudTrail SendSSHPublicKeyInstance local only journalctl -u sshd
File transfer/ Port forwardingPort forwarding document; scp available after SSH over SSMStandard ssh/scpStandard ssh/scp

Why: Why Session Manager is selected by default

  • Attack surface: There is no sshd port listening to the Internet, so scanning and brute force cracking are impossible.
  • Identity Unification: Who can log in to which instance is determined by IAM/SSO, and it becomes invalid upon resignation; there is no need to distribute or rotate private keys.
  • Audit: Each session is recorded in CloudTrail, and the complete terminal output can be saved after the session log is turned on.

How: Real link to Session Manager

  1. After the instance is started, SSM Agent obtains the instance role credentials through IMDS (module 2) and registers as a managed node with ssm.ca-central-1.amazonaws.com (describe-instance-information PingStatus=Online), and maintain a long connection with ec2messages / ssmmessages.
  2. You run aws ssm start-session locally: the CLI calls the StartSession API with your SSO credentials, and IAM evaluates ssm:StartSession (the resource is the instance ARN and session document).
  3. The service notifies the Agent to open a data channel (WebSocket over TLS) through ssmmessages, and returns the StreamUrl and token to the local session-manager-plugin.
  4. Both the plug-in and the Agent are connected to the Session Manager service, and the service forwards the byte stream in the middle; the Agent starts the shell with ssm-user on the instance (or does port forwarding according to the document).

Prerequisite (verified):SSM Agent ≥ 2.3.68 (Port forwarding/SSH requires ≥ 3.0.222.0); the instance can outbound HTTPS to three endpoints: ec2messages, ssm, ssmmessages (private subnet uses VPC Interface endpoint instead of NAT); instance role contains AmazonSSMManagedInstanceCore (or enable Default Host Management Configuration, and SSM will provide the role on your behalf, subject to the official documentation); native AWS CLI + Session Manager plug-in.

How: Real link to EC2 Instance Connect

  1. Natively generate or use a temporary key pair, calling SendSSHPublicKey (specifying the instance and OS user).
  2. EC2 places the public key in the instance's metadata and removes it after 60 seconds.
  3. You ssh connect within 60 seconds; the ec2-instance-connect package on the instance configures AuthorizedKeysCommand for sshd, and sshd calls it to read the just-pushed public key through IMDS and compare it.
  4. EIC Endpoint: Create an endpoint in the private subnet, aws ec2-instance-connect ssh --connection-type eice to establish a tunnel through the endpoint, the instance does not require a public IP; the instance security group only needs to allow 22 from the endpoint security group.

When: How to choose

ScenarioRecommended
Daily operation and maintenance, production environmentSession Manager (with session logs, authorization by label)
Requires native SSH capabilities (scp, Ansible over SSH, VS Code Remote)SSH over SSM (ProxyCommand), or EIC Endpoint
Agent is broken, the instance is not registered to SSM, but the network and sshd are normalEC2 Instance Connect (temporary open source IP)
Neither the network nor sshd can start (fstab, kernel panic)EC2 Serial Console (Module 7)
Long-term key pairOnly as a last resort; private key in password manager, inbound restricted source
Common misunderstandings① "Session Manager uses SSH" - the default shell session does not go through sshd, and does not require port 22; only the AWS-StartSSHSession document wraps the SSH protocol in the SSM tunnel. ② "It is enough for the security group to allow outbound, private subnets can also be used" - the private subnet has no route to the public network and requires NAT or three VPC interface endpoints. ③ "EIC does not require inbound rules" - the direct connection is still SSH to port 22, and the source must be released; only the EIC Endpoint method can remove the public IP. ④ "ssm-user No permissions" - It has full sudo in sudoers by default. You can instead use Run As in the Session Manager preferences to specify a low-privilege user.

Architecture diagram: three access paths

linuxlab (native)aws CLI v2 + SSOsession-manager-pluginssh client Systems Manager (regional service)StartSession (IAM Authorization + CloudTrail)ssmmessages forward data channel EC2 Instance Connect APISendSSHPublicKey → Metadata (60 seconds) Security Group linux-lab-sgInbound: empty (SSM)SSH/EIC requires temporary release 22 EC2 instance linux-labamazon-ssm-agent→ ssm-user shellsshd :22AuthorizedKeysCommand (EIC via IMDS Get the public key)~/.ssh/authorized_keys(Key pair, cloud-init injection) ① HTTPS API Agent outbound 443 ② Push the public key ③ ssh :22
Figure 4-1 Blue is Session Manager: Both ends are connected to the service, and the instance does not need to be inbound; gray is EIC / SSH, which requires instance 22 port to be reachable

Flow chart: Session Manager port forwarding access myapp

curl localhost:5000linuxlab session-manager-pluginListen to local 5000 Session ManagerTLS WebSocket SSM AgentConnect 127.0.0.1:5000 gunicornmyapp.service Documentation AWS-StartPortForwardingSession; The instance security group still does not have any inbound rules
Figure 4-2 Port forwarding: The local port reaches the instance loopback address through the SSM tunnel

Animation: data flow and checkpoints of three access methods

Play after selecting the access method. Each step identifies who initiates the connection, where identity verification is performed, and what audit records are left. Check "Security group has no inbound rules" to see which method will fail.

NativeCLI / ssh AWS APIIAM Authorization Network BoundarySecurity Group/Routing Instance componentAgent / sshd shellUsers/Audit

Core Command

CommandFunctionDescription
aws ssm describe-instance-informationCheck whether the managed node is Online, Agent version, platformPrerequisites for Session Manager
aws ssm start-session --target $IIDInteractive shellRequires session-manager-plugin
--document-name AWS-StartPortForwardingSessionLocal port → instance port--parameters portNumber=5000,localPortNumber=5000
--document-name AWS-StartPortForwardingSessionToRemoteHostForwarded to other hosts in VPC (such as RDS) via instancehost=…,portNumber=…
--document-name AWS-StartSSHSessionSSH over SSM(ProxyCommand)Still requires SSH key/EIC Public key for authentication
aws ssm send-command --document-name AWS-RunShellScriptNon-interactive batch execution of commandsOutput can be written to S3 / CloudWatch Logs
aws ec2-instance-connect ssh --instance-id $IIDOne command to complete pushing the public key + SSH--connection-type direct|eice, --os-user
aws ec2-instance-connect send-ssh-public-keyOnly push the public key (60 seconds)Then ssh

check the managed node

aws ssm describe-instance-information --filters Key=InstanceIds,Values=$IID \
  --query 'InstanceInformationList[0].[PingStatus,AgentVersion,PlatformName,PlatformVersion]'
[ "Online", "3.3.5828.0", "Amazon Linux", "2023" ]

SSH over SSM(~/.ssh/config)

Host i-* mi-*
    User ec2-user
    ProxyCommand sh -c "aws ssm start-session --target %h --document-name AWS-StartSSHSession --parameters 'portNumber=%p'"

then ssh i-0123456789abcdef0; authentication is still completed by sshd (key pair or first use ssh-public-key pushes the public key), but does not require any inbound rules.

Restrict who can connect to which instance by label (IAM policy fragment)

{
  "Effect": "Allow",
  "Action": "ssm:StartSession",
  "Resource": "arn:aws:ec2:ca-central-1:*:instance/*",
  "Condition": { "StringEquals": { "ssm:resourceTag/Name": "linux-lab" } }
},
{
  "Effect": "Allow",
  "Action": ["ssm:TerminateSession", "ssm:ResumeSession"],
  "Resource": "arn:aws:ssm:*:*:session/${aws:userid}-*"
}

Experiment 4: Zero inbound port login, port forwarding, and comparison with EC2 Instance Connect (about 8 minutes, cost ≈ 0)

Confirm that the node is online and log in:
cd ~/linuxlab/aws && source hour4.env
aws ssm describe-instance-information --filters Key=InstanceIds,Values=$IID --query 'InstanceInformationList[0].PingStatus'
aws ssm start-session --target $IID
# In instance
whoami; id; sudo -l | tail -2
systemctl status amazon-ssm-agent --no-pager | head -3
sudo ss -tnp | grep -E 'amazon-ssm|ssm-session' | head -3
exit
ssm-user
uid=1001(ssm-user) gid=1001(ssm-user) groups=1001(ssm-user)
    (ALL) NOPASSWD: ALL
● amazon-ssm-agent.service - amazon-ssm-agent
     Active: active (running) since …
ESTAB 0 0 172.31.5.23:41822 15.157.x.x:443 users:(("amazon-ssm-agen",pid=1312,fd=11))
ESTAB 0 0 172.31.5.23:41836 15.157.x.x:443 users:(("ssm-session-wor",pid=2290,fd=12))

All connections are instance active outbound to 443, there are no inbound connections.

Port forwarding access myapp(local terminal A):
aws ssm start-session --target $IID --document-name AWS-StartPortForwardingSession \
  --parameters '{"portNumber":["5000"],"localPortNumber":["5000"]}'
# Local terminal B
curl -s http://127.0.0.1:5000/
curl -s http://127.0.0.1:5000/healthz
Starting session with SessionId: labadmin-0a1b2c3d4e5f6a7b8
Port 5000 opened for sessionId labadmin-0a1b2c3d4e5f6a7b8.
Waiting for connections...
[aws-1.0] Hello from ip-172-31-5-23.ca-central-1.compute.internal, hits=4
ok
Non-interactive execution command (basis of batch operation and maintenance):
CMD=$(aws ssm send-command --instance-ids $IID --document-name AWS-RunShellScript \
  --parameters 'commands=["systemctl is-active myapp valkey","df -h /data | tail -1"]' --query Command.CommandId --output text)
sleep 3; aws ssm get-command-invocation --command-id $CMD --instance-id $IID --query '[Status,StandardOutputContent]' --output text
Success	active
active
/dev/nvme1n1     20G  175M   20G   1% /data
Comparison: EC2 Instance Connect (temporarily release local IP):
MYIP=$(curl -s https://checkip.amazonaws.com)
aws ec2 authorize-security-group-ingress --group-id $SG_ID --protocol tcp --port 22 --cidr $MYIP/32
aws ec2-instance-connect ssh --instance-id $IID --os-user ec2-user --connection-type direct
# View how sshd obtains the public key in the example:
sudo sshd -T | grep -i authorizedkeyscommand
sudo journalctl -u sshd -n 3 --no-pager
exit
aws ec2 revoke-security-group-ingress --group-id $SG_ID --protocol tcp --port 22 --cidr $MYIP/32
authorizedkeyscommand /opt/aws/bin/eic_run_authorized_keys %u %f
authorizedkeyscommanduser ec2-instance-connect
Nov 17 14:40:02 ip-172-31-5-23 sshd[3021]: Accepted publickey for ec2-user from 203.0.113.10 port 50122 ssh2: ED25519 SHA256:…

Be sure to revoke the inbound rule. You will see the SendSSHPublicKey event in CloudTrail (including OS users), and the sshd log is an ordinary public key login.

(Optional) Enable session logs: Enable CloudWatch Logs in Systems Manager Console → Session Manager → Preferences, log group such as /linux-lab/ssm-sessions (the instance role requires write log permission, CloudWatchAgentServerPolicy is included logs:PutLogEvents etc.).
Cleaning: Confirm that the security group inbound rules are empty: aws ec2 describe-security-groups --group-ids $SG_ID --query 'SecurityGroups[0].IpPermissions' Should be output [].

Case 1: Close port 22 for the entire company

Issue: An audit found 300 instances open to 0.0.0.0/0 22, with private keys scattered around PCs. Method: Add AmazonSSMManagedInstanceCore to the unified instance role (or enable Default Host Management Configuration); establish a private subnet for ssm, ssmmessages, ec2messages interface endpoints; centralize IAM Identity Center permissions by ssm:resourceTag/Team for authorization; enable session logs to be encrypted S3; finally use the AWS Config rule restricted-ssh to detect and remove the 22 port rule. Limitations: Some tools rely on native SSH (Ansible, scp), use SSH over SSM's ProxyCommand or Ansible's aws_ssm connection plug-in instead.

Case 2: Private instance SSM keeps ConnectionLost

Problem: The newly created private subnet instance does not appear in Fleet Manager. How to do: Check sequence: Instance role → Routing (no NAT) → Whether three interface endpoints are created and private DNS is turned on → Whether the endpoint security group allows 443 from the instance → Agent log /var/log/amazon/ssm/amazon-ssm-agent.log. Eventually it was discovered that the endpoint security group only allowed 80. Limitations: Interface endpoints are billed by the hour + traffic, one per Availability Zone.

Case 3: VS Code Remote-SSH is required to a development machine without a public IP

Problem: Developers need SSH experience, but the security team prohibits public IP. What to do: Use EIC Endpoint (aws ec2-instance-connect open-tunnel / ssh --connection-type eice) or SSH over SSM; the development machine security group only allows 22 from the EIC Endpoint security group. Restrictions: EIC Endpoint has quotas such as the number of concurrent connections, please refer to the official documentation.

Common errors and solutions

An error occurred (TargetNotConnected) when calling the StartSession operation: i-0123… is not connected.

Cause: The node is not registered or offline: there is no instance configuration file/the role lacks permissions; the Agent is not running; the three endpoints cannot be accessed outbound; the instance time is seriously deviated, causing the signature to fail.

aws ssm describe-instance-information --filters Key=InstanceIds,Values=$IID
aws ec2 describe-instances --instance-ids $IID --query 'Reservations[0].Instances[0].IamInstanceProfile'
# If you can log in via serial console/EIC:
sudo systemctl status amazon-ssm-agent; sudo tail -n 50 /var/log/amazon/ssm/amazon-ssm-agent.log
curl -sI https://ssmmessages.ca-central-1.amazonaws.com | head -1

Fix: Associate the correct instance profile (no need to restart, Agent will retry in a few minutes); fix routes/endpoints/security groups; sudo systemctl restart amazon-ssm-agent.

SessionManagerPlugin is not found. Please refer to SessionManager Documentation here: …

Cause:The Session Manager plug-in is not installed on this machine or is not in PATH. Fix: Follow "Warm-up" step 1 to install, session-manager-plugin --version to verify.

An error occurred (AccessDeniedException) when calling the StartSession operation: User: arn:aws:sts::…:assumed-role/… is not authorized to perform: ssm:StartSession on resource: arn:aws:ec2:ca-central-1:…:instance/i-…

Cause: Your identity is missing ssm:StartSession, or the label conditions do not match (the instance label is not Name=linux-lab), or port forwarding lacks authorization for the document arn:aws:ssm:*::document/AWS-StartPortForwardingSession. Fix: Adjust permission set policy; verify with aws iam simulate-principal-policy.

ec2-user@…: Permission denied (publickey,gssapi-keyex,gssapi-with-mic)(EC2 Instance Connect)

Reason: It took more than 60 seconds to connect; --os-user does not match the actual user of the instance (Ubuntu is ubuntu); the instance is AL2023 minimum AMI, ec2-instance-connect is not installed; sshd has been customized AuthorizedKeysCommand (EIC will not overwrite); IMDS is disabled (EIC relies on IMDS to obtain the public key). Fix: Completed in one command using aws ec2-instance-connect ssh; minimum AMI first dnf install -y ec2-instance-connect.

ssh: connect to host 3.98.x.x port 22: Connection timed out

Cause: The security group/NACL is not allowed, the instance does not have a public IP, the local export IP has changed (company proxy), and sshd is not running. Diagnosis:curl -s https://checkip.amazonaws.com Compare security group CIDR; VPC Reachability Analyzer. Fix: Prioritize using Session Manager instead, don't let go of 0.0.0.0/0 for SSH.

Command line operation questions
1. Through instance $IID forwarding, let the local port 15432 access the 5432 port of the VPC address 10.0.2.15.
aws ssm start-session --target $IID --document-name AWS-StartPortForwardingSessionToRemoteHost \
  --parameters '{"host":["10.0.2.15"],"portNumber":["5432"],"localPortNumber":["15432"]}'
2. List the managed nodes in the current region whose PingStatus is not Online.
aws ssm describe-instance-information --query "InstanceInformationList[?PingStatus!='Online'].[InstanceId,PingStatus,LastPingDateTime]" --output table
Scenario Analysis Questions
Security team requirements: production instances have no public network IP, no 22 inbound, all operations can be audited, and developers can only log in to instances of their own team. Give a plan.

Private subnet + ssm/ssmmessages/ec2messages (and logs, S3 gateway) VPC endpoint; instance role AmazonSSMManagedInstanceCore; instance is labeled Team, permission set policy is used ssm:resourceTag/Team conditions in combination with ${aws:PrincipalTag/Team}; Session Manager preferences enable KMS encryption and CloudWatch Logs/S3 session logging, enable Run As if necessary to have sessions run as personal OS users; CloudTrail logging StartSession; use SSH over if SSH tools are required SSM; emergency use of the serial console (separate IAM permissions and account-level switches).

Verified teaching video

▶
AWS Sessions Manager Overview — Amazon Web Services
English · AWS official channel · Overview of the positioning and capabilities of Session Manager
▶
Connect to EC2 with Session Manager and EC2 Instance Connect — Digital Cloud Training
English · Configuration and demonstration of two methods
▶
EC2 Instance Connect Tutorial — Stephane Maarek
English · EIC Console usage and security group requirements

Official document

Video storyboard script (about 90 seconds)

This courseware cannot directly generate video/MP3. Storyboards and explanation scripts have been provided, which can be generated by video tools.

Shot 1 · 0–20s
Screen: An instance is surrounded by a wall with "Security Group: Inbound is empty", and the scanner outside bounces off the wall after hitting it.
Narration: Without an inbound port, the Internet cannot reach your instance. So how do we log in?
Shot 2 · 20–50s
Screen: The SSM Agent in the instance extends a 443 rope from the wall to the Systems Manager; the local CLI is also connected to the same service, and the service connects the two ropes together.
Narration: Session Manager allows both ends to connect outwards, and services are forwarded in the middle. Identity is verified by IAM and entered into CloudTrail every session.
Shot 3 · 50–75s
Screen: The machine hands a key to the EC2 Instance Connect API. The key appears in the instance metadata and counts down for 60 seconds; sshd gets the key from the metadata to open the door.
Narration: EC2 Instance Connect pushes a one-time public key, which is valid within sixty seconds, but SSH connections still need to release port 22.
Lens 4 · 75–90s
Screen: Three-column comparison card: inbound port, long-term key, audit.
Narration: When using Session Manager on a daily basis, use the SSM tunnel when you need SSH tools, and use long-term keys only as a last resort.
Or score ≥ 70% on the Quiz

Module 5 · Monitoring and logging: CloudWatch Agent

29:00 – 37:00 · EC2 cannot see memory and disk usage by default, nor can it receive journald logs - complete it with a JSON configuration
8 minutesamazon-cloudwatch-agent 1.300071.0 (AL2023 repository)journald input★★★★
Learning Objectives
  • Tell me the difference between EC2 default indicators (Hypervisor/Nitro perspective) and Agent indicators (operating system perspective), and know that memory and file system usage must rely on Agent.
  • Write CloudWatch Agent configuration: journald collects myapp / valkey unit logs, files collects /var/log/cloud-init-output.log, mem/disk indicators, and sets the retention period and dimensions.
  • Use amazon-cloudwatch-agent-ctl to load the configuration and check the Agent's own logs; use aws logs tail, Logs Insights and alarms to verify the results.
Prerequisite knowledge:Lesson 2 journald, journalctl -u, log priority; instance role of module 2. Importance:★★★★ (Without logs and indicators, there is no basis for troubleshooting)

What: What is CloudWatch Agent

A daemon (amazon-cloudwatch-agent.service) running on the instance, reading a JSON configuration, periodically collecting metrics from the operating system (calling PutMetricData to write to CloudWatch Metrics, the default namespace is CWAgent) and log (calling PutLogEvents to write Log group/log stream for CloudWatch Logs). Credentials come from the instance role (CloudWatchAgentServerPolicy), obtained via IMDSv2.

Why: Default indicators are not enough

MetricsEC2 default (AWS/EC2, no Agent required)Requires Agent (CWAgent)
CPUCPUUtilization, burst instance's CPUCreditBalanceBroken down by core, iowait, steal, etc.
Memory✗ Cannot seemem_used_percent
Filesystem✗ Not visible (EBS only IOPS/Throughput, on AWS/EBS)disk_used_percent (by mount point)
Network / Status checkNetworkIn/Out, StatusCheckFailed_*TCP connection count (netstat)
Process✗procstat (by process name/pid file)
Log✗ (only console output)journald, text file

How: Configuration file structure (verified fields)

  • agent: metrics_collection_interval, logfile, run_as_user (if not written, run as root; if used as non-root user such as cwagent, read journald, you need to add it to the systemd-journal group).
  • metrics: namespace (default CWAgent), append_dimensions (only supported ImageId/InstanceId/InstanceType/AutoScalingGroupName; after use it no longer comes with the hostname dimension), metrics_collected (mem, disk, cpu, procstat...).
  • logs.logs_collected.files.collect_list[]: file_path, log_group_name, log_stream_name (available {instance_id}, {hostname}, {ip_address}), retention_in_days.
  • logs.logs_collected.journald.collect_list[] (Linux only): units (supports wildcards, such as ["sshd*"]), priority (default info, i.e. info and more serious), matches (press _SYSTEMD_UNIT, _UID and other field filtering), filters (include/exclude regular), retention_in_days. After the Agent restarts, it will continue from the last cursor read, and the historical log will not be replenished.

The configuration can be placed in a local file or in the SSM Parameter Store (when the name starts with AmazonCloudWatch-, CloudWatchAgentServerPolicy has allowed reading), and use fetch-config -c ssm:AmazonCloudWatch-linux-lab to deliver it to the entire group of instances. Agent will convert JSON into internal TOML (/opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.toml) before running.

When: What to collect and how long to keep

DataRecommendationsCost tips
Application log (myapp)journald is collected by unit, priority infoBilled by ingested GB (ca-central-1 is about 0.5 USD/GB)
System logOnly collected err and above, or only use key units (sshd, kernel)Full journald can easily count GB every day
Memory/diskOnce every 60 seconds, only using the InstanceId dimensionEach indicator × dimension combination is a custom indicator, billed monthly
Retention periodExperiment 1–7 days, production according to compliance requirementsNew log groups never expire by default, be sure to set it
Comparison with Lesson 3Azure Monitor Agent uses DCR (data collection rules) to centrally define what to collect in the cloud; CloudWatch Agent's "DCR" is this JSON, which is usually placed in SSM parameters and is associated with State Manager for batch delivery.
Common misunderstandings① "There will be memory indicators after the Agent is installed" - it must be declared in the configuration metrics_collected mem. ② "AL2023 cannot receive system logs without /var/log/messages" - AL2023 only uses journald by default, just use journald for input, and there is no need to install rsyslog. ③ "Agent uses my SSO permissions" - the Agent on the instance uses the instance role; if it is missing, AccessDenied will appear in the Agent log. ④ "Write the alarm dimensions as you like" - the dimensions must be exactly the same as those actually released by the Agent (if logs:PutLogEvents AccessDenied will appear in the Agent log. ④ "Write the alarm dimensions as you like" - the dimensions must be exactly the same as those actually released by the Agent (used append_dimensions is used, there is only InstanceId; the disk indicator also comes with path/device/fstype).

Architecture diagram: from journald to CloudWatch

instance linux-lab myapp.servicegunicorn stdout/stderr valkey.serviceLog /var/log/cloud-init-output.log /proc/meminfostatfs(/, /data) journaldCursor amazon-cloudwatch-agent inputs: journald / files / mem / diskBatch buffer + retryCredentials: IMDSv2 → Instance roleConfiguration: JSON → TOMLSelf log:/opt/aws/amazon-cloudwatch-agent/logs/…agent.log CloudWatch Logs/linux-lab/myapp → Stream i-0123…/linux-lab/cloud-initReserved for 7 days · Logs Insights CloudWatch MetricsCWAgent / mem_used_percentCWAgent / disk_used_percent→ Alarm → SNS PutLogEvents PutMetricData
Figure 5-1 Agent reads journald Cursor, file offset and kernel statistics, batch calls to CloudWatch API

Flowchart: Configuration delivery method

Write JSONor run the configuration wizard SSM parametersAmazonCloudWatch-linux-lab fetch-config-m ec2 -c ssm:… -s Agent restartTOML takes effect Scale: SSM State Manager associates AmazonCloudWatch-ManageAgent documents and delivers them uniformly to instances selected by tags
Figure 5-2 Single machine uses local files, multiple machines use SSM Parameters + State Manager

Animation: The journey of a line of myapp logs and a memory data point

Demo gunicorn writes stdout → journald storage (with _SYSTEMD_UNIT=myapp.service) → Agent reads by cursor → batch PutLogEvents; at the same time mem input reads /proc/meminfo → PutMetricData. Real faults can be injected.

myappstdout journaldField + Cursor CW AgentFilter/Batch IMDSv2 CredentialsInstance Role CloudWatchLogs / Metrics

Core Command

CommandFunctionInstructions
sudo dnf install -y amazon-cloudwatch-agentAL2023 installationUbuntu download https://amazoncloudwatch-agent.s3.amazonaws.com/ubuntu/amd64/latest/amazon-cloudwatch-agent.deb
…/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -c file:… -sLoad configuration and start-c ssm: parameter name; -a append-config Overlay multiple configurations
…-ctl -a status / -a stopStatus/stopOutput JSON, including configstatus
…/bin/amazon-cloudwatch-agent-config-wizardInteractively generate configurationOptional to save SSM parameters
aws logs tail --follow --since 10mView logs in real time on this machine--filter-pattern
aws logs put-retention-policySet retention periodExisting log groups will not be automatically changed by the Agent (unless configured retention_in_days)
aws cloudwatch get-metric-statistics / put-metric-alarmQuery indicators/create alarmsDimensions must match exactly

Agent configuration (~/linuxlab/aws/cwagent.json)

{
  "agent": { "metrics_collection_interval": 60 },
  "metrics": {
    "namespace": "CWAgent",
    "append_dimensions": { "InstanceId": "${aws:InstanceId}" },
    "metrics_collected": {
      "mem":  { "measurement": ["mem_used_percent"] },
      "disk": { "measurement": ["used_percent"], "resources": ["/", "/data"],
                "ignore_file_system_types": ["sysfs", "devtmpfs", "tmpfs"] }
    }
  },
  "logs": {
    "logs_collected": {
      "journald": {
        "collect_list": [
          { "log_group_name": "/linux-lab/myapp", "log_stream_name": "{instance_id}",
            "units": ["myapp", "valkey"], "priority": "info", "retention_in_days": 7 },
          { "log_group_name": "/linux-lab/system-errors", "log_stream_name": "{instance_id}",
            "priority": "err", "retention_in_days": 7 }
        ]
      },
      "files": {
        "collect_list": [
          { "file_path": "/var/log/cloud-init-output.log", "log_group_name": "/linux-lab/cloud-init",
            "log_stream_name": "{instance_id}", "retention_in_days": 7 }
        ]
      }
    }
  }
}

Logs Insights: Find recent errors in myapp

fields @timestamp, @message
| filter @message like /(?i)(error|traceback|exception)/
| sort @timestamp desc
| limit 20

Lab 5: Collect myapp Log and memory/disk metrics, and create alarms (about 8 minutes, cost < 0.05 USD)

Save configuration into SSM parameters(native; first save the JSON of the "Command" page as ~/linuxlab/aws/cwagent.json):
cd ~/linuxlab/aws && source hour4.env
python3 -m json.tool cwagent.json > /dev/null && echo "JSON OK"
aws ssm put-parameter --name AmazonCloudWatch-linux-lab --type String --overwrite \
  --value file://cwagent.json --tags Key=Name,Value=$LAB 2>/dev/null || \
aws ssm put-parameter --name AmazonCloudWatch-linux-lab --type String --overwrite --value file://cwagent.json

--overwrite with --tags cannot be used for existing parameters at the same time, so the second item is used as a fallback when updating.

Install and start the Agent on the instance (remotely executed via SSM, without logging in):
CTL=/opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl
CMD=$(aws ssm send-command --instance-ids $IID --document-name AWS-RunShellScript \
  --parameters "{\"commands\":[\"dnf install -y amazon-cloudwatch-agent\",\"$CTL -a fetch-config -m ec2 -c ssm:AmazonCloudWatch-linux-lab -s\",\"$CTL -a status\"]}" \
  --query Command.CommandId --output text)
sleep 25; aws ssm get-command-invocation --command-id $CMD --instance-id $IID --query StandardOutputContent --output text | tail -12
…
{
  "status": "running",
  "starttime": "2026-11-17T14:52:10+00:00",
  "configstatus": "configured",
  "version": "1.300071.0"
}
Generate logs and view them locally:
for i in 1 2 3; do aws ssm send-command --instance-ids $IID --document-name AWS-RunShellScript \
  --parameters 'commands=["curl -s localhost:5000/ >/dev/null; logger -t myapp-test hello-from-ssm"]' >/dev/null; done
aws ssm send-command --instance-ids $IID --document-name AWS-RunShellScript --parameters 'commands=["systemctl restart myapp"]' >/dev/null
sleep 30
aws logs tail /linux-lab/myapp --since 10m | tail -5
aws logs describe-log-groups --log-group-name-prefix /linux-lab --query 'logGroups[].[logGroupName,retentionInDays]' --output table
2026-11-17T14:54:01 i-0123456789abcdef0 Stopping myapp.service - myapp (Flask + gunicorn)...
2026-11-17T14:54:01 i-0123456789abcdef0 [2026-11-17 14:54:01 +0000] [2051] [INFO] Handling signal: term
2026-11-17T14:54:02 i-0123456789abcdef0 Started myapp.service - myapp (Flask + gunicorn).
2026-11-17T14:54:02 i-0123456789abcdef0 [2026-11-17 14:54:02 +0000] [3310] [INFO] Listening at: http://0.0.0.0:5000 (3310)
|  /linux-lab/cloud-init        |  7 |
|  /linux-lab/myapp             |  7 |
|  /linux-lab/system-errors     |  7 |

Note that logger -t myapp-test's message will not appear in /linux-lab/myapp because it does not belong to the myapp.service unit - this is the effect of units filtering

View memory indicators and create alarms:
aws cloudwatch list-metrics --namespace CWAgent --dimensions Name=InstanceId,Value=$IID --query 'Metrics[].[MetricName,Dimensions[].Name]' --output text
aws cloudwatch put-metric-alarm --alarm-name linux-lab-mem-high --namespace CWAgent --metric-name mem_used_percent \
  --dimensions Name=InstanceId,Value=$IID --statistic Average --period 300 --evaluation-periods 2 \
  --threshold 80 --comparison-operator GreaterThanThreshold --treat-missing-data breaching
aws cloudwatch describe-alarms --alarm-names linux-lab-mem-high --query 'MetricAlarms[0].StateValue'
mem_used_percent	InstanceId
disk_used_percent	InstanceId	path	device	fstype
disk_used_percent	InstanceId	path	device	fstype
"INSUFFICIENT_DATA" (changes to "OK")

--treat-missing-data breaching: The agent will also alarm when it stops reporting, which itself is a kind of "Agent survival" monitoring

Cleaning: Keep Agent. Unify the cleanup with the log group to module 8 (log groups, alarms, and SSM parameters are all in the cleanup list).

Case 1: The log bill increased tenfold in a month

Problem: In order to "collect them all", a journald without units/priority was configured. Collection items, and no retention period is set. After a certain service turns on debug, the log ingestion and storage costs skyrocket. Method: Split the collection items by unit, and only use err at the system level; use filters to exclude health check access logs; set retention_in_days for all log groups; IncomingBytes Create an alarm. Limitations: Filtering too hard will lose troubleshooting clues, and the application side should control the log level.

Case 2: The disk is full, causing the database to crash, but there is no alarm

Problem:The team only monitors CPUUtilization, and /data is full. Valkey cannot be persisted. Method: Agent collects disk_used_percent (resources include /data), and sets an 85% alarm for the path=/data indicator; cooperates with the online expansion process of module 3. Restrictions: The disk indicator dimension includes device, and the device name changes (nvme1n1 → nvme2n1) will generate a new time series, and the alarm needs to use indicator mathematics or aggregation by path (aggregation_dimensions)

Case 3: Unified configuration of thousands of instances

Problem: Each team manually maintains Agent. Configuration, different formats. Method: The platform team maintains several SSM parameters (basic, web, database), uses State Manager to associate the AmazonCloudWatch-ManageAgent document and distribute it according to the tag, and append-config overlays the team's own part. Restrictions: If there is a conflict between log groups/indicators with the same name, the namespace needs to be agreed upon.

Common errors and solutions

E! cloudwatchlogs: … AccessDeniedException: User: arn:aws:sts::…:assumed-role/linux-lab-ec2-role/i-… is not authorized to perform: logs:PutLogEvents

Cause: The instance role is not attached to CloudWatchAgentServerPolicy (or the custom policy is missing logs:CreateLogGroup/CreateLogStream/PutLogEvents; setting the retention period is also required logs:PutRetentionPolicy).

sudo tail -n 30 /opt/aws/amazon-cloudwatch-agent/logs/amazon-cloudwatch-agent.log
aws iam list-attached-role-policies --role-name linux-lab-ec2-role

Fix: Credentials can be refreshed within a few minutes after attaching the policy, without restarting the instance (you can restart the Agent to speed up).

configstatus: not configured / Configuration validation first phase failed

Cause:JSON syntax error, misspelled fields (such as log_group), SSM The parameter name is incorrect or the role does not have permission to read (the default policy does not allow the parameter name if it does not start with AmazonCloudWatch-).

python3 -m json.tool cwagent.json
sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -c file:/tmp/cwagent.json
sudo cat /opt/aws/amazon-cloudwatch-agent/logs/configuration-validation.log
The log group has been created, but there is no log for myapp

Reason:units The name does not match the unit; the log priority is lower than the configured one priority; The Agent is running as a non-root user but not in the systemd-journal group; the Agent is not running before the log is generated (the history is not restored)

journalctl -u myapp -n 3 -o verbose | grep -E "_SYSTEMD_UNIT|PRIORITY"
ps -o user= -C amazon-cloudwatch-agent; id cwagent 2>/dev/null
The alarm always INSUFFICIENT_DATA
Reason: The alarm dimension is inconsistent with the actual published one (for example, the host dimension is also included, or path/device/fstype is omitted); the namespace is written incorrectly; the indicator has not been generated yet. Repair: First aws cloudwatch list-metrics --namespace CWAgent. Look at the real dimension combination and click it to create an alarm.

Command line operation questions
1. Continue to check the logs containing "ERROR" in /linux-lab/myapp.
aws logs tail /linux-lab/myapp --follow --filter-pattern ERROR
2. The log group retention period for the /linux-lab/ prefix is changed to 3 days.
for g in $(aws logs describe-log-groups --log-group-name-prefix /linux-lab/ --query 'logGroups[].logGroupName' --output text); do
  aws logs put-retention-policy --log-group-name "$g" --retention-in-days 3
done
Scenario analysis question
Agent status is running, the indicators are normal, but the journald log only appears for a short period and then stops after the Agent restarts. Possible reasons and troubleshooting?

① Whether there is PutLogEvents current limit/denial (ThrottlingException, InvalidSequenceToken, AccessDenied) in the Agent's own log; ② Whether journald rotation/vacuum causes cursor failure (journalctl --disk-usage, SystemMaxUse of /etc/systemd/journald.conf); ③ Whether the log event timestamp exceeds the range accepted by CloudWatch (instance clock drift, check chronyc tracking); ④ Whether a single log is too large and truncated; ⑤ Whether subsequent logs are accidentally excluded by the filters regularity. → Time synchronization → journald status → Check the configuration sequence.

Verified teaching video

▶
Install the Amazon CloudWatch Agent and Log to CloudWatch Logs — Digital Cloud Training
English · Installing Agent and configuring file log collection (the video does not cover journald input, which is subject to the configuration of this lesson)
▶
Setting Up CloudWatch Agent on EC2: From Basic to Advanced Metrics | Amazon EC2 — Rahul Nath
English · Custom indicators and dimensions such as memory/disk

Official documentation

Video storyboard script (about 80 seconds)

This courseware cannot directly generate video/MP3. Storyboards and explanation scripts have been provided, which can be generated by video tools.

Shot 1 · 0–20s
Screen: The EC2 console indicator page only has CPU and network curves, and the locations of memory and disk are question marks.
Narration: EC2 cannot see inside the operating system from outside the host, and requires an Agent for memory and disk usage.
Shot 2 · 20–45s
Screen: A line of logs from myapp falls into journald, the Agent reads it out with the cursor bookmark, packages it and flies to the log group of CloudWatch Logs.
Narration: Agent reads journald by unit, remembers where it is read, and sends it in batches. After restarting, continue from the bookmark, and the history will not be restored.
Shot 3 · 45–65s
Screen: /proc/meminfo The number becomes a point, falling on the mem_used_percent curve of the CWAgent namespace, and the alarm bell sounds when it crosses the 80% red line.
Narration: Indicators are written into the CWAgent namespace, and the dimensions of the alarm must be exactly the same as the published dimensions.
Shot 4 · 65–80s
Screen: Log group setting interface, the retention period is changed from "never expires" to 7 days, and the billing numbers decrease.
Narration: The new log group will never expire by default. Remember to set the retention period.
Or score ≥ 70% on the Quiz

Module 6 · Patch and Compliance: SSM Patch Manager

37:00 – 45:00 · Why AL2023 on dnf upgrade Display "No updates available"? Versioned Warehouse, Patch Baseline and Controlled Upgrades
8 minutesAL2023 Versioned WarehouseAWS-AmazonLinux2023DefaultPatchBaseline★★★★
Learning Objectives
  • Explanation of AL2023 Deterministic upgrade (versioned repository): By default, the instance is locked at the repository version when the AMI was built, and dnf upgrade will not exceed it; use dnf check-release-update and --releasever to actively upgrade.
  • Name the components of Patch Manager: patch baseline (approval rules, severity levels, automatic approval delays), AWS-RunPatchBaseline's Scan/Install, RebootOption, compliance reporting.
  • Perform scanning and installation on the experimental instance, use dnf needs-restarting -r to determine whether a restart is needed, and compare it with Ubuntu's unattended-upgrades.
Prerequisite knowledge:Lesson 1 dnf/apt basics, Lesson 2 systemd restart impact; Module 4 send-command. Importance:★★★★ (Most intrusions exploit known vulnerabilities)

What: AL2023 versioned repository

AL2023 is released each time (approximately one build per week, one minor version per quarter, currently 2023.12) will produce a new repository version and a set of AMIs locked to that version. By default, the dnf of an instance is locked at the repository version of the AMI used to launch: 100 instances launched with the same AMI will get the same package version no matter which day they execute dnf install. This is "deterministic upgrades" and is enabled by default.

  • dnf check-update / dnf upgrade: Only look for updates within the currently locked version (usually none).
  • dnf check-release-update: Lists updated repository versions and gives upgrade command examples.
  • dnf upgrade --releasever=2023.12.20261112: Upgrade to the specified version; after completion, it becomes the default version of dnf in the future. --releasever=latest means the latest.
  • Old version repositories are still available, so you can "lock on tested versions".

Why: Why Patch Manager

  • Manual dnf upgrade for one machine is no problem, a thousand machines require: unified approval rules (only install Critical/Important security patches? 7 days delay?), maintenance window, batching, restart strategy, compliance report (who is missing what patch).
  • The audit requires "prove that all instances have repaired high-risk vulnerabilities within N days", and Patch Manager's compliance data can be exported directly.

How: How Patch Manager works on AL2023 (verified)

  1. You associate the instance to a patch baseline (if not specified, the operating system's default baseline is used). AL2023 Predefined Baseline AWS-AmazonLinux2023DefaultPatchBaseline: Approvals patches classified as Security and severity level Critical/Important, as well as Bugfix patches, automatically approved 7 days after release.
  2. Run AWS-RunPatchBaseline through Run Command, Maintenance Window, State Manager, or Quick Setup patch policy: Operation=Scan only evaluates and reports compliance; Operation=Install installs approved patches.
  3. On AL2023, Patch Manager obtains the latest locked repository version, calculates the packages to be installed according to the baseline rules (Global Filter → Approval Rules → Explicit Approval/Deny List), and installs them using the DNF API. The effect of the predefined baseline is equivalent to: sudo dnf upgrade-minimal --sec-severity=Critical --sec-severity=Important --bugfix -y (when "Include non-security updates" is checked, it is equivalent to dnf upgrade --security … and includes other repository updates).
  4. If there is an update after installation, the default RebootOption=RebootIfNeeded will restart; NoReboot will not restart, and InstalledPendingReboot will be displayed in the compliance status.
  5. The results are written to Systems Manager compliance (describe-instance-patch-states, list-compliance-items).

Details: AL2023 supports severity level None; Medium in the baseline is equivalent to Moderate in the external repository; Patch Manager may install the latest version for transitive dependencies, while dnf upgrade-minimal installs the minimum satisfactory version - the results of the two may be slightly different.

When: Select patching method

ScenarioRecommendedDescription
Immutable infrastructure (ASG, short life cycle)Replace instead of patch: Refresh instances with the latest AMI weeklyWork with resolve:ssm or Image Builder
Long-running "pet" instances (this lesson)Patch Manager weekly Scan, monthly maintenance window InstallEnsure that the service can start automatically (systemctl is-enabled) before restarting
Needs to be strictly reproducibleLock --releasever, and then proceed after verification in the test environmentCustom baseline + explicit approval list
Ubuntu (control)unattended-upgrades (security updates installed by default) + Patch Manager compliance scanUbuntu baseline AWS-UbuntuDefaultPatchBaseline
Common misunderstandings① “dnf upgrade Showing Nothing to do is the latest" - just "the latest within the current locked version". ② "Patch Manager only installs security patches so there is no need to test" - Bugfix will also be approved, and kernel updates need to be restarted and still need to be done in batches. ③ "It is safe without restarting after Installing" - the new kernel and glibc/openssl will not take effect before restarting (or restarting related services), dnf needs-restarting -r will tell you. ④ "AL2023 will automatically install security updates" - No, new security updates will not be automatically applied at startup, and you need to actively handle it.

Architecture diagram: Patch Manager Components

Patch BaselineAWS-AmazonLinux2023Default…Security: Critical/Important+ Bugfix · Automatic approval after 7 days SchedulingQuick Setup Patch StrategyMaintenance Window / State ManagerRun Command (this lesson) AWS-RunPatchBaselineOperation = Scan | InstallRebootOption =RebootIfNeeded | NoRebootExecuted by SSM Agent Instance (AL2023)Latest locked repository versionupdateinfo.xml (Security Bulletin)DNF API Installation → Restart if needed Compliance ReportInstalled / Missing / FailedInstalledPendingRebootCompliance / Patch Manager Console
Figure 6-1 The baseline defines "what to install", the schedule defines "when to install", and the document is "executed and reported" on the instance

Timeline: Versioned repository and locking

2023.12.20261012AMI build · The instance is locked here 2023.12.20261021 2023.12.20261102 2023.12.20261112(latest) dnf upgrade: Nothing to do (no updates within the lock) dnf upgrade --releasever=2023.12.20261112 → New lock point Patch Manager: Take the latest locked version and only install patches that have been approved by the baseline (if released for more than 7 days)
Fig. 6-2 Versioned repository: Upgrade is an explicit "moving lock point"

Animation: a patch cycle

Starting from the instance being locked in the old repository version, demonstrate check-release-update → Patch Manager Scan (approval rule filtering) → Install → Restart judgment → Compliance reporting. Toggleable restart option with "Include non-security updates".

Warehouse lock point
—
Patch assessment
—
Compliance status
—

Core Commands

CommandFunctionDescription
cat /etc/amazon-linux-release; rpm -q system-releaseCurrent release build/locked versionAMI Build version number
sudo dnf check-release-updateWhether there is a newer repository versionOutput including recommended commands
dnf check-update --releasever=latestPreview which packages will be updated when upgrading to the latestDo not change the lock point
sudo dnf upgrade --releasever=Upgrade and move lockpoint-y non-interactive
dnf updateinfo list --security --releasever=latestList security advisories (ALAS)--sec-severity=Critical
sudo dnf needs-restarting -rWhether restart is requiredExit code 1 = required
sudo dnf supportinfo --pkg valkeySoftware package support periodAL2023 specific plug-in
aws ssm send-command --document-name AWS-RunPatchBaselineScan / InstallOperation, RebootOption
aws ssm describe-instance-patch-statesPatch compliance summaryInstalled/Missing/Failed Count
aws ssm describe-instance-patchesPatch-by-patch status--filters Key=State,Values=Missing

View locked vs. available versions on instance

cat /etc/amazon-linux-release
rpm -q system-release kernel6.18 2>/dev/null || rpm -q system-release
sudo dnf check-release-update
dnf check-update --releasever=latest | tail -5
dnf updateinfo list --security --releasever=latest | head
Amazon Linux release 2023.12.20261102 (Amazon Linux)
system-release-2023.12.20261102-0.amzn2023.noarch
WARNING:
  A newer release of "Amazon Linux" is available.

  Available Versions:

  Version 2023.12.20261109:
    Run the following command to upgrade to 2023.12.20261109:

      dnf upgrade --releasever=2023.12.20261109
  …
  Version 2023.12.20261112:
    Run the following command to upgrade to 2023.12.20261112:

      dnf upgrade --releasever=2023.12.20261112
curl-minimal.x86_64        8.21.0-5.amzn2023.0.5      amazonlinux
amazon-ssm-agent.x86_64    3.3.5828.0-1.amzn2023      amazonlinux
…

How to verify: After upgrade cat /etc/amazon-linux-release displays the new version. Common mistakes: Directly --releasever=latest in production without verifying it in the test environment; forgetting to restart causes the new kernel to not take effect. Production use: Use "target releasever" as part of the change order, test first and then push.

Experiment 6: Scan for patch compliance, install and determine restart (about 8 minutes, cost ≈ 0)

Tip: If your instance comes from the latest AMI, there may be no patch available for installation. It is normal for Missing in the output to be 0; you can use the older fixed kernel AMI parameters to restart one to practice (remember to add the Name=linux-lab tag).

View the lock status on the instance (the first three items of the "Command" page executed in Session Manager), record the current version.
Scan (evaluate only):
cd ~/linuxlab/aws && source hour4.env
aws ssm describe-patch-baselines --filters Key=OWNER,Values=AWS --query "BaselineIdentities[?OperatingSystem=='AMAZON_LINUX_2023'].[BaselineName,DefaultBaseline]" --output text
CMD=$(aws ssm send-command --instance-ids $IID --document-name AWS-RunPatchBaseline \
  --parameters Operation=Scan --query Command.CommandId --output text)
aws ssm wait command-executed --command-id $CMD --instance-id $IID
aws ssm describe-instance-patch-states --instance-ids $IID \
  --query 'InstancePatchStates[0].[BaselineId,InstalledCount,MissingCount,FailedCount,InstalledPendingRebootCount,OperationEndTime]'
AWS-AmazonLinux2023DefaultPatchBaseline	True
[ "pb-0123456789abcdef0", 412, 3, 0, 0, "2026-11-17T15:05:41+00:00" ]
Check which patches are missing:
aws ssm describe-instance-patches --instance-id $IID --filters Key=State,Values=Missing \
  --query 'Patches[].[Title,Classification,Severity]' --output table
|  curl-minimal.x86_64:0:8.21.0-5.amzn2023.0.5   |  Security |  Important |
|  libcurl-minimal.x86_64:0:8.21.0-5.amzn2023.0.5|  Security |  Important |
|  rpm.x86_64:0:4.16.1.3-29.amzn2023.0.10        |  Bugfix   |  None      |
Install but do not restart first:
CMD=$(aws ssm send-command --instance-ids $IID --document-name AWS-RunPatchBaseline \
  --parameters Operation=Install,RebootOption=NoReboot --query Command.CommandId --output text)
aws ssm wait command-executed --command-id $CMD --instance-id $IID
aws ssm describe-instance-patch-states --instance-ids $IID --query 'InstancePatchStates[0].[MissingCount,InstalledPendingRebootCount]'
[ 0, 3 ]
Judge and execute restart, verify that the service starts automatically:
aws ssm send-command --instance-ids $IID --document-name AWS-RunShellScript \
  --parameters 'commands=["dnf needs-restarting -r; echo exit=$?","cat /etc/amazon-linux-release"]' --query Command.CommandId --output text
# If exit=1, restart is required:
aws ec2 reboot-instances --instance-ids $IID
aws ec2 wait instance-status-ok --instance-ids $IID
aws ssm start-session --target $IID --document-name AWS-StartPortForwardingSession --parameters '{"portNumber":["5000"],"localPortNumber":["5000"]}'
# Another terminal: curl -s localhost:5000/ → hits continue to increase (Valkey data is in /data)
Contrast (optional): Manually upgrade to the latest locking point: sudo dnf upgrade -y --releasever=latest, and then cat /etc/amazon-linux-release. Note that this will load updates that the baseline has not yet approved (less than 7 days old) - this is the difference between "manual" and "policy".
Cleaning: This experiment does not add new billing resources. Compliance data becomes invalid when the instance is terminated.

Case 1: Vulnerability scan says "CVE", but dnf says "No update"

Problem: The security team's scanner reports openssl high-risk vulnerability, but the operation and maintenance execution dnf upgrade shows Nothing to do. Reason: The instance is locked in a repository version half a year ago. Method:dnf check-release-update Confirm the new version, test the environment --releasever= to upgrade and verify, and then use Patch Manager (get the latest locked version) to push to production; in the long term, replace it with a new AMI every month. Limitations: The amount of upgrade changes across many versions is large, so a rollback plan (snapshot/new instance) must be reserved.

Case 2: The application does not run after the patch

Problem: After the maintenance window is automatically installed and restarted, myapp on a batch of instances does not run. The reason is that someone manually systemctl start myapp and never enable. Practice: Use State Manager / Run Command to check systemctl is-enabled before patching; run the "health check" document after Patch Manager is installed (subsequent tasks of Run Command or maintenance window); use health check instead in ASG environment. Limitations: Patch Manager is only responsible for patches and does not verify applications.

Case 3: Batch and Approval

Problem: Patching 500 instances at one time caused a sudden drop in service capacity. Method: Divide the instance into canary / wave1 / wave2 according to the tag PatchGroup (or the target of the Quick Setup patch strategy), set the concurrency and error thresholds for the maintenance window; set the "automatic approval delay" to 7 days in the custom baseline to allow time for testing, and use an explicit approval list for urgent vulnerabilities. Restrictions: The patch strategy and maintenance window configuration methods are frequently updated in the console, please refer to the official documentation.

Common errors and solutions

Last metadata expiration check … Dependencies resolved. Nothing to do. Complete! (but the scanner reported a vulnerability)

Reason: Versioned repository lock. Fix:sudo dnf check-release-update; sudo dnf upgrade --releasever=, or run Patch Manager Install.

AWS-RunPatchBaseline failed: Errors were found while downloading patches / Curl error (28): Timeout was reached for https://al2023-repos-ca-central-1-….s3.dualstack.ca-central-1.amazonaws.com/…

Cause:The instance cannot access the AL2023 repository (the repository is hosted on region S3). The private subnet has no NAT and no S3 gateway endpoint; or the S3 endpoint policy restricts the bucket.

sudo dnf repolist -v | grep -i baseurl
REPOHOST=$(sudo dnf repolist -v 2>/dev/null | awk -F/ '/Repo-(baseurl|mirrors)/{print $3; exit}')
curl -sI "https://$REPOHOST/" | head -1      # If you can get the HTTP status line, it means the network is reachable

Fix: Add S3 gateway endpoint and allow access to AL2023 repository bucket, or provide NAT.

describe-instance-patch-states returns an empty list

Reason: Scan/Install has never been successfully run; the instance is not a managed node; the query region is incorrect. Fixed: Make sure describe-instance-information is Online, run Operation=Scan once, and use get-command-invocation to see the output.

The compliance status is InstalledPendingReboot / NON_COMPLIANT for a long time

Reason: There is no restart after installation using NoReboot. Fix: Restart in the maintenance window (or RebootIfNeeded), and then scan to refresh compliance.

dnf: Error: Unable to find a match / Dependency conflict (after upgrading --releasever)

Cause: The third-party repository (such as Docker CE, vendor repository) conflicts with the new version, or the package has been renamed/abandoned (such as a package that has ended support). Fix:dnf upgrade --releasever=… --exclude= Exclude it first, check dnf supportinfo and release notes, and migrate to alternative packages (such as redis6 → valkey).

Command line operation questions
1. Without changing the locking point, check which security-related software packages (Critical) will be updated when upgrading to the latest version.
dnf updateinfo list --security --sec-severity=Critical --releasever=latest
2. Perform a patch scan on all instances of the Name=linux-lab tag.
aws ssm send-command --document-name AWS-RunPatchBaseline --targets Key=tag:Name,Values=linux-lab \
  --parameters Operation=Scan --max-concurrency 50% --max-errors 1
Scenario Analysis Question
You are responsible for 40 long-running AL2023 instances (3 applications). High-risk vulnerabilities are required to be fixed within 14 days and all instances of the same application cannot be restarted at the same time. Design a patch plan.

① Customized baseline: Security Critical/Important + Bugfix, automatic approval is delayed for 3 days (allow test time to meet the 14-day requirement); ② Label by application and batch (App, Wave=canary/1/2); ③ Weekly Scan (State Manager), two maintenance windows each week canary, wave1/wave2 execute Install + RebootIfNeeded, max-concurrency is controlled to be ≤ 1/3 for each application; ④ Run the health check document after installation, and if it fails, stop subsequent batches (error threshold); ⑤ Compliance dashboard and alarm tracking Missing Critical number and number of days; ⑥ Long-term direction: bake AMI + instance refresh, reduce in-place patches.

Verified instructional video

▶
Back to Basics: Automating Patching of EC2 Instances Using Systems Manager — Amazon Web Services
English · AWS official Back to Basics series · Patch baseline, maintenance window and overall compliance architecture
▶
Automate Patching with AWS Systems Manager Quick Setup Patch Policy — Amazon Web Services
English · AWS official · Use Quick Setup patch strategy to do organizational-level patches

Official documents

Video storyboard script (about 80 seconds)

This courseware cannot directly generate video/MP3. Storyboards and explanation scripts have been provided, which can be generated by video tools.

Shot 1 · 0–20s
Screen: A row of repository versions on the timeline, the instance is tied to the old version on the left by a rope, dnf upgrade shows Nothing to do.
Narration: AL2023 locks the instance in the repository version corresponding to the AMI by default, and dnf will not cross it by itself.
Shot 2 · 20–45s
Screen: dnf check-release-update lists new version, admin moved the rope to 2023.12.20261112.
Narration: Upgrading is an explicit operation: first check what new versions are available, and then use releasever to move the lock point.
Lens 3 · 45–65s
Screen: The patch baseline is like a sieve, only allowing patches that are "security, critical or important" and "defect fixes" and are seven days old to pass.
Narration: Patch Manager uses the baseline to decide what to install and the maintenance window to decide when to install it.
Shot 4 · 65–80s
Screen: Compliance dashboard changes from red Missing to yellow pending restart, then back to green.
Narration: Complete installation does not mean it takes effect, the new kernel needs to be restarted. Compliance reports will tell you what’s missing.
Or score ≥ 70% on the Quiz

Module 7 · Troubleshooting on the cloud: EC2 serial console, status checks and common faults

45:00 – 54:00 · The instance is "running" but cannot be connected: first check the status check, then look at the console output, and finally enter the serial console or rescue the instance
9 minutesNitro · ttyS0The serial console needs to be enabled at the account level★★★★★
Learning objectives
  • Distinguish between system status checks (AWS side: host, network, power), instance status checks (your operating system: network configuration, kernel, file system, memory), mount EBS status checks (volume I/O reachability), and know how to handle each.
  • You can see the startup log without logging in to the instance: get-console-output --latest, get-console-screenshot; use EC2 serial console to fix when neither SSM nor SSH is available.
  • Learn the diagnostic paths for common failures (fstab, disk full, kernel update failure, network/SSM endpoints, OOM, CPU credits), and the method of "rescue instance" mounting the root volume.
Prerequisite knowledge:Lesson 2 systemd startup target and emergency/rescue mode, GRUB; module 3 fstab, module 4 access method. Importance:★★★★★

What: EC2 status check (verified)

EC2 performs a status check every minute, and the result is pass/fail; when all pass, the overall status of the instance is ok, and any failure is impaired. When a failure occurs, the corresponding CloudWatch indicator is incremented and can be used for alarms and automatic recovery.

CheckDetection objectsTypical reasonsWho will fix it / how to fix itIndicators
System status checkThe AWS system where the instance is locatedNetwork connection loss, power loss, host software and hardware problemsWait for AWS, or stop and restart (EBS Supported instances are typically migrated to new hosts); configurable automatic recoveryStatusCheckFailed_System
Instance status checkYour operating system and network configuration (EC2 sends ARP request to the network card)Boot failure, network configuration error, memory exhaustion, file system corruption, kernel incompatibility; failed system status check will also cause it to failYourself: Restart, modify configurationStatusCheckFailed_Instance
Mount EBS status checkWhether the mounted EBS volume is reachable and can complete I/OStorage subsystem, host or connection issuesWait, or replace volume/stop and restartStatusCheckFailed_AttachedEBS
Application status check (optional)HTTP/HTTPS response you configuredApplication unhealthyYourselfSubject to the document

Why: "Running" is not equal to "available"

Instance status running only means that the virtual machine has been allocated and powered on. A system stuck in emergency mode or a system with no network connection will also display running on the console. Status checks tell you whether the problem is on the AWS side or the OS side; console output tells you where the OS is stuck; and the serial console lets you go in and fix it without a network connection.

How: Toolbox (from shallow to deep)

ToolsNeed an instance network? Need to log in? What can be done
describe-instance-statusNoNoResults and events of three types of inspections (planned maintenance)
get-console-output --latestNoNoSerial port (ttyS0) recent output: kernel, systemd, cloud-init messages
get-console-screenshotNoNoCurrent screenshot (JPG, base64)
Session Manager / EIC / SSHYesYesGeneral troubleshooting when the system is running normally
EC2 Serial consoleNoYes (password user required)Interactive access to ttyS0: GRUB menu, emergency shell, login prompt; can also send SysRq
Rescue instanceNoNo (the disk is operated)Stop the instance → Detach the root volume → Mount to another instance in the same availability zone for modification → Mount back

EC2 serial console prerequisite (verified)

  • All Nitro-based virtualization instances and most bare metal instances are supported (t3 in this lesson is Nitro).
  • Off by default at the account level, needs to be explicitly turned on by region: aws ec2 enable-serial-console-access (Organizationally available SCP prohibition).
  • IAM permissions: ec2-instance-connect:SendSerialConsoleSSHPublicKey (can be restricted by instance tag).
  • Linux requires a OS user with a password (AL2023 default users have no password). The emergency mode shell requires a root password, so the password is temporarily set for root during the experiment and locked after completion.
  • Each instance can only have 1 serial session at the same time; the session is usually up to 1 hour; it takes about 30 seconds to create a new session after being disconnected; the pushed SSH public key is valid for 60 seconds.
  • SSH endpoint: serial-console.ec2-instance-connect.ca-central-1.aws, username format .port0.

When: Select path

PhenomenaDo it first
System check failedSee AWS Health / Scheduled Events → Stop and restart (note that instance storage will be lost)
Instance check failed, system check passedConsole output → Serial console → Rescue instance
Both checks passed, but SSM is offlineInstance role, outbound network, Agent status (EIC or serial console to check)
All passed, able to log in, but the application is unavailablesystemd / journald / CloudWatch log (Lesson 2, Module 5)
Common misunderstandings① "Reboot can change the instance to a new host" - reboot does not change the host, stop and restart. ② "Serial console can replace SSM" - it is an emergency channel and requires additional account switches, permissions and passwords, and should be strictly restricted after opening. ③ "Passing the instance check indicates that the system is normal" - it only verifies that the network card responds to ARP; systemd-networkd systems may report health before other startup tasks are completed. ④ "Disk full will only affect log writing" - will cause all exceptions in SSM Agent, sshd, dnf, and Valkey persistence.

Decision diagram: from phenomenon to tool

Instance running but unavailable System check failedAWS side Instance check failedOS side Checks all passedAccess/application layer AWS Health / scheduled eventsstop → start (change host)Automatically restore alarms get-console-output --latestget-console-screenshotDetermine which step to stop SSM Online? Role? Endpoint? Security Group/Routing/sshdsystemctl / journalctl EC2 Serial ConsoleGRUB / emergency shell Rescue InstanceMount root volume offline repair
Fig. 7-1 Layer first (AWS/OS/Access and Application), then select tools

Flowchart: Serial console connection link

Nativesend-serial-console-…key Account switch + IAMPublic key valid for 60 seconds serial-console.ec2-…ssh i-….port0@…ca-central-1.aws Nitro virtual serial port ttyS0getty / sulogin (password required) Network card and security group without instance: can also be used when the network is completely broken
Figure 7-2 The serial console uses the virtual serial port provided by Nitro, not the instance network

Interaction: Fault Injection Simulator

Play after selecting a fault: three types of status checks, SSM status, console output fragments, and the tools and repair commands that should be used are displayed in sequence. All outputs are examples, but correspond to real checking logic and real log formats.

System Check
—
Instance Check
—
EBS Check
—
SSM
—

Core Command

CommandFunctionDescription
aws ec2 describe-instance-status --instance-ids $IID --include-all-instancesThree types of status checks + planned eventsSystemStatus, InstanceStatus, AttachedEbsStatus
aws ec2 get-console-output --instance-id $IID --latest --output textRecent serial port output--latest Get the latest (Nitro Support)
aws ec2 get-console-screenshot --instance-id $IIDScreenshot--query ImageData --output text | base64 -d > shot.jpg
aws ec2 enable-serial-console-access / get-serial-console-access-status / disable-…Account level (this region) switchClose when finished
aws ec2-instance-connect send-serial-console-ssh-public-keyPush the public key and start a serial session--serial-port 0
ssh -i key $IID.port0@serial-console.ec2-instance-connect.ca-central-1.awsConnect to serial consoleConnect within 60 seconds; ~. Disconnect
aws ec2 stop-instances + start-instancesChange host (when system check fails)Public network IPv4 will change (no EIP when); the instance store is lost
sudo mount -o nouuid /dev/nvme1n1p1 /mnt/rescueMount the XFS root volume of the same AMI on the rescue instanceThe two XFS volumes have the same UUID and require nouuid

View status checks and events

aws ec2 describe-instance-status --instance-ids $IID --include-all-instances \
  --query 'InstanceStatuses[0].{state:InstanceState.Name,system:SystemStatus.Status,instance:InstanceStatus.Status,instanceDetail:InstanceStatus.Details,ebs:AttachedEbsStatus.Status,events:Events}'
{
    "state": "running",
    "system": "ok",
    "instance": "impaired",
    "instanceDetail": [ { "Name": "reachability", "Status": "failed", "ImpairedSince": "2026-11-17T15:21:00+00:00" } ],
    "ebs": "ok",
    "events": null
}

Configure automatic recovery for system check failures

aws cloudwatch put-metric-alarm --alarm-name linux-lab-auto-recover --namespace AWS/EC2 \
  --metric-name StatusCheckFailed_System --dimensions Name=InstanceId,Value=$IID \
  --statistic Maximum --period 60 --evaluation-periods 2 --threshold 1 --comparison-operator GreaterThanOrEqualToThreshold \
  --alarm-actions arn:aws:automate:ca-central-1:ec2:recover

The recovered instance retains the instance ID, private IP, EIP, and EBS volume, but the instance storage data is lost. Many current instance types also have Simplified AutoRecovery enabled by default, as determined by the instance's MaintenanceOptions.AutoRecovery.

Experiment 7: Deliberately write bad fstab, use serial console to repair (about 9 minutes, cost ≈ 0)

Safety tipsThis experiment will be discussed inThis area of ​​the experimental accountEnable serial console access and temporarily set a password for root. Be sure to perform the final recycling step at the end. Don't do this in a production account.
Preparation: enable serial console access, set root password:
cd ~/linuxlab/aws && source hour4.env
aws ec2 enable-serial-console-access
aws ec2 get-serial-console-access-status
# Instance (Session Manager):
sudo passwd root          # Enter a temporary strong password and the experiment will be locked
{ "SerialConsoleAccessEnabled": true, "ManagedBy": "account" }
Inject failure: add a row of non-existent UUID, and without nofail, and then restart:
# In instance
echo "UUID=00000000-dead-beef-0000-000000000000  /broken  xfs  defaults  0  2" | sudo tee -a /etc/fstab
sudo mkdir -p /broken
sudo systemctl daemon-reload
sudo reboot
Observe the phenomenon (local machine): After about 2–3 minutes:
aws ssm describe-instance-information --filters Key=InstanceIds,Values=$IID --query 'InstanceInformationList[0].PingStatus'
aws ec2 describe-instance-status --instance-ids $IID --query 'InstanceStatuses[0].[SystemStatus.Status,InstanceStatus.Status]'
aws ec2 get-console-output --instance-id $IID --latest --output text | grep -E "Timed out|Dependency failed|emergency" | tail -5
"ConnectionLost"
[ "ok", "impaired" ] ← Instance check usually becomes impaired after a few minutes (subject to actual situation)
[ TIME ] Timed out waiting for device dev-disk-by\x2duuid-00000000\x2ddead\x2dbeef\x2d0000\x2d000000000000.device - /dev/disk/by-uuid/00000000-dead-beef-0000-000000000000.
[DEPEND] Dependency failed for broken.mount - /broken.
[DEPEND] Dependency failed for local-fs.target - Local File Systems.
You are in emergency mode. After logging in, type "journalctl -xb" to view system logs,

Neither the network nor the SSM Agent is started in emergency mode, and the Session Manager is unavailable. This is the scenario where a serial console is required.

Connect to serial console(native; if there is no key, fix it first ssh-keygen -t ed25519 -f ~/.ssh/serial_lab -N ''):
aws ec2-instance-connect send-serial-console-ssh-public-key --instance-id $IID --serial-port 0 \
  --ssh-public-key file://$HOME/.ssh/serial_lab.pub
ssh -i ~/.ssh/serial_lab $IID.port0@serial-console.ec2-instance-connect.ca-central-1.aws
# When connecting for the first time, you will be prompted to check the service fingerprint (compared with the fingerprint of ca-central-1 in the official document); press Enter once after connecting
Give root password for maintenance
(or press Control-D to continue): 
(in serial session, after entering root password):
journalctl -xb -p err --no-pager | tail -5
sed -i '/00000000-dead-beef/d' /etc/fstab
findmnt --verify
systemctl daemon-reload
reboot
# After seeing the login: prompt, enter ~. to disconnect the serial session
Verify and reclaim emergency permissions:
aws ec2 wait instance-status-ok --instance-ids $IID && echo recovered
aws ssm start-session --target $IID
# In example:
sudo passwd -l root && sudo rmdir /broken
findmnt /data && curl -s localhost:5000/
exit
aws ec2 disable-serial-console-access
recovered
Locking password for user root.
passwd: Success
TARGET SOURCE       FSTYPE OPTIONS
/data  /dev/nvme1n1 xfs    rw,relatime,…
[aws-1.0] Hello from ip-172-31-5-23…, hits=9
{ "SerialConsoleAccessEnabled": false }
Alternative solution (understand): Rescue instance—When the serial console is not open: Stop the instance → Detach the root volume → Mount the temporary AL2023 instance in the same availability zone as /dev/sdf → sudo mount -o nouuid /dev/nvme1n1p1 /mnt/rescue → Modify /mnt/rescue/etc/fstab → Uninstall and detach → hang back the original instance as /dev/xvda → start. Remember to terminate the temporary instance.

Case 1: 30% of instances fail to start after kernel update

Problem: After restarting after a patch, some instances failed to check. The console output shows that the new kernel panics when loading third-party modules. How to do: Enter the GRUB menu through the serial console and select the previous kernel to boot; after logging in, grubby --set-default points to the old kernel and dnf versionlock (or remove the third-party module); follow up in canary Batch verification kernel update. Restrictions: You need to open the serial console in advance and prepare the password user, otherwise you can only use the rescue instance.

Case 2: The log fills the root partition, and SSM cannot connect

Problem: The application debug log fills the 8 GiB root volume, and the SSM Agent Unable to write the status file and crash repeatedly, sshd cannot create a session. Method: Native modify-volume expands the root volume; after serial console login, growpart + xfs_growfs, clears the log; long-term: journald SystemMaxUse=, logrotate, application log in independent volume, CloudWatch disk alarm (module 5). Limitations: Capacity expansion requires volume modification cooling time permission.

Case 3: System status check failed planned event

Problem: Received "instance-retirement/. system-reboot" scheduled event email, the host is about to retire. Method: Stop and then start the migration to the new host before the event expires; confirm that there is no critical data on the instance store; configure automatic recovery alarms for key instances or rely on ASG replacement. Limitations: Stopping/starting will change the public network IPv4 (when EIP is not used), and DNS needs to be updated accordingly.

Common errors and solutions

An error occurred (SerialConsoleSessionUnavailableException) / Access to the serial console is not allowed for this account

Cause:The account does not have serial console access enabled in this region, or is banned by the organization SCP. Fix:aws ec2 get-serial-console-access-status; aws ec2. enable-serial-console-access (requires appropriate permissions).

SerialConsoleSessionLimitExceededException: A session is already open for this instance

Cause: There can be only one serial session per instance at a time; the newly disconnected session takes about 30 seconds to release. Fix: Close other sessions (including those in the console browser) and wait 30 seconds before trying again.

Cannot open access to console, the root account is locked. See sulogin(8) man page for more details.

Cause:emergency mode requires root password, and AL2023/Ubuntu locks root by default. Fix:You can only rescue the instance at this time; or restart in the serial console and edit the kernel parameters in the GRUB menu (higher risk, need to be familiar with GRUB). Prevention: Set a controlled root password (stored in the password library) in advance for instances that require serial emergency or use the rescue instance process

XFS (nvme1n1p1): Filesystem has duplicate UUID … - can't mount

Cause:The rescue instance is from the same AMI as the failed instance, with the same root volume XFS UUID. Fix:sudo mount -o nouuid /dev/nvme1n1p1 /mnt/rescue.

Out of memory: Killed process 2051 (gunicorn) total-vm:… (console output/journalctl -k)

Cause: Out of memory, kernel OOM killer chooses process to terminate; t3.small is only 2 GiB and has no swap by default. Diagnosis:journalctl -k | grep -i oom, CloudWatch. mem_used_percent. Fix: Reduce gunicorn workers, set MemoryMax= to myapp.service, add swap files, or upgrade instance types.

t3 instance CPU suddenly slows down, CPUUtilization stuck at ~20%

Cause:The instance was set to standard credits mode and ran out of credits, being throttled at baseline performance (20% for t3.small baseline). Diagnosis:CPUCreditBalance metric is 0; aws ec2 describe-instance-credit-specifications Fix: Switch to. unlimited (additional charges will be incurred) or change to a non-burst instance type.

Command line operation questions
1. Find all instances in the current region whose instance check or system check is not ok.
aws ec2 describe-instance-status --filters Name=instance-status.status,Values=impaired,insufficient-data \
  --query 'InstanceStatuses[].[InstanceId,SystemStatus.Status,InstanceStatus.Status]' --output table
aws ec2 describe-instance-status --filters Name=system-status.status,Values=impaired --query 'InstanceStatuses[].InstanceId'
2. Save the current instance console screenshot to a local file.
aws ec2 get-console-screenshot --instance-id $IID --query ImageData --output text | base64 -d > linux-lab-screen.jpg
Scenario analysis
The production instance status check is impaired, the system check is healthy, and SSM reports ConnectionLost. The final console line is “Kernel panic - not syncing: VFS: Unable to mount root fs on unknown-block(0,0)”. How would you recover the instance, and how would you prevent this from happening again?

The reason is mostly that the initramfs of the new kernel is missing/damaged (the upgrade is interrupted or the disk is full). Recovery: ① If the serial console is enabled and GRUB has a timeout menu, select the previous kernel to start. After logging in, dracut -f --kver rebuild initramfs or grubby --set-default to return to the old kernel; ② Otherwise, use the rescue instance: stop the instance, detach the root volume and mount it to the rescue instance, mount -o nouuid, chroot (mount /proc /sys /dev), rebuild initramfs or modify the default kernel and hang back to boot. Prevention: Check disk space before patching, canary batches, ensure old kernels are retained (installonly_limit), critical instance pre-preparation serial console access and rescue procedures, pre-patch snapshots of critical volumes.

Verified instructional video

▶
Why is my EC2 Linux instance unreachable and failing its status checks? — Amazon Web Services
English · AWS official knowledge center video · Troubleshooting ideas for status check failure
▶
How to Enable and Use the Serial Console for AWS EC2 Instances for Linux and Window — KnowITFree
English · Enabling account-level access, setting password users and connection demonstrations
▶
AWS EC2 Instance Troubleshooting: Diagnosing Status Check Failures — Cloud Explainers
English · The difference and handling of failed system check and instance check

Official Document

Video storyboard script (about 95 seconds)

This courseware cannot directly generate video/MP3. Storyboards and explanation scripts have been provided, which can be generated by video tools.

Line 1 · 0–20s
Screen: The console shows running, and the status check 1/2 next to it turns red; when the camera is zoomed in, the system check is green and the instance check is red.
Narration: Running does not mean available. Check the AWS side for system check, and check your operating system for instance check.
Shot 2 · 20–45s
Screen: The text of get-console-output flows out of the instance and stops at You are in emergency mode.
Narration: Without logging in, the console output can tell you where the system stops. This time it's a disk that doesn't exist in fstab.
Shot 3 · 45–75s
Screen: Next to the instance where the network cable was cut, a virtual serial port cable labeled ttyS0 is connected from the Nitro card. The administrator enters the root password through it and deletes the fstab line.
Narration: The serial console does not go through the instance network and is the last channel. It requires account-level enablement, IAM permissions, and a user with a password.
Lens 4 · 75–95s
Screen: After restarting, the two checks turn green, the administrator locks the root password and turns off the serial console switch.
Narration: After repairing, take back the emergency permissions and write nofail into the specification to avoid it happening again.
Or score ≥ 70% on the Quiz

Module 8 · Cost, Cleanup, and Self-Test

54:00 – 60:00 · AWS There is no "one-click deletion of resource groups": find each billing resource by label, delete it in dependency order, and then do a residual scan
6 minutesTag Name=linux-labThe price is ca-central-1 approximate value★★★★
Learning Objectives
  • List the resources and billing methods that generate fees for this lesson: instance hours, EBS GB·month, snapshots, public network IPv4 hours, CloudWatch log ingestion/storage, custom indicators, and alarms.
  • Clean up in order of dependency: Alarm → Instance → Volumes and snapshots not deleted with the instance → Security group → Instance profile and role → Log group → SSM parameters → Account-level switches.
  • Use the Resource Groups Tagging API and describe command to do residual scanning; use the interactive troubleshooting tree to review the entire course faults.
Prerequisite knowledge: All resources created by modules 1–7. Importance:★★★★ (Legacy resources are the most common surprise in cloud bills)

What: The billing items for this course (ca-central-1 approximate price, subject to the official pricing page)

ResourcesBilling methodUsage of this lessonApproximate cost
EC2 t3.smallBilled by the second (minimum 60 seconds), about 0.023 USD/hour; no instance fee will be charged after stoppingAbout 2 Hours≈ 0.05 USD
t3 unlimited excess pointsExtra billing by vCPU·hour when high CPU is sustainedThis lesson is almost 0≈ 0
EBS gp3Based on preset capacity GB·month (about 0.088 USD), Stopped instance is still billed8 GiB root volume + 20 GiB data volume≈ 0.01 USD (2 hours)
EBS snapshotAccording to the incremental data stored GB·monthOptional≈ 0
Public IPv4About 0.005 USD/hour/address (including automatically assigned public IP and EIP)1, about 2 hours≈ 0.01 USD
CloudWatch LogsIngest by GB (about 0.5–0.6 USD/GB) + storage by GB·monthA few MB≈ 0
CloudWatch custom metrics/alarmsMetrics are prorated on a monthly basis; standard alarms are about 0.1 USD each per month3 metrics + 2 alarms< 0.01 USD
Session Manager, Patch Manager, Run Command, EIC, Serial ConsoleFor EC2 There is no additional charge for instances (advanced features and data transfer are extra)—0

Why: Why AWS cleanup is more prone to leaks than Azure

  • Azure can az group delete delete the entire resource group (Lesson 3); AWS does not have equivalent deletion boundaries, and resources are scattered across multiple services such as EC2, IAM, CloudWatch, SSM, etc.
  • Terminating the instance will only delete the volumes with DeleteOnTermination=true; the attached data volumes, snapshots, log groups, and IAM roles will all remain.
  • IAM is a global service, and log groups and parameters are regional resources - check them one by one by region and service.

How: Deletion order and dependencies

  1. CloudWatch alarm (to avoid false alarms after instance termination).
  2. Terminate the instance (label Name=linux-lab) and wait for terminated; the root volume is then deleted, the network card is released, and the public IP is released.
  3. Delete data volumes and experimental snapshots with status available.
  4. Delete the security group (must be after the network card is released, otherwise DependencyViolation).
  5. Remove the role from the instance configuration file → delete the instance configuration file → detach the hosting policy → delete the role (in the wrong order, DeleteConflict will occur).
  6. Delete /linux-lab/* log group, SSM parameters AmazonCloudWatch-linux-lab.
  7. Confirm that serial console access is closed; retain budget alerts as needed.

When: Stop or terminate?

SelectStill billedSuitable
StopEBS volume, EIP (when not associated); the automatically assigned public IP will be releasedContinue the experiment tomorrow
TerminateUndeleted data volumes, snapshots, logsEnd of course
Hibernate (hibernate)EBS (including memory mirroring)Need to retain memory status (needs to be enabled in advance)

Self-test checklist for this lesson









Common misunderstandings① "It doesn't cost money to stop the instance" - EBS, snapshots, and log storage continue to be billed. ② "Deleting the instance deletes everything" - data volumes (DeleteOnTermination=false), snapshots, IAM, logs, and parameters must be deleted separately. ③ "Use whatever you want in the free package" - the free quota rules vary depending on the time when the account is created. Public network IPv4 and the portion exceeding the quota are still charged, which is subject to the account's billing page.

Dependency graph: cleanup sequence

① Alarm ② Terminate instanceRoot volume / ENI / public IP will be released ③ Data volume (available) ③ Snapshot ④ Security group ⑤ Instance configuration fileremove-role → delete ⑤ IAM Roledetach policy → delete ⑥ Log groupSSM parameters ⑦ Residual scanSerial console shutdown Typical errors in wrong sequence: security group DependencyViolation (ENI not released), role DeleteConflict (still in the instance configuration file or still attached to the policy) IAM are global resources; volumes, snapshots, log groups, parameters, and serial console switches are all regional resources (ca-central-1)
Figure 8-1 Cleanup sequence: first "user" (instance), then "used thing" (security group, role)

Cost composition (2-hour experiment, illustration)

EC2 t3.small ≈ 0.046 IPv4 0.01 EBS ≈0.007 CW The total cost is about 0.07 USD; if you forget to clean up: the instance + IPv4 is about 0.68 USD per day, and the 20 GiB data volume is about 1.8 USD per month
Figure 8-2 The real risk is not the experiment itself, but the long-term cost of legacy resources

Interaction: Experiment Cost Calculator

Adjust the parameters, and the calculator calculates in real time based on the approximate unit price (only used for order-of-magnitude judgment, subject to AWS Pricing Calculator). Click "Simulate forgetting to clean up for 30 days" to see the cost of legacy resources.






Estimated results (USD)

Core command

CommandFunctionDescription
aws resourcegroupstaggingapi get-resources --tag-filters Key=Name,Values=linux-labList resources in the region by labelDoes not contain global resources such as IAM; some services do not support
aws ec2 terminate-instances + wait instance-terminatedTerminate and waitTermination protection needs to be turned off first
aws ec2 describe-volumes --filters Name=status,Values=availableFind unmounted volumesCommon legacy
aws ec2 describe-addressesElastic IPBilling even if not associated
aws iam remove-role-from-instance-profile / delete-instance-profile / delete-roleIAM cleanupDetach policy first
aws logs delete-log-groupDelete log groupUnrecoverable
aws ce get-cost-and-usageQuery actual costsData is delayed (usually several hours)

Complete cleanup script (~/linuxlab/aws/cleanup.sh)

#!/usr/bin/env bash
set -uo pipefail
source ~/linuxlab/aws/hour4.env
echo "== 1. alarms";      aws cloudwatch delete-alarms --alarm-names linux-lab-mem-high linux-lab-auto-recover 2>/dev/null
echo "== 2. instances"
IIDS=$(aws ec2 describe-instances --filters Name=tag:Name,Values=$LAB Name=instance-state-name,Values=pending,running,stopping,stopped \
  --query 'Reservations[].Instances[].InstanceId' --output text)
if [ -n "$IIDS" ]; then aws ec2 terminate-instances --instance-ids $IIDS >/dev/null; aws ec2 wait instance-terminated --instance-ids $IIDS; fi
echo "== 3. volumes & snapshots"
for v in $(aws ec2 describe-volumes --filters Name=tag:Name,Values=$LAB Name=status,Values=available --query 'Volumes[].VolumeId' --output text); do
  aws ec2 delete-volume --volume-id $v && echo "deleted $v"; done
for s in $(aws ec2 describe-snapshots --owner-ids self --filters Name=tag:Name,Values=$LAB --query 'Snapshots[].SnapshotId' --output text); do
  aws ec2 delete-snapshot --snapshot-id $s && echo "deleted $s"; done
echo "== 4. security group"; aws ec2 delete-security-group --group-id $SG_ID 2>&1 | tail -1
echo "== 5. iam"
aws iam remove-role-from-instance-profile --instance-profile-name $IPROFILE --role-name $ROLE 2>/dev/null
aws iam delete-instance-profile --instance-profile-name $IPROFILE 2>/dev/null
for p in AmazonSSMManagedInstanceCore CloudWatchAgentServerPolicy; do
  aws iam detach-role-policy --role-name $ROLE --policy-arn arn:aws:iam::aws:policy/$p 2>/dev/null; done
aws iam delete-role --role-name $ROLE 2>&1 | tail -1
echo "== 6. logs & parameters"
for g in $(aws logs describe-log-groups --log-group-name-prefix /linux-lab --query 'logGroups[].logGroupName' --output text); do
  aws logs delete-log-group --log-group-name $g && echo "deleted $g"; done
aws ssm delete-parameter --name AmazonCloudWatch-linux-lab 2>/dev/null
echo "== 7. account switches"; aws ec2 disable-serial-console-access --query SerialConsoleAccessEnabled
echo "done"

Residual scanning

aws resourcegroupstaggingapi get-resources --tag-filters Key=Name,Values=linux-lab --query 'ResourceTagMappingList[].ResourceARN'
aws ec2 describe-instances --filters Name=tag:Name,Values=linux-lab Name=instance-state-name,Values=running,stopped --query 'Reservations[].Instances[].InstanceId'
aws ec2 describe-volumes --filters Name=status,Values=available --query 'Volumes[].[VolumeId,Size,Tags[?Key==`Name`]|[0].Value]'
aws ec2 describe-addresses --query 'Addresses[].[PublicIp,AssociationId]'
aws iam get-role --role-name linux-lab-ec2-role 2>&1 | tail -1
aws logs describe-log-groups --log-group-name-prefix /linux-lab --query 'logGroups[].logGroupName'
[]
[]
[]
[]
An error occurred (NoSuchEntity) when calling the GetRole operation: The role with name linux-lab-ec2-role cannot be found.
[]

Experiment 8: One-click cleaning and residual scanning (about 5 minutes)

(Optional) Save a data snapshot and then clean it——Exercise "protect data before deleting the instance", and then the script will be deleted together:
cd ~/linuxlab/aws && source hour4.env
aws ec2 create-snapshot --volume-id $VOL --description "linux-lab valkey data" \
  --tag-specifications "ResourceType=snapshot,Tags=[{Key=Name,Value=$LAB}]" --query SnapshotId --output text
View the current resources by tag:
aws resourcegroupstaggingapi get-resources --tag-filters Key=Name,Values=$LAB --query 'ResourceTagMappingList[].ResourceARN' --output text | tr '\t' '\n'
arn:aws:ec2:ca-central-1:111122223333:instance/i-0123456789abcdef0
arn:aws:ec2:ca-central-1:111122223333:volume/vol-0aaaabbbbccccdddd0
arn:aws:ec2:ca-central-1:111122223333:volume/vol-0123456789abcdef0
arn:aws:ec2:ca-central-1:111122223333:security-group/sg-0abc…
arn:aws:ec2:ca-central-1::snapshot/snap-0…
arn:aws:ssm:ca-central-1:111122223333:parameter/AmazonCloudWatch-linux-lab
Run the cleanup script (The script to save the "Command" paging is cleanup.sh):
chmod +x cleanup.sh && ./cleanup.sh
== 1. alarms
== 2. instances
== 3. volumes & snapshots
deleted vol-0123456789abcdef0
deleted snap-0…
== 4. security group
== 5. iam
== 6. logs & parameters
deleted /linux-lab/cloud-init
deleted /linux-lab/myapp
deleted /linux-lab/system-errors
== 7. account switches
false
done
Residual scan: Execute the residual scan of the "command" page, and it will be completed when all are empty / NoSuchEntity get-resources The newly deleted resources may still be returned in a short period of time (eventually consistent). Check again after a few minutes.
Clean up the machine: rm -f ~/.ssh/serial_lab ~/.ssh/serial_lab.pub; if you do not want to continue Lesson 5, you can aws sso logout. Budget alarms can be retained.

Case 1: "Invisible" volumes at $300 per month

Problem: The development team frequently creates/terminates test instances, the data volumes default to DeleteOnTermination=false, and hundreds of volumes in the available status are accumulated in a year. Practice: Set DeleteOnTermination=true for data volumes in the Launch Template (except those that really need to be retained); use AWS Config rules to detect unmounted volumes; perform regular script or Data Lifecycle Manager cleanup; enforce tag policies (Owner, TTL). Restrictions: A snapshot or approval is required before automatic deletion to avoid accidental deletion.

Case 2: Billing changes after public IPv4 billing

Issue: Starting in 2024, all public IPv4 addresses will be billed by the hour, and an account with 200 "Default VPC Public Subnet" instances will incur significant monthly charges. How to do it: Move the instance to a private subnet, use NAT or VPC endpoint for outbound use, and log in to Session Manager (the method in this lesson naturally does not require public IP); use the public IP insight of VPC IP Address Manager to find out the unused EIP. Limitations: The NAT gateway itself is also billed by the hour and traffic, which needs to be weighed based on scale.

Case 3: Automatic cleanup of experimental accounts

Problem: Students in training accounts often forget to clean up. Method: All resources are forced to have Name=linux-lab and ExpiresAt tags; EventBridge triggers Lambda/SSM Automation regularly, terminates expired instances and deletes volumes according to tags; budget alerts are sent to the person in charge. Restrictions: IAM, log groups, etc. do not support unified tag deletion and require separate logic.

Interactive Troubleshooting Tree: Linux on EC2 (Full Lesson Review)

Common mistakes when cleaning

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

Cause: There are still network cards (the instance has not been completely terminated, or the EIC Endpoint / VPC endpoint uses this security group) or other security group rules refer to it.

aws ec2 describe-network-interfaces --filters Name=group-id,Values=$SG_ID --query 'NetworkInterfaces[].[NetworkInterfaceId,Status,Description]'

Fix: Wait for the instance to be terminated, delete the endpoints/rules referencing it and try again.

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 the instance profile, or a managed policy/inline policy is still attached. Fix:remove-role-from-instance-profile → list-attached-role-policies one by one detach → list-role-policies one by one delete-role-policy → delete-role.

An error occurred (VolumeInUse) when calling the DeleteVolume operation: Volume vol-… is currently attached to i-…

Cause: The instance has not been terminated or the volume is still mounted. Fix: Wait for the instance to terminate, or detach-volume (umount the instance first) before deleting it.

OperationNotPermitted: The instance 'i-…' may not be terminated. Modify its 'disableApiTermination' instance attribute and try again.

Reason: Termination protection is turned on. Fixed:aws ec2 modify-instance-attribute --instance-id $IID --no-disable-api-termination, and then terminate after confirming that it is correct.

Command line operation questions
1. Find all unmounted (available) EBS volumes in the current region and their total sizes.
aws ec2 describe-volumes --filters Name=status,Values=available --query 'Volumes[].[VolumeId,Size]' --output text
aws ec2 describe-volumes --filters Name=status,Values=available --query 'sum(Volumes[].Size)'
2. Query the actual costs grouped by services from this month to today.
aws ce get-cost-and-usage --time-period Start=$(date +%Y-%m-01),End=$(date +%Y-%m-%d) \
  --granularity MONTHLY --metrics UnblendedCost --group-by Type=DIMENSION,Key=SERVICE \
  --query 'ResultsByTime[0].Groups[].[Keys[0],Metrics.UnblendedCost.Amount]' --output table
Scenario analysis question
A colleague said, "I stopped the experimental example, so there should be no charge." A week later there are still EC2 related charges on the bill. List possible billing sources and verification commands.

① EBS root volumes and data volumes (describe-volumes); ② Snapshots (describe-snapshots --owner-ids self); ③ EIPs that are not associated or associated with stopped instances (describe-addresses); ④ Instances in other regions (check region-by-region or use Resource Resource Explorer); ⑤ CloudWatch log storage, custom indicators, alarms; ⑥ NAT gateway/VPC endpoint (if any). Use Cost Explorer to group and locate by USAGE_TYPE, such as EBS:VolumeUsage.gp3, PublicIPv4:IdleAddress.

Verified instructional videos

▶
Find and Delete all AWS Resources Using Cost Explorer & Tag Editor | AWS Tutorial for Beginners — Tiny Technical Tutorials
English · Use Cost Explorer and Tag Editor to find and delete legacy resources
▶
How can I tag my AWS resources to divide up my bill by cost center or project? — Amazon Web Services
English · AWS official knowledge center · Cost allocation tags

Official documentation

Video storyboard script (about 70 seconds)

This courseware cannot directly generate video/MP3. Storyboards and explanation scripts have been provided, which can be generated by video tools.

Shot 1 · 0–20s
Screen: The kill button is pressed and the instance disappears, but the data volumes, snapshots, log groups, and IAM roles are still floating in place, each with a price tag hanging on it.
Narration: Terminating the instance does not mean the cleanup is complete. Data volumes, snapshots, logs, and roles will remain.
Shot 2 · 20–45s
Screen: Delete in numerical order: alarms, instances, volumes, security groups, roles, log groups, tick each step.
Narration: Delete in dependency order, delete users first, then delete used resources.
Lens 3 · 45–70s
Screen: The residual scan command outputs an empty list and the billing curve is reset to zero.
Narration: Finally, perform a residual scan according to the label. An empty list is truly complete.
Or score ≥ 70% on the Quiz

Command Cheat Sheet

Common commands for Linux operation and maintenance on AWS (region ca-central-1, see ~/linuxlab/aws/hour4.env for variables)

AMI and instance types

aws ssm get-parameters --names /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64 --query 'Parameters[0].Value'
aws ssm get-parameters --names /aws/service/canonical/ubuntu/server/26.04/stable/current/amd64/hvm/ebs-gp3/ami-id
aws ec2 describe-images --image-ids $AMI --query 'Images[0].[Name,Architecture,ImdsSupport]'
aws ec2 describe-instance-types --instance-types t3.small t4g.small
aws ec2 run-instances --dry-run --image-id resolve:ssm:$AL2023_PARAM --instance-type t3.small

Startup, user data and cloud-init

aws ec2 run-instances --image-id resolve:ssm:$AL2023_PARAM --instance-type t3.small \
  --iam-instance-profile Name=linux-lab-ec2-profile --security-group-ids $SG_ID \
  --metadata-options HttpTokens=required,HttpPutResponseHopLimit=2,InstanceMetadataTags=enabled \
  --user-data file://user-data.sh --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=linux-lab}]'
sudo cloud-init status --long ; sudo cloud-init analyze blame
sudo tail /var/log/cloud-init-output.log
aws ec2 get-console-output --instance-id $IID --latest --output text

IMDSv2

TOKEN=$(curl -s -X PUT http://169.254.169.254/latest/api/token -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/instance-id
curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/iam/security-credentials/
ec2-metadata -i -z
aws ec2 modify-instance-metadata-options --instance-id $IID --http-tokens required --http-put-response-hop-limit 2
aws ec2 modify-instance-metadata-defaults --http-tokens required

EBS and file system

aws ec2 create-volume --availability-zone $AZ --volume-type gp3 --size 10 --encrypted
aws ec2 attach-volume --volume-id $VOL --instance-id $IID --device /dev/sdf
lsblk -o NAME,SIZE,MOUNTPOINTS,SERIAL ; sudo ebsnvme-id /dev/nvme1n1
sudo mkfs.xfs -L data /dev/nvme1n1 ; sudo blkid
# fstab: UUID=…  /data  xfs  defaults,nofail,x-systemd.device-timeout=10s  0 2
sudo findmnt --verify && sudo mount -a
aws ec2 modify-volume --volume-id $VOL --size 20 ; sudo xfs_growfs /data
sudo growpart /dev/nvme0n1 1 && sudo xfs_growfs -d /

Access

aws ssm describe-instance-information --query 'InstanceInformationList[].[InstanceId,PingStatus,AgentVersion]'
aws ssm start-session --target $IID
aws ssm start-session --target $IID --document-name AWS-StartPortForwardingSession \
  --parameters '{"portNumber":["5000"],"localPortNumber":["5000"]}'
aws ssm send-command --instance-ids $IID --document-name AWS-RunShellScript --parameters 'commands=["uptime"]'
aws ec2-instance-connect ssh --instance-id $IID --os-user ec2-user --connection-type eice

CloudWatch Agent

sudo dnf install -y amazon-cloudwatch-agent
sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -c ssm:AmazonCloudWatch-linux-lab -s
sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a status
sudo tail /opt/aws/amazon-cloudwatch-agent/logs/amazon-cloudwatch-agent.log
aws logs tail /linux-lab/myapp --follow
aws cloudwatch list-metrics --namespace CWAgent

Patch

cat /etc/amazon-linux-release
sudo dnf check-release-update
dnf check-update --releasever=latest
sudo dnf upgrade --releasever=2023.12.20261112
sudo dnf needs-restarting -r ; sudo dnf supportinfo --pkg valkey
aws ssm send-command --instance-ids $IID --document-name AWS-RunPatchBaseline --parameters Operation=Scan
aws ssm describe-instance-patch-states --instance-ids $IID

Troubleshooting and cleanup

aws ec2 describe-instance-status --instance-ids $IID --include-all-instances
aws ec2 get-console-screenshot --instance-id $IID --query ImageData --output text | base64 -d > s.jpg
aws ec2 enable-serial-console-access   # disable after use
aws ec2-instance-connect send-serial-console-ssh-public-key --instance-id $IID --serial-port 0 --ssh-public-key file://k.pub
ssh -i k $IID.port0@serial-console.ec2-instance-connect.ca-central-1.aws
aws resourcegroupstaggingapi get-resources --tag-filters Key=Name,Values=linux-lab

Quick troubleshooting table

PhenomenaCheck firstCommon causesSee
RunInstances report InvalidParameterValue (architecture)AMI and instance type architecturex86_64 AMI + GravitonM1
Instance 2/2 passed but the application did not startcloud-init status --long, cloud-init-output.logUser data failed, package name errorM2
Unable to locate in container credentialshop limithop limit = 1M2
IMDS returns 401With token or notIMDSv1 script / old SDKM2
Enter emergency mode after restartConsole outputfstab no nofail, device name driftM3 / M7
TargetNotConnectedInstance role, outbound 443, AgentMissing instance configuration file / private subnet no endpointM4
Log group is emptyAgent log, units namePermissions, filter conditionsM5
dnf shows no update but CVEdnf check-release-updateVersioned repository lockM6
Instance check impairedConsole output → Serial consoleStartup failure, network configuration, OOMM7
Delete security group DependencyViolationNetwork cardThe instance is not completely terminatedM8

Recommended configuration fragment

"MetadataOptions": {
  "HttpTokens": "required",
  "HttpPutResponseHopLimit": 1,
  "HttpEndpoint": "enabled",
  "InstanceMetadataTags": "enabled"
},
"ImageId": "resolve:ssm:/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64",
"IamInstanceProfile": { "Name": "linux-lab-ec2-profile" }

When no container requires the instance role, the hop limit is set to 1 safer.

[Unit]
RequiresMountsFor=/data

[Service]
ReadWritePaths=/data/valkey
UUID= /data xfs defaults,nofail,x-systemd.device-timeout=10s 0 2

Comprehensive experiment + final test

Deliver a myapp from scratch "without SSH, with data disk, with monitoring and patch compliance" Instance, clean thoroughly after acceptance
About 30 minutesThe cost is about 0.1 USD

Scenario

The team wants to provide myapp for internal users in ca-central-1. Security requirements: The instance does not have any inbound rules, only IMDSv2, all logins are auditable; operation and maintenance requirements: Valkey data is in an independent EBS volume, logs and memory/disk metrics enter CloudWatch, patch compliance can be reported; after delivery, it must be cleaned by another engineer within 5 minutes according to the list.

Preparation: source ~/linuxlab/aws/hour4.env; Confirm that roles, instance profiles, and security groups exist (if they were deleted in module 8, follow "Warm-up" steps 3–4 to re-create them).
Extended user data: Append at the end of module 2's user-data.sh : install amazon-cloudwatch-agent and fetch-config -c ssm:AmazonCloudWatch-linux-lab -s; wait /dev/sdf appears (up to 60 seconds cycle [ -e /dev/sdf ]), if it is an empty disk mkfs.xfs, write the fstab line of UUID + nofail, mount /data, put Valkey's dir Change to /data/valkey and add drop-in.
One boot with data volume: Declare the root volume and --block-device-mappings (gp3 10 GiB, encrypted, /dev/sdf at the same time in DeleteOnTermination=true, easy to clean), and label instances and volumes Name=linux-lab .
--block-device-mappings \
 'DeviceName=/dev/xvda,Ebs={VolumeSize=8,VolumeType=gp3,Encrypted=true}' \
 'DeviceName=/dev/sdf,Ebs={VolumeSize=10,VolumeType=gp3,Encrypted=true,DeleteOnTermination=true}'
Verify first startup: aws ec2 wait instance-status-ok; get-console-output --latest "linux-lab user data finished" appears; in SSM PingStatus=Online.
Verify application and data: after port forwarding curl localhost:5000/ hits are incremented twice; in the instance findmnt /data, valkey-cli CONFIG GET dir is /data/valkey; hits continue to increment after restarting the instance.
Verify observability and security: aws logs tail /linux-lab/myapp There are gunicorn logs;list-metrics --namespace CWAgent There are mem_used_percent and disk_used_percent (path=/data); IMDSv1 requests return 401; the security group inbound is empty.
Patch compliance: Run AWS-RunPatchBaseline Operation=Scan and record the number of Missing; if it is not 0, scan again after Install + RebootIfNeeded .
Handover and cleanup: Write the resource list (instance ID, volume, log group, parameters, IAM) into the handover description; run the cleanup.sh and residual scan of module 8, and the result is empty.

Acceptance Checklist






Open self-test (answer first and then expand)

1. Describe in your own words: From the time when RunInstances returns to when myapp can respond to the request, what happens inside the instance?

Nitro allocates resources and creates root volume from AMI snapshot → UEFI → GRUB → kernel (load NVMe/ENA driver) → systemd → cloud-init-local (Ec2 data source, IMDSv2 PUT token, read metadata and network configuration) → network ready → cloud-init network phase (growpart, hostname, SSH public key) → config phase → final phase executes user data (dnf installs valkey/python, creates user, venv, writes unit, enable --now) → at the same time, SSM Agent uses IMDS to get role credentials to register → status check passes → myapp listens to 5000.

2. Why is IMDSv2 said to mitigate SSRF? What can't it protect against?

You need to PUT first with a custom header to get the token, and then GET with the token; most SSRF can only initiate a simple GET and cannot set the header; PUT with X-Forwarded-For will be rejected; hop limit limits the propagation range of the token response. It cannot protect against attackers who can execute arbitrary commands on the instance (RCE), nor can it protect against logical vulnerabilities in the application itself that uses the SDK to initiate requests on its behalf, so a minimum privilege role is still required.

3. The /etc/fstab of an instance is /dev/nvme1n1. Why is "currently available" still a hidden danger? How to change safely?

NVMe names are assigned in enumeration order and may change after stopping/starting, adding or removing volumes, resulting in the wrong disk being mounted or the device not being found and entering an emergency. Modification: blkid gets UUID → change to UUID=… defaults,nofail → findmnt --verify → systemctl daemon-reload → umount/mount -a Verification → Add RequiresMountsFor to dependent services.

4. What are the identity checkpoints and network requirements for Session Manager and EC2 Instance Connect? When would you choose EIC?

SSM: IAM ssm:StartSession verification, the instance only needs outbound 443 to three endpoints, zero inbound; EIC: IAM SendSSHPublicKey verification is limited to OS users, the instance requires port 22 to be reachable by the client (or EIC Endpoint), sshd takes 60 through IMDS seconds public key. Select EIC (Prioritize EIC Endpoint) when the SSM Agent is abnormal or you need native SSH tools and do not want to distribute long-term keys.

5. "dnf upgrade shows no updates" and Patch Manager scan shows missing patches. Are they contradictory?

No contradiction. dnf searches within the locked repository version by default; Patch Manager gets the latest locked version and evaluates it against the baseline. To allow manual dnf to see it, --releasever=latest or specify the version is required.

6. How will you evolve the manual steps in this lesson into a production plan?

Terraform/CloudFormation description VPC (private subnet + endpoint), Launch Template (resolve:ssm, IMDSv2, hop limit 1, instance configuration file, encrypted volume), ASG + ALB health check; Image Builder bakes the AMI containing myapp dependencies and CloudWatch Agent, user data is only configured; Agent configuration is placed in SSM Parameters are issued by the State Manager; Patch strategy + regular instance refresh; Session Manager logs to S3; tag strategy and budget; the data layer uses managed services (ElastiCache for Valkey).

Source and version description

Verification basis for the technical facts of this lesson (Verification date: 2026-11-17, all visit official sources such as docs.aws.amazon.com)
TopicVerification conclusionSource (accessed 2026-11-17)
AL2023 support cycle2023-03 release; standard support until 2027-06-30 (quarterly version); maintenance period until 2029-06-30Release cadence
AL2023 Current Release12th Quarter Release 2023.12; latest build 2023.12.20261112; 6.1 / 6.12 / 6.18 kernel AMI available2023.12 release notes
Default kernel and SSM parametersFrom 2026-08-17 al2023-ami-kernel-default Default 6.18; parameters /aws/service/ami-amazon-linux-latest/al2023-ami-[minimal-]kernel-default-{x86_64,arm64} and -kernel-6.1/6.12/6.18-AL2023 on EC2
AL2023 packagesystemd 252.23, dnf 4.14.0, cloud-init 22.2.2, amazon-cloudwatch-agent 1.300071.0, ec2-instance-connect 1.1, docker 25.0.16, python3 3.9 (system), python3.12/3.13/3.14 Optional; redis6 6.2.20 has ended support on 2026-01-31; valkey 9.0.6 is fully supported until 2029-06-30All packages in AL2023.12
valkey unit nameFedora Packaging specifications: valkey.service, valkey-cli, configuration /etc/valkey/valkey.conf; not in AL2023 list valkey-compat-redisFedora valkey.spec (Please refer to rpm -ql valkey for the actual path of AL2023)
Ubuntu AMI parameters/aws/service/canonical/ubuntu/server/{26.04|resolute|24.04|noble}/stable/current/{amd64|arm64}/hvm/ebs-gp3/ami-id; Canonical account 099720109477Find Ubuntu images on AWS
IMDSv2PUT /latest/api/token, TTL 1 second–6 hours (21600); no/expired token 401; PUT with X-Forwarded-For rejected; PUT response default hop limit 1; IPv6 [fd00:ec2::254] (Nitro); CLI ≥ 1.16.289, boto3 ≥ 1.12.6 supportedHow IMDSv2 works
AL2023 IMDS defaultAL2023 AMI ImdsSupport=v2.0: only IMDSv2, hop limit 2; account-level default available modify-instance-metadata-defaults SettingsAL2023 IMDSv2 · Configure IMDS for new instances
Instance profile credentials/latest/meta-data/iam/security-credentials/; Automatic rotation, new credentials available at least 5 minutes before expirationRetrieve security credentials
user dataOriginal 16 KB limit; run as root; output /var/log/cloud-init-output.log; script stored in /var/lib/cloud/instances//User data
NVMe / EBSDevice /dev/nvmen1 In enumeration order, may vary; serial number = volume ID; Amazon Linux udev creates /dev/sdf link; ebsnvme-id; other distributions nvme id-ctrl -VMap EBS volumes to NVMe device names
Instance StorageRestart retained; stop, hibernate, terminate lostInstance store data persistence
SSM Agent pre-installed / Session ManagerAL2023 pre-installed (RPM); Ubuntu 18.04–24.04, 25.04 pre-installed (snap), not listed in the document 26.04; Agent ≥ 2.3.68 (Port Forwarding/SSH ≥ 3.0.222.0); Outbound 443 to ec2messages / ssm / ssmmessages; ssm-user created on first sessionPreinstalled agent · Session Manager prerequisites
EC2 Instance ConnectAL2023 Standard AMI, Ubuntu 20.04+ pre-installed (AL2023 minimum AMI requires manual installation); public key 60 seconds; aws ec2-instance-connect ssh --connection-type direct|eice; prefix list com.amazonaws..ec2-instance-connectInstall EIC · Connect methods
CloudWatch Agentlogs_collected supports files, windows_events, journald (units/priority/matches/filters/retention_in_days; default priority info; continue from the last cursor after restart); run_as_user is not set to root Run; do not publish the hostname dimension after append_dimensionsAgent configuration file
Versioned repositoryDefault locked to the repository version of the AMI; dnf check-release-update; dnf upgrade --releasever=… will become the default version; new security updates will not be automatically applied at startupDeterministic upgrades
Patch ManagerAWS-AmazonLinux2023DefaultPatchBaseline: Security Critical/Important + Bugfix, automatically approved after 7 days; equivalent dnf upgrade-minimal --sec-severity=Critical --sec-severity=Important --bugfix -y; Get the latest locked repository version; RebootOption Default RebootIfNeededHow patches are installed · Baselines · Package selection
Status checkFive categories: system, instance, attached EBS, application (optional), performance (accelerated instance); per minute; indicators StatusCheckFailed_System/_Instance/_AttachedEBS; Instance check probes network card via ARPStatus checks
EC2 Serial ConsoleNitro virtualized instances and most bare metal; default off at account level; password user required; 1 session/instance, ~1 hour, 30 after disconnect seconds; public key 60 seconds; endpoint serial-console.ec2-instance-connect.ca-central-1.aws, username .port0Prerequisites · Connect
Pricet3.small, gp3, public IPv4 (approx. 0.005 USD/hour), CloudWatch are all ca-central-1 approximate valuesEC2 · EBS · VPC · CloudWatch

Video verification instructions

The following videos were verified through the YouTube oEmbed interface on 2026-11-17 with titles and channels (only English videos listed): AWS "What is Amazon Linux 2023 | Amazon Web Services" (sxPqBT19bfA); AWS Events "AWS re:Invent 2025 - Amazon Linux: latest features and AWS optimizations (CMP303)" (LXZMjOm_OMc); Tiny Technical Tutorials "UPDATED - Amazon/AWS EC2 Basics | Create an EC2 Instance | AWS Tutorials for Beginners" (YH_DVenJHII), "Find and Delete all AWS Resources Using Cost Explorer & Tag Editor | AWS Tutorial for Beginners" (8BwDrzeHOks); cloudonaut "Transition to IMDSv2 on EC2 - Introduction, Preparation, Pitfalls" (bi3bIs92xE0); StratusGrid "Understanding Amazon EC2 Instance Metadata Service v2 Hop Limit" (4oCezO4AaqA); Learn Linux TV "Getting Started with cloud-init" (exeuvgPxd-E); Cloud Explainers "AWS EBS vs. EC2 Instance Store: Differences, Performance, and Use Cases Explained" (TuHqGy4pp4w), "AWS EC2 Instance Troubleshooting: Diagnosing Status Check Failures" (MuKJEqN_uHQ); KodeKloud "AWS Storage Explained | EBS vs EFS vs S3 | AWS Training" (C9StEK6EMQY); DheerajTechInsight "AWS EBS Volumes Explained - Create, Attach, Snapshot & Backup" (9zE2Tmlhi7E); AWS "AWS Sessions Manager Overview" (cUEFGKaZOyU); Digital Cloud Training "Connect to EC2 with Session Manager and EC2 Instance Connect" (3tKB947rT5Q), "Install the Amazon CloudWatch Agent and Log to CloudWatch Logs" (7UlFuwONrvQ); Stephane Maarek "EC2 Instance Connect Tutorial" (lxSNeF7BAII); Rahul Nath "Setting Up CloudWatch Agent on EC2: From Basic to Advanced Metrics | Amazon EC2" (kksPEerXIGs); AWS "Back to Basics: Automating Patching of EC2 Instances Using Systems Manager" (MhfKh35fols), "Automate Patching with AWS Systems Manager Quick Setup Patch Policy" (nDe9kLnDmsk), "Why is my EC2 Linux instance unreachable and failing its status checks?" (YttXHhPiAo0), "How can I tag my AWS resources to divide up my bill by cost center or project?" (HmXkLtSYHtk); KnowITFree "How to Enable and Use the Serial Console for AWS EC2 Instances for Linux and Window" (OA6ri3fYfDI). The length and release date of the video have not been verified one by one. The content may be earlier than the version facts of this lesson (such as AL2023 default kernel, valkey). This lesson shall prevail.

Voice explanation instructions

The "Voice" page uses the browser Web Speech API (speechSynthesis, en-US) to read the explanation script. English terms are pronounced in en-US. The effect depends on the voice installed on the system. This courseware generation environment cannot call the TTS service, so there is no embedded MP3; when offline audio is needed, the transcript can be generated by the TTS service.

Known limitations

  • The commands in this courseware are not executed in real AWS accounts; the account ID, instance/volume/snapshot ID, IP, time, patch number, Agent version number and error wording in "Expected Output" are examples, please refer to your environment.
  • Valkey's configuration file path, data directory and systemd unit sandbox settings on AL2023 are inferred based on Fedora packaging specifications. In the experiment, rpm -qc valkey and grep '^dir' were used to confirm in advance; if there are any differences, the actual situation shall prevail.
  • Whether Ubuntu 26.04 has pre-installed SSM Agent is not listed in the AWS documentation (listed to 24.04 / 25.04), please use snap list amazon-ssm-agent to self-check. The unit name of the newer cloud-init (cloud-init-network.service) is subject to the actual system.
  • CloudWatch Agent's journald input requires a newer Agent version. This lesson uses the AL2023 repository 1.300071.0 as the baseline; if you encounter "unknown key journald" errors, please upgrade the Agent.
  • When the instance status check becomes impaired in emergency mode, the prompt text in the serial console, etc. vary depending on the version; the root password in the experiment is a temporary measure and must be locked after the end.
  • The price is an approximation of 2026-11 ca-central-1 and is only used for order-of-magnitude judgment; free tier rules vary by account.
  • The time, status sequence and log in the animation are schematic and used to illustrate the real mechanism.