Linux Hour 4: Towards the cloud platform (AWS)
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- 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 theami-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/sdfin 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-labEstimate the cost and clean thoroughly.
1-hour time allocation table
| # | Time | Module | Core content | Animation/Interaction | Experiment (AWS ca-central-1) |
|---|---|---|---|---|---|
| 0 | Before class | Warm-up and AWS preparation | AWS CLI v2, Session Manager plug-in, SSO profile, IAM role + Instance profile, security group without inbound rules, budget alert | Environment self-check list | aws sts get-caller-identity |
| 1 | 00–05 | AMI, instance type and AL2023 | AMI composition, SSM public parameters, AL2023 vs Ubuntu, instance family/generation/size, Graviton, burst instances | AMI parser: Parameters → AMI → Architecture matches instance type | Parse latest AMI, query instance type, --dry-run |
| 2 | 05–13 | user data, cloud-init and IMDSv2 | cloud-init four phases, user data only runs once, IMDSv2 token, hop limit, instance profile credentials | Core 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 |
| 3 | 13–21 | EBS, instance storage and file system | gp3 / io2 / st1, instance storage life cycle, NVMe Naming, udev symbolic link, fstab, online expansion | AttachVolume → NVMe hot plug → udev → mkfs → mount; instance storage is lost after stopping/starting | Add a gp3 volume to Valkey as a data disk, and then expand the capacity |
| 4 | 21–29 | Access: SSM / EC2 Instance Connect / SSH | Session Manager architecture, port forwarding, SSH over SSM, EIC 60-second temporary public key, EIC Endpoint, key pair | Data flow comparison of three access paths | Zero inbound port login + port forwarding access 5000 |
| 5 | 29–37 | CloudWatch Agent | journald / file log, memory and disk indicators, CWAgent namespace, retention period, IAM permissions | Pipeline of logs and metrics from instances to CloudWatch | Collect myapp logs and memory metrics, create alarms |
| 6 | 37–45 | SSM Patch Manager | AL2023 versioned repository, dnf check-release-update, patch baseline, Scan / Install, restart strategy | Warehouse version timeline: Lock → Scan → Upgrade | Scan compliance + manual --releasever upgrade |
| 7 | 45–54 | Cloud debugging | System / instance / Mount EBS status check, console output and screenshots, EC2 serial console, common faults | Fault injection simulator: which check failed, what tool to use | Deliberately write bad fstab, and then use the serial console to repair |
| 8 | 54–60 | Cost, cleanup and self-test | Hour/GB Billing items, public network IPv4 fees, log fees, cleaning by tags, residual scanning | Cost Calculator + Interactive Troubleshooting Tree | Press Name=linux-lab for one-click cleanup |
| — | After class | Cheatsheet · Comprehensive lab | Deliver a myapp instance with "no SSH, with data disk, monitoring and patching" from scratch, and then clean it up | Final test (12 questions) | Comprehensive experiment (about 0.1–0.2 USD) |
Knowledge Coverage Matrix
| Target skills | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands/resources | Experiment |
|---|---|---|---|---|---|---|---|---|---|---|
| Select AMI and instance type | ✓ | · | · | · | · | ✓ | · | ✓ | resolve:ssm:, describe-instance-types | M1 |
| First boot and cloud-init | · | ✓ | · | · | · | · | ✓ | · | cloud-init status --long, /var/log/cloud-init-output.log | M2 |
| IMDSv2 and instance credentials | · | ✓ | · | ✓ | ✓ | · | ✓ | · | PUT /latest/api/token, modify-instance-metadata-options | M2 |
| Block storage and file system | · | · | ✓ | · | ✓ | · | ✓ | ✓ | lsblk -o +SERIAL, ebsnvme-id, xfs_growfs | M3 |
| Secure Access (Zero Inbound) | · | · | · | ✓ | · | ✓ | ✓ | · | aws ssm start-session, ec2-instance-connect ssh | M4 |
| Logs and Metrics | · | · | · | · | ✓ | · | ✓ | ✓ | amazon-cloudwatch-agent-ctl, aws logs tail | M5 |
| Patches and Compliance | ✓ | · | · | · | · | ✓ | · | · | dnf check-release-update, AWS-RunPatchBaseline | M6 |
| Cloud Troubleshooting | · | ✓ | ✓ | ✓ | · | · | ✓ | ✓ | describe-instance-status, get-console-output, serial console | M7 |
| Cost and cleanup | ✓ | · | ✓ | · | ✓ | · | · | ✓ | terminate-instances, resourcegroupstaggingapi | M8 |
What this lesson does not cover (and where to learn)
| Topics | Why not in this lesson | Where to learn |
|---|---|---|
| Azure VM, managed identity, Azure Monitor Agent | Has been taught in the previous lesson; this lesson uses comparison table mapping for each module | Lesson 3: Moving towards the cloud platform (Azure) |
| VPC design, private subnet + NAT, complete construction of VPC interface endpoints | Belongs to the network architecture; this lesson uses the default VPC and only explains which endpoints are required for private instances | Terraform Lesson 4 (AWS Network) |
| Use Terraform / CloudFormation to code the CLI steps of this lesson | Focus of this lesson Linux-side mechanism, use AWS CLI to make every step visible | Terraform 8-hour course |
| Configuration management (unified configuration of multiple instances) | Requires Ansible / SSM State Manager System explanation | Ansible 8-hour course, Lesson 5 (automated operation and maintenance) |
| Prometheus / Grafana monitoring system | This course only uses the CloudWatch native solution | Prometheus & Grafana Lesson |
| Container (ECS / EKS) and Mirroring | This lesson myapp runs as a native systemd service; only in hop limit Temporarily use the container once in the experiment | Docker class, Kubernetes class |
| Auto Scaling, load balancing, AMI Baking Pipeline (EC2 Image Builder) | Belongs to Architecture and Automation | Lessons 5 and 6 |
How to use this courseware
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. 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).
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. 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)
- Completed Lesson 1 to Lesson 3: know how to use shell, permissions, package management, systemd unit (
myapp.servicecreated in Lesson 2), journald, cloud-init (Lesson 3 is in used on Azure). - Local lab VM
linuxlab(Ubuntu Server current LTS, userlabadmin), 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
AdministratorAccesspermission set is available for experiments; please tighten it for production).
Concept comparison with Lesson 3 (Azure)
| Concepts | Azure (Lesson 3) | AWS (this lesson) |
|---|---|---|
| Virtual Machine | VM vm-linux-lab, resource group rg-linux-lab | EC2 instance, label Name=linux-lab (AWS There is no "resource group deletes the boundary", cleaning depends on tags) |
| Mirror | Image URN (Publisher: Product: SKU: Version) | AMI ID (different for each region) + SSM public parameters |
| First startup configuration | custom data → cloud-init | user data → cloud-init |
| Metadata service | IMDS 169.254.169.254, request header Metadata: true | IMDS 169.254.169.254, IMDSv2 PUT first to get the token |
| Machine identity | Managed identity | IAM role + instance profile |
| No public IP login | Azure Bastion / az ssh vm(Entra ID) | SSM Session Manager / EC2 Instance Connect Endpoint |
| Monitoring agent | Azure Monitor Agent + DCR | CloudWatch Agent + JSON configuration (can be stored in SSM parameters) |
| Patch | Azure Update Manager | SSM Patch Manager |
| Startup troubleshooting | Startup diagnostics + serial console | Console output/screenshot + EC2 serial console |
| Temporary disk | Temporary 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"
]
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
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
- 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 inrun-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.
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 version | Parameter path | Description |
|---|---|---|
| AL2023 Standard Edition | /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64 | arm64 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_64 | Fewer 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-id | Canonical 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-id | Code 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 2023 | Ubuntu Server 26.04 / 24.04 | |
|---|---|---|
| Default user | ec2-user | ubuntu |
| Package management | dnf 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 control | SELinux (default permissive) | AppArmor |
| Log | only journald (rsyslog not pre-installed) | journald + rsyslog |
| SSM Agent | RPM 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 period | Standard support until 2027-06-30, maintenance until 2029-06-30 | LTS standard support for 5 years (Ubuntu Pro extended) |
| Root file system | XFS | ext4 |
When: How to choose the instance type
| Scenario | Recommended | Reason |
|---|---|---|
| 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 load | m7i / m7g / m8g and other general-purpose services | are not subject to CPU credit restrictions |
| CPU-intensive (compilation, encoding) | c7i / c7g | Less memory per vCPU, high cost performance |
| In-memory database, cache | r7i / r7g | 8 GiB per vCPU |
| Requires local high-speed temporary disk | With d suffix, such as m7gd, c6id | Comes with NVMe Instance storage (Module 3) |
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
Flow chart: using SSM Public parameter resolution "Latest AMI"
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.
Core Command
| Command | Function | Key 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-latest | List all Amazon Linux parameters | Only return the next level of the path, combined with --query filtering |
aws ec2 describe-images --image-ids … | View AMI name, architecture, startup mode, IMDS support | Architecture, BootMode, ImdsSupport |
aws ec2 describe-instance-types | Instance type vCPU, memory, architecture, network | --filters Name=processor-info.supported-architecture,Values=arm64 |
aws ec2 describe-instance-type-offerings | Whether an instance type is provided in an availability zone | --location-type availability-zone |
aws ec2 run-instances --dry-run | Only verify permissions and parameters, do not create resources | Return 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)
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
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 …
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.
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).
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'
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
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
Official document
- AL2023 on Amazon EC2 (SSM parameter list)
- AL2023 release cadence and support cycle
- EC2 instance types
- Find Ubuntu images on AWS(Canonical)
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.
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.
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.
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.
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.
Module 2 · user data, cloud-init and IMDSv2
- 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, usermyapp,/opt/myapp,/etc/myapp/myapp.env, port 5000) and Valkey to AL2023. - Use IMDSv2 (
PUT /latest/api/token→ with tokenGET) to read metadata and instance configuration file credentials, explain the role ofHttpTokens,HttpPutResponseHopLimit, and diagnose "credentials not available in the container".
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-configYAML, 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.logandcloud-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 + rejectX-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)
| Phases | systemd unit | What to do | With IMDS Interaction |
|---|---|---|---|
| Local | cloud-init-local.service | Run when the network is not ready: identify the data source and generate network configuration | The Ec2 data source will temporarily establish a DHCP connection, PUT the token and then read the metadata (including network information) |
| Network | cloud-init.service | The network is ready: run cloud_init_modules (growpart, resizefs, set hostname, user and SSH public key, etc.) | Read user data, public-keys |
| Config | cloud-config.service | Run cloud_config_modules (such as runcmd Write the script to be executed, time zone, mount) | — |
| Final | cloud-final.service | Run cloud_final_modules: install software package, execute user data script (scripts-user), runcmd, final message | The 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/. Modifying user data requires stopping the instance first, and restarting it after modification will not re-execute the script (unless you use the/sem/ #cloud-config'scloud_final_modulesfrequency configuration or the per-boot script in MIME, or manuallycloud-init clean). - Run as root without sudo or loading the interactive shell environment; commands in the script must use absolute paths or set
PATHat 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)
PUT http://169.254.169.254/latest/api/token, request headerX-aws-ec2-metadata-token-ttl-seconds: 21600(1 second – 6 hours) → Returns the token. The token is only valid in this instance.- Subsequent
GETrequests carryX-aws-ec2-metadata-token:.HttpTokens=required, if there is no token or the token expires, 401 Unauthorized will be returned. - PUT requests with
X-Forwarded-Forheader will be rejected (to prevent exploitation via reverse proxy). - hop limit: PUT's response is sent with IP TTL =
HttpPutResponseHopLimit. The default is 1; but when starting with an AMI (AL2023 is AL2023) usingImdsSupport: v2.0, it defaults to only IMDSv2 + hop limit 2, so that containers in the Docker bridge network can also get the token. - Credentials:
GET /latest/meta-data/iam/security-credentials/returns the role name; thenGET .../security-credentials/returnsAccessKeyId/SecretAccessKey/Token/Expiration. AWS provides new credentials at least 5 minutes before expiration, and the SDK automatically refreshes them.
| IMDSv1 | IMDSv2 | Azure IMDS (Lesson 3) | |
|---|---|---|---|
| Request method | Direct GET | PUT first to get the token, GET with the token | GET + Metadata: true Header |
| Anti-SSRF | Weak (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 default | Disabled | Required, hop limit 2 | — |
When: Choose shell script or #cloud-config
| Required | Recommended |
|---|---|
| A small number of commands, the team knows bash | shell 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 files | user data only bootstrapping: download the installation package from S3 / CodeArtifact, or bake it into your own AMI |
| Long-term consistency of multiple instances | user data only installs the agent, and leaves the configuration to SSM State Manager / Ansible (Lesson 5) |
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
Flowchart: Instance profile credentials arrive at the process (host vs container) via IMDSv2
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.
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.
Core command
| Command | Function | Instructions |
|---|---|---|
aws ec2 run-instances --user-data file://user-data.sh | With user data at startup | CLI automatically does base64; modify-instance-attribute does not |
--metadata-options HttpTokens=required,HttpPutResponseHopLimit=2,InstanceMetadataTags=enabled | Explicitly set IMDS at startup | Does not rely on AMI default values and facilitates auditing |
aws ec2 modify-instance-metadata-options | Modify the IMDS options of a running instance | Take effect immediately without restarting |
aws ec2 modify-instance-metadata-defaults | Set the IMDS default value of the account in this region | Only affects newly created instances |
cloud-init status --long --wait | Wait and view the cloud-init results | status: done / error |
cloud-init analyze blame / show | Each module takes time | Find out which stage is slow |
ec2-metadata -i -z -t | AL2023's own IMDS Query tool (ec2-utils package) | IMDSv2 token processed internally |
aws ec2 get-console-output --latest | View instance serial port output from the local machine | No 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)
~/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
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
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
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
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
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.
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/ 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.
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
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
Official documentation
- Run commands when you launch an EC2 instance with user data input
- How IMDSv2 works
- Configure IMDS for new instances / account defaults
- AL2023: IMDSv2 default settings
- Retrieve security credentials from instance metadata
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.
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.
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.
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.
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.
Module 3 · EBS volume, instance storage and file system
- 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-idon 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.
What: Two types of block storage on EC2
| EBS volumes | Instance store | |
|---|---|---|
| Physical location | EBS storage cluster, connected via network (Nitro card presents it as an NVMe device) | Host local NVMe SSD (some older models are HDD) |
| Life cycle | Independent of the instance; can be detached and remounted to other instances in the same availability zone | Bound to the instance: retained on restart; lost when stopping, hibernating, and terminating |
| Availability range | One availability zone; crossing availability zones requires snapshots | One host |
| Backup | Snapshot (incremental, stored in S3), can be copied across regions | None, you need to copy to persistent storage yourself |
| Typical type | gp3 (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 |
| Billing | Based on preset GB·month + additional IOPS/throughput; regardless of whether it is mounted or full | Included in the instance price |
| Suitable for placement | Root volume, database, application state, logs | Cache, 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 +SERIALVisible;/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-utilspackage) read it and create a/dev/sdf → nvme1n1symlink;sudo ebsnvme-id /dev/nvme1n1can be viewed directly. For other distributions, usesudo nvme id-ctrl -V /dev/nvme1n1(nvme-cli). - File system UUID / LABEL: Generated when
mkfsis 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 withx-systemd.device-timeout=10sto avoid long waiting. systemd will convert fstab lines intodata.mountunits, and services can declare dependencies usingRequiresMountsFor=/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 asp127/p128). cloud-init'sgrowpartwill expand the root partition to the entire disk when booting for the first time.
When: Where to put
| Data | Location | Reason |
|---|---|---|
Operating system, myapp code (/opt/myapp) | Root volume gp3 | Rebuildable from AMI + user data |
| Valkey persistent data (RDB/AOF) | Independent gp3 data volume /data | Can be individually snapshotted, expanded, and migrated to new instances |
| Temporary cache, compilation of intermediate products | Instance storage (if any) | Free and fastest, loss is acceptable |
| Multi-instance shared files | EFS / FSx (not EBS) | EBS can generally only be mounted to one instance (io2 multi-mounting requires a cluster file system) |
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
Flowchart: New volume from creation to use by the service
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.
Core Command
| Command | Function | Key parameters/description |
|---|---|---|
aws ec2 create-volume | Create volume | --availability-zone must be the same as the instance; --volume-type gp3 --size 10 --encrypted |
aws ec2 attach-volume / detach-volume | Mount/detach | --device /dev/sdf (prompt name); before detaching, umount |
aws ec2 modify-volume | Modify size, type, IOPS, throughput online | There is a cooling time between two modifications of the same volume (subject to documentation, usually 6 hours) |
lsblk -o NAME,SIZE,TYPE,MOUNTPOINTS,SERIAL,MODEL | List block device and serial number | SERIAL = volume ID (no hyphen) |
sudo ebsnvme-id /dev/nvme1n1 | AL2023: NVMe → Volume ID + Mapping name | Ubuntu uses nvme id-ctrl -V |
sudo mkfs.xfs -L valkeydata /dev/nvme1n1 | Format (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 system | ext4 Use resize2fs |
findmnt --verify | Check fstab syntax and equipment | Finish 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)
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 ]
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
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.
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 /.
sudo reboot, reconnect after about 1 minute, and confirm that findmnt /data, valkey-cli GET hits still has a value. 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.
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 /
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
Official Document
- Map Amazon EBS volumes to NVMe device names
- Make an Amazon EBS volume available for use
- Data persistence for instance store volumes
- Extend the file system after resizing a volume
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.
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.
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.
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.
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.
Module 4 · Access: SSM Session Manager, EC2 Instance Connect and SSH
- 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.
What: three access methods
| SSM Session Manager | EC2 Instance Connect(EIC) | Key pair + SSH | |
|---|---|---|---|
| Connection direction | Instance → External (Agent outbound 443), User → SSM API | User → Instance 22 port (or via EIC Endpoint) | User → Instance 22 Ports |
| Inbound Rules | Not required | Required 22 (Source: your IP, EIC service prefix list, or EIC Endpoint security group) | Required 22 |
| Identity | IAM (ssm:StartSession, can be restricted by tag) | IAM (ec2-instance-connect:SendSSHPublicKey, can be restricted by ec2:osuser) | Person holding private key |
| Credentials | No long-term key | One-time public key, valid for 60 seconds | Long-term private key (easy to leak, difficult to rotate) |
| Instance-side component | amazon-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 user | Default ssm-user (with sudo), configurable Run As | The OS user you specify (ec2-user / ubuntu) | The user corresponding to the key |
| Audit | CloudTrail StartSession + optional session logs (CloudWatch Logs/S3) | CloudTrail SendSSHPublicKey | Instance local only journalctl -u sshd |
| File transfer/ Port forwarding | Port forwarding document; scp available after SSH over SSM | Standard ssh/scp | Standard 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
- 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-informationPingStatus=Online), and maintain a long connection withec2messages/ssmmessages. - You run
aws ssm start-sessionlocally: the CLI calls theStartSessionAPI with your SSO credentials, and IAM evaluatesssm:StartSession(the resource is the instance ARN and session document). - The service notifies the Agent to open a data channel (WebSocket over TLS) through
ssmmessages, and returns the StreamUrl and token to the localsession-manager-plugin. - 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-useron 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
- Natively generate or use a temporary key pair, calling
SendSSHPublicKey(specifying the instance and OS user). - EC2 places the public key in the instance's metadata and removes it after 60 seconds.
- You
sshconnect within 60 seconds; theec2-instance-connectpackage on the instance configuresAuthorizedKeysCommandfor sshd, and sshd calls it to read the just-pushed public key through IMDS and compare it. - EIC Endpoint: Create an endpoint in the private subnet,
aws ec2-instance-connect ssh --connection-type eiceto 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
| Scenario | Recommended |
|---|---|
| Daily operation and maintenance, production environment | Session 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 normal | EC2 Instance Connect (temporary open source IP) |
| Neither the network nor sshd can start (fstab, kernel panic) | EC2 Serial Console (Module 7) |
| Long-term key pair | Only as a last resort; private key in password manager, inbound restricted source |
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
Flow chart: Session Manager port forwarding access myapp
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.
Core Command
| Command | Function | Description |
|---|---|---|
aws ssm describe-instance-information | Check whether the managed node is Online, Agent version, platform | Prerequisites for Session Manager |
aws ssm start-session --target $IID | Interactive shell | Requires session-manager-plugin |
--document-name AWS-StartPortForwardingSession | Local port → instance port | --parameters portNumber=5000,localPortNumber=5000 |
--document-name AWS-StartPortForwardingSessionToRemoteHost | Forwarded to other hosts in VPC (such as RDS) via instance | host=…,portNumber=… |
--document-name AWS-StartSSHSession | SSH over SSM(ProxyCommand) | Still requires SSH key/EIC Public key for authentication |
aws ssm send-command --document-name AWS-RunShellScript | Non-interactive batch execution of commands | Output can be written to S3 / CloudWatch Logs |
aws ec2-instance-connect ssh --instance-id $IID | One command to complete pushing the public key + SSH | --connection-type direct|eice, --os-user |
aws ec2-instance-connect send-ssh-public-key | Only 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)
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.
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
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
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.
/linux-lab/ssm-sessions (the instance role requires write log permission, CloudWatchAgentServerPolicy is included logs:PutLogEvents etc.). 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.
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
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
Official document
- Session Manager prerequisites
- AMIs with SSM Agent preinstalled
- Connect using EC2 Instance Connect
- Install EC2 Instance Connect
- EC2 Instance Connect Endpoint
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.
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?
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.
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.
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.
Module 5 · Monitoring and logging: CloudWatch Agent
- 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:
journaldcollectsmyapp/valkeyunit logs,filescollects/var/log/cloud-init-output.log,mem/diskindicators, and sets the retention period and dimensions. - Use
amazon-cloudwatch-agent-ctlto load the configuration and check the Agent's own logs; useaws logs tail, Logs Insights and alarms to verify the results.
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
| Metrics | EC2 default (AWS/EC2, no Agent required) | Requires Agent (CWAgent) |
|---|---|---|
| CPU | CPUUtilization, burst instance's CPUCreditBalance | Broken down by core, iowait, steal, etc. |
| Memory | ✗ Cannot see | mem_used_percent |
| Filesystem | ✗ Not visible (EBS only IOPS/Throughput, on AWS/EBS) | disk_used_percent (by mount point) |
| Network / Status check | NetworkIn/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 ascwagent, read journald, you need to add it to thesystemd-journalgroup).metrics:namespace(defaultCWAgent),append_dimensions(only supportedImageId/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(defaultinfo, i.e. info and more serious),matches(press_SYSTEMD_UNIT,_UIDand 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
| Data | Recommendations | Cost tips |
|---|---|---|
| Application log (myapp) | journald is collected by unit, priority info | Billed by ingested GB (ca-central-1 is about 0.5 USD/GB) |
| System log | Only collected err and above, or only use key units (sshd, kernel) | Full journald can easily count GB every day |
| Memory/disk | Once every 60 seconds, only using the InstanceId dimension | Each indicator × dimension combination is a custom indicator, billed monthly |
| Retention period | Experiment 1–7 days, production according to compliance requirements | New log groups never expire by default, be sure to set it |
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
Flowchart: Configuration delivery method
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.
Core Command
| Command | Function | Instructions |
|---|---|---|
sudo dnf install -y amazon-cloudwatch-agent | AL2023 installation | Ubuntu 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:… -s | Load configuration and start | -c ssm: parameter name; -a append-config Overlay multiple configurations |
…-ctl -a status / -a stop | Status/stop | Output JSON, including configstatus |
…/bin/amazon-cloudwatch-agent-config-wizard | Interactively generate configuration | Optional to save SSM parameters |
aws logs tail | View logs in real time on this machine | --filter-pattern |
aws logs put-retention-policy | Set retention period | Existing log groups will not be automatically changed by the Agent (unless configured retention_in_days) |
aws cloudwatch get-metric-statistics / put-metric-alarm | Query indicators/create alarms | Dimensions 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)
~/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.
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"
}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
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
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
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. 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
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
Official documentation
- CloudWatch agent configuration file (including journald section)
- Install the CloudWatch agent on EC2
- Metrics collected by the CloudWatch agent
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.
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.
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.
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.
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.
Module 6 · Patch and Compliance: SSM Patch Manager
dnf upgrade Display "No updates available"? Versioned Warehouse, Patch Baseline and Controlled Upgrades- Explanation of AL2023 Deterministic upgrade (versioned repository): By default, the instance is locked at the repository version when the AMI was built, and
dnf upgradewill not exceed it; usednf check-release-updateand--releaseverto actively upgrade. - Name the components of Patch Manager: patch baseline (approval rules, severity levels, automatic approval delays),
AWS-RunPatchBaseline'sScan/Install,RebootOption, compliance reporting. - Perform scanning and installation on the experimental instance, use
dnf needs-restarting -rto determine whether a restart is needed, and compare it with Ubuntu's unattended-upgrades.
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=latestmeans the latest.- Old version repositories are still available, so you can "lock on tested versions".
Why: Why Patch Manager
- Manual
dnf upgradefor 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)
- 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. - Run
AWS-RunPatchBaselinethrough Run Command, Maintenance Window, State Manager, or Quick Setup patch policy:Operation=Scanonly evaluates and reports compliance;Operation=Installinstalls approved patches. - 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 todnf upgrade --security …and includes other repository updates). - If there is an update after installation, the default
RebootOption=RebootIfNeededwill restart;NoRebootwill not restart, andInstalledPendingRebootwill be displayed in the compliance status. - 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
| Scenario | Recommended | Description |
|---|---|---|
| Immutable infrastructure (ASG, short life cycle) | Replace instead of patch: Refresh instances with the latest AMI weekly | Work with resolve:ssm or Image Builder |
| Long-running "pet" instances (this lesson) | Patch Manager weekly Scan, monthly maintenance window Install | Ensure that the service can start automatically (systemctl is-enabled) before restarting |
| Needs to be strictly reproducible | Lock --releasever, and then proceed after verification in the test environment | Custom baseline + explicit approval list |
| Ubuntu (control) | unattended-upgrades (security updates installed by default) + Patch Manager compliance scan | Ubuntu baseline AWS-UbuntuDefaultPatchBaseline |
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
Timeline: Versioned repository and locking
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".
Core Commands
| Command | Function | Description |
|---|---|---|
cat /etc/amazon-linux-release; rpm -q system-release | Current release build/locked version | AMI Build version number |
sudo dnf check-release-update | Whether there is a newer repository version | Output including recommended commands |
dnf check-update --releasever=latest | Preview which packages will be updated when upgrading to the latest | Do not change the lock point |
sudo dnf upgrade --releasever= | Upgrade and move lockpoint | -y non-interactive |
dnf updateinfo list --security --releasever=latest | List security advisories (ALAS) | --sec-severity=Critical |
sudo dnf needs-restarting -r | Whether restart is required | Exit code 1 = required |
sudo dnf supportinfo --pkg valkey | Software package support period | AL2023 specific plug-in |
aws ssm send-command --document-name AWS-RunPatchBaseline | Scan / Install | Operation, RebootOption |
aws ssm describe-instance-patch-states | Patch compliance summary | Installed/Missing/Failed Count |
aws ssm describe-instance-patches | Patch-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).
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" ]
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 |
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 ]
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)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". 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).
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
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
Official documents
- AL2023 Deterministic upgrades through versioned repositories
- AL2023 Manage package and OS updates
- How patches are installed
- Predefined and custom patch baselines
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.
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.
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.
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.
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.
Module 7 · Troubleshooting on the cloud: EC2 serial console, status checks and common faults
- 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.
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.
| Check | Detection objects | Typical reasons | Who will fix it / how to fix it | Indicators |
|---|---|---|---|---|
| System status check | The AWS system where the instance is located | Network connection loss, power loss, host software and hardware problems | Wait for AWS, or stop and restart (EBS Supported instances are typically migrated to new hosts); configurable automatic recovery | StatusCheckFailed_System |
| Instance status check | Your 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 fail | Yourself: Restart, modify configuration | StatusCheckFailed_Instance |
| Mount EBS status check | Whether the mounted EBS volume is reachable and can complete I/O | Storage subsystem, host or connection issues | Wait, or replace volume/stop and restart | StatusCheckFailed_AttachedEBS |
| Application status check (optional) | HTTP/HTTPS response you configured | Application unhealthy | Yourself | Subject 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)
| Tools | Need an instance network? | Need to log in? | What can be done |
|---|---|---|---|
describe-instance-status | No | No | Results and events of three types of inspections (planned maintenance) |
get-console-output --latest | No | No | Serial port (ttyS0) recent output: kernel, systemd, cloud-init messages |
get-console-screenshot | No | No | Current screenshot (JPG, base64) |
| Session Manager / EIC / SSH | Yes | Yes | General troubleshooting when the system is running normally |
| EC2 Serial console | No | Yes (password user required) | Interactive access to ttyS0: GRUB menu, emergency shell, login prompt; can also send SysRq |
| Rescue instance | No | No (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
| Phenomena | Do it first |
|---|---|
| System check failed | See AWS Health / Scheduled Events → Stop and restart (note that instance storage will be lost) |
| Instance check failed, system check passed | Console output → Serial console → Rescue instance |
| Both checks passed, but SSM is offline | Instance role, outbound network, Agent status (EIC or serial console to check) |
| All passed, able to log in, but the application is unavailable | systemd / journald / CloudWatch log (Lesson 2, Module 5) |
Decision diagram: from phenomenon to tool
Flowchart: Serial console connection link
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.
Core Command
| Command | Function | Description |
|---|---|---|
aws ec2 describe-instance-status --instance-ids $IID --include-all-instances | Three types of status checks + planned events | SystemStatus, InstanceStatus, AttachedEbsStatus |
aws ec2 get-console-output --instance-id $IID --latest --output text | Recent serial port output | --latest Get the latest (Nitro Support) |
aws ec2 get-console-screenshot --instance-id $IID | Screenshot | --query ImageData --output text | base64 -d > shot.jpg |
aws ec2 enable-serial-console-access / get-serial-console-access-status / disable-… | Account level (this region) switch | Close when finished |
aws ec2-instance-connect send-serial-console-ssh-public-key | Push the public key and start a serial session | --serial-port 0 |
ssh -i key $IID.port0@serial-console.ec2-instance-connect.ca-central-1.aws | Connect to serial console | Connect within 60 seconds; ~. Disconnect |
aws ec2 stop-instances + start-instances | Change 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/rescue | Mount the XFS root volume of the same AMI on the rescue instance | The 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)
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" }# 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
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.
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):
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
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 }/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.
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
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
Official Document
- Status checks for Amazon EC2 instances
- EC2 Serial Console prerequisites
- Configure access to the EC2 Serial Console
- Connect to the EC2 Serial Console (including endpoints and fingerprints of each region)
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.
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.
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.
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.
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.
Module 8 · Cost, Cleanup, and Self-Test
- 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.
What: The billing items for this course (ca-central-1 approximate price, subject to the official pricing page)
| Resources | Billing method | Usage of this lesson | Approximate cost |
|---|---|---|---|
EC2 t3.small | Billed by the second (minimum 60 seconds), about 0.023 USD/hour; no instance fee will be charged after stopping | About 2 Hours | ≈ 0.05 USD |
| t3 unlimited excess points | Extra billing by vCPU·hour when high CPU is sustained | This lesson is almost 0 | ≈ 0 |
| EBS gp3 | Based on preset capacity GB·month (about 0.088 USD), Stopped instance is still billed | 8 GiB root volume + 20 GiB data volume | ≈ 0.01 USD (2 hours) |
| EBS snapshot | According to the incremental data stored GB·month | Optional | ≈ 0 |
| Public IPv4 | About 0.005 USD/hour/address (including automatically assigned public IP and EIP) | 1, about 2 hours | ≈ 0.01 USD |
| CloudWatch Logs | Ingest by GB (about 0.5–0.6 USD/GB) + storage by GB·month | A few MB | ≈ 0 |
| CloudWatch custom metrics/alarms | Metrics are prorated on a monthly basis; standard alarms are about 0.1 USD each per month | 3 metrics + 2 alarms | < 0.01 USD |
| Session Manager, Patch Manager, Run Command, EIC, Serial Console | For 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 deletedelete 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
- CloudWatch alarm (to avoid false alarms after instance termination).
- Terminate the instance (label
Name=linux-lab) and wait forterminated; the root volume is then deleted, the network card is released, and the public IP is released. - Delete data volumes and experimental snapshots with status
available. - Delete the security group (must be after the network card is released, otherwise
DependencyViolation). - Remove the role from the instance configuration file → delete the instance configuration file → detach the hosting policy → delete the role (in the wrong order,
DeleteConflictwill occur). - Delete
/linux-lab/*log group, SSM parametersAmazonCloudWatch-linux-lab. - Confirm that serial console access is closed; retain budget alerts as needed.
When: Stop or terminate?
| Select | Still billed | Suitable |
|---|---|---|
| Stop | EBS volume, EIP (when not associated); the automatically assigned public IP will be released | Continue the experiment tomorrow |
| Terminate | Undeleted data volumes, snapshots, logs | End 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
Dependency graph: cleanup sequence
Cost composition (2-hour experiment, illustration)
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.
Core command
| Command | Function | Description |
|---|---|---|
aws resourcegroupstaggingapi get-resources --tag-filters Key=Name,Values=linux-lab | List resources in the region by label | Does not contain global resources such as IAM; some services do not support |
aws ec2 terminate-instances + wait instance-terminated | Terminate and wait | Termination protection needs to be turned off first |
aws ec2 describe-volumes --filters Name=status,Values=available | Find unmounted volumes | Common legacy |
aws ec2 describe-addresses | Elastic IP | Billing even if not associated |
aws iam remove-role-from-instance-profile / delete-instance-profile / delete-role | IAM cleanup | Detach policy first |
aws logs delete-log-group | Delete log group | Unrecoverable |
aws ce get-cost-and-usage | Query actual costs | Data 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)
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 textaws 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
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
get-resources The newly deleted resources may still be returned in a short period of time (eventually consistent). Check again after a few minutes. 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.
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
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
Official documentation
- EC2 On-Demand Pricing
- EBS Pricing
- VPC Pricing (Public IPv4)
- CloudWatch Pricing
- Resource Groups Tagging API: GetResources
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.
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.
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.
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.
Command Cheat Sheet
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 textIMDSv2
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 eiceCloudWatch 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
| Phenomena | Check first | Common causes | See |
|---|---|---|---|
| RunInstances report InvalidParameterValue (architecture) | AMI and instance type architecture | x86_64 AMI + Graviton | M1 |
| Instance 2/2 passed but the application did not start | cloud-init status --long, cloud-init-output.log | User data failed, package name error | M2 |
| Unable to locate in container credentials | hop limit | hop limit = 1 | M2 |
| IMDS returns 401 | With token or not | IMDSv1 script / old SDK | M2 |
| Enter emergency mode after restart | Console output | fstab no nofail, device name drift | M3 / M7 |
| TargetNotConnected | Instance role, outbound 443, Agent | Missing instance configuration file / private subnet no endpoint | M4 |
| Log group is empty | Agent log, units name | Permissions, filter conditions | M5 |
| dnf shows no update but CVE | dnf check-release-update | Versioned repository lock | M6 |
| Instance check impaired | Console output → Serial console | Startup failure, network configuration, OOM | M7 |
| Delete security group DependencyViolation | Network card | The instance is not completely terminated | M8 |
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
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.
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). 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. --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}'aws ec2 wait instance-status-ok; get-console-output --latest "linux-lab user data finished" appears; in SSM PingStatus=Online. 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. 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. AWS-RunPatchBaseline Operation=Scan and record the number of Missing; if it is not 0, scan again after Install + RebootIfNeeded . 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
| Topic | Verification conclusion | Source (accessed 2026-11-17) |
|---|---|---|
| AL2023 support cycle | 2023-03 release; standard support until 2027-06-30 (quarterly version); maintenance period until 2029-06-30 | Release cadence |
| AL2023 Current Release | 12th Quarter Release 2023.12; latest build 2023.12.20261112; 6.1 / 6.12 / 6.18 kernel AMI available | 2023.12 release notes |
| Default kernel and SSM parameters | From 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 package | systemd 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-30 | All packages in AL2023.12 |
| valkey unit name | Fedora Packaging specifications: valkey.service, valkey-cli, configuration /etc/valkey/valkey.conf; not in AL2023 list valkey-compat-redis | Fedora 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 099720109477 | Find Ubuntu images on AWS |
| IMDSv2 | PUT /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 supported | How IMDSv2 works |
| AL2023 IMDS default | AL2023 AMI ImdsSupport=v2.0: only IMDSv2, hop limit 2; account-level default available modify-instance-metadata-defaults Settings | AL2023 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 expiration | Retrieve security credentials |
| user data | Original 16 KB limit; run as root; output /var/log/cloud-init-output.log; script stored in /var/lib/cloud/instances/ | User data |
| NVMe / EBS | Device /dev/nvme In enumeration order, may vary; serial number = volume ID; Amazon Linux udev creates /dev/sdf link; ebsnvme-id; other distributions nvme id-ctrl -V | Map EBS volumes to NVMe device names |
| Instance Storage | Restart retained; stop, hibernate, terminate lost | Instance store data persistence |
| SSM Agent pre-installed / Session Manager | AL2023 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 session | Preinstalled agent · Session Manager prerequisites |
| EC2 Instance Connect | AL2023 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. | Install EIC · Connect methods |
| CloudWatch Agent | logs_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_dimensions | Agent configuration file |
| Versioned repository | Default 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 startup | Deterministic upgrades |
| Patch Manager | AWS-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 RebootIfNeeded | How patches are installed · Baselines · Package selection |
| Status check | Five categories: system, instance, attached EBS, application (optional), performance (accelerated instance); per minute; indicators StatusCheckFailed_System/_Instance/_AttachedEBS; Instance check probes network card via ARP | Status checks |
| EC2 Serial Console | Nitro 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 | Prerequisites · Connect |
| Price | t3.small, gp3, public IPv4 (approx. 0.005 USD/hour), CloudWatch are all ca-central-1 approximate values | EC2 · 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 valkeyandgrep '^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-agentto 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.