Chapter 14: EC2 Operations — Elastic IP, AMI, Snapshots and Vertical Scaling
14.2 AMI (Amazon Machine Image)
In short: An AMI is a template used to launch instances.
What is an AMI?
Friends, an AMI supplies a reusable starting image for EC2. The new instance still needs compatible capacity, launch settings and a verified application start.
मित्रांनो, AMI मधून नव्या EC2 instance साठी सुरुवातीची image मिळते. Instance type, launch settings आणि application नीट चालते का ते स्वतंत्र तपासा.
दोस्तों, AMI नए EC2 instance के लिए शुरुआती image देती है। सही instance type, launch settings और application के चालू होने की अलग से जाँच करें।
An AMI is a template used to launch instances. It is made of:
| Part | Meaning |
|---|---|
| Root volume snapshot(s) | EBS snapshot of the OS disk (plus any extra data volumes included) |
| Block device mapping | Which volumes to create at launch, their sizes, types and device names |
| Launch permissions | Who can use it: only your account, specific accounts, or public |
| Metadata | Architecture (x86_64/arm64), virtualization, boot mode, ENA support, description |
Launching this EBS-backed AMI creates new volumes from the referenced snapshots as described by its device mapping. The instance receives its own runtime identity and launch settings. External data, live sessions and data on instance store must follow their own recovery plans.
| AMI type | Provided by | Examples |
|---|---|---|
| AWS/Quick Start | AWS and OS vendors | Amazon Linux 2023, Ubuntu 24.04, Windows Server |
| AWS Marketplace | Software vendors (may include software charges) | Hardened OS images, WordPress by vendors, firewalls |
| Community AMIs | Anyone who made an AMI public | CentOS Stream images, custom builds (verify the publisher!) |
| My AMIs | You | Your own configured web server |
Create an AMI from a configured instance
Suppose your web-1 from Chapter 7 or 9 is working perfectly. Let's make a reusable image of it.
Step 1 — Prepare a clean image: use a dedicated builder with non-sensitive lab data. Check the disks you plan to include for stored credentials, private keys, logs and user data. Revoke or rotate any credential that was already exposed. Clearing shell history alone does not remove secrets from the image.
Step 2 — Create image: EC2 → Instances → select web-1 → Actions → Image and templates → Create image.
- Image name:
web-nginx-v1, description:Nginx + mysite, tested. - Plan the capture during a suitable builder window. The default reboots the instance. Choose the documented no-reboot option only when the captured consistency is appropriate for the workload.
- Instance volumes: review sizes/types; add tags → Create image.
Step 3. Check the image state and its backing snapshot mappings. Wait for the image to become available before an authorized test launch. The time varies with the work and volume data.
| Capture choice | Behavior | What to validate |
|---|---|---|
| Default reboot | EC2 reboots the source before creating the image to flush written volume data. | Plan the interruption and test important application and external state separately. |
| No reboot | EC2 skips reboot and captures crash-consistent written volume data. | Confirm how the application recovers, including buffered data and state outside the included volumes. |
Launch a new instance from your AMI and verify
- Choose the intended available AMI in the correct account and Region.
- Select a compatible instance type, expected boot mode and approved launch settings. Use an isolated candidate for the first check.
- Verify instance readiness, data mounts, application release and one known data-backed request before moving any public traffic.
Things that differ on the copy
The new instance gets a distinct instance ID and its launch-selected network settings. A public IPv4 address depends on its configuration. Verify any hostname, service endpoint and external dependency before transferring traffic.
Copy an AMI to another region
An AMI copy has its own destination Region and AMI ID. For an approved copy, choose destination encryption and key settings as needed. Reapply intended launch permissions in the destination, wait for availability and test a launch there using the target network and data configuration.
Share an AMI with another AWS account (brief)
To share privately, grant intended AWS accounts launch permission on the owned AMI. For encrypted backing snapshots, verify customer managed KMS key rights. Images backed by snapshots encrypted with the default AWS managed EBS key cannot be shared across accounts this way. The recipient should verify an authorized launch. Copying a shared AMI has its own backing storage and key access requirements.
Deregister an AMI and delete its snapshots
Deregister an AMI after reviewing active launch templates and planned recovery. Existing instances use their current volumes, while a future launch still depends on an available image. The default deregistration keeps EBS snapshots.
The documented associated-snapshot deletion option skips snapshots referenced by multiple AMIs. Check the exact backing IDs, ownership and recovery dependencies, then verify which assets were actually removed or retained.
The golden AMI idea
A golden AMI supplies a versioned, approved starting build with common software. Automate patching and tests where appropriate, and verify the candidate with its intended launch settings. Separate the baked software from instance identity, networking and current application data.
Ravindra Bagale's Tip
Before a maintenance change, identify the required image and data recovery points. Use a clear version name. Rehearse launching an alternate instance, verifying its application and data, and restoring the intended traffic path.
Ravindra Bagale's Tip – मराठी
Maintenance बदलाआधी image आणि data साठी recovery point ठरवा. स्पष्ट version नाव द्या. स्वतंत्र instance launch करून application आणि data तपासा आणि traffic परत कसा आणायचा ते आधी सरावात पाहा.
Ravindra Bagale's Tip – हिंदी
Maintenance से पहले image और data के लिए recovery point तय करें। साफ़ version नाम दें। अलग instance launch करके application, data और traffic वापस लाने की प्रक्रिया का परीक्षण करें।
Lab
खालील private lab मध्ये image compatibility, दोन स्वतंत्र app copies आणि त्यांचा data तपासा. Real EC2 test साठी स्वतंत्र builder आणि मंजूर test instance वापरा. योग्य release आणि known record तपासल्यावरच recovery यशस्वी म्हणा.
Prepare a replacement that starts from a known server build
Suppose the team runs a small inventory application on EC2. The server needs a supported operating system, web service, app release and initialization configuration. When a new trainee creates another server, part of the setup can be missed. Maybe the right process was installed but never starts at boot, or a runtime package differs from the version used for testing. The team wants repeatable launches. They also want to test a clean replacement without configuring every package by hand during an incident.
An Amazon Machine Image is a regional EC2 resource containing the information needed to set up and boot an instance. In this lesson the root device is backed by Amazon EBS. Its root snapshot contains saved blocks from the original root volume. A block device mapping describes which devices to provide when launching, including snapshot-backed EBS volumes when mapped that way. The image carries metadata such as processor architecture, root device type, virtualization type and supported launch properties. An image has launch permissions which determine who can use it. When you launch a new instance from the image, EC2 can make new EBS volumes from the referenced snapshots.
This is a good way to package intentionally selected software and files. It is not a full record of every part of a server's running environment. A different instance gets its own identity and launch settings. Its RAM and existing connections are not transferred. Data on an external database, an object storage service or a mounted network file service is managed separately. An inventory application can launch with the right package build and still read the wrong data until you set its runtime environment. Write down which things depend on the image and which belong to the target deployment.
For example, the warehouse team builds version inventory-web-2026-11. The image contains a Linux filesystem, installed packages and a non-sensitive application release. The launch plan chooses an instance type supported by the image architecture, an approved subnet, a security group, a role and operational settings for that new copy. After launch, the application reads its actual dataset through that role or another sanctioned credential path. The team verifies the correct asset or release marker and a known record before moving any customer address. A bootable image gives them a repeatable starting point with a smaller setup burden.
Separate snapshots, AMI metadata and launch parameters
| Resource or state | Purpose | Question for the builder |
|---|---|---|
| EBS snapshot | Point-in-time volume data used as the source for a new EBS volume | Is this the intended data for this device? Can it be restored and verified? |
| EBS-backed AMI | Bootable image configuration, with device mappings, metadata and permissions | Can the selected intended instance boot and use the mapped volumes? |
| Launch template version | Reusable launch choices, including a selected image ID and other settings | Which exact version specifies the desired network, instance and initialization settings? |
| Running deployed application | Started process and correct external dependencies for a distinct environment | Does it serve the expected request and data after a fresh launch? |
A volume snapshot supplies disk blocks, not every field required to boot an EC2 machine on its own. AWS supports creating an EBS-backed AMI from an appropriate root volume snapshot via a documented procedure, but the resulting AMI still requires the correct registration metadata and mapping. Conversely, an AMI references the bootable source and any additional EBS snapshots that were included. Two launches can share the same reference image while writing to different new volumes. They do not share the writable state of those volumes by default. Saving the root image doesn't capture state on a separate EBS volume that the builder intentionally excluded.
Instance store is temporary storage provided by supported instance types. A mapping might describe an instance store device for a launch. Its future device does not contain data stored on the original instance's store. Move any required data into durable storage before relying on an image-based recreation. If the application uses a local mount, record what backs that path. A directory name cannot tell you whether it lived on the root disk, extra EBS, instance store, or another server. Use the guest mount evidence and EC2 attachment metadata together.
Instance type and processor architecture are separate choices. An image with an x86_64 operating system and native programs does not become an arm64 image by selecting a Graviton instance type. A compatible instance type must support the architecture and related launch format. Boot mode matters as well. An image can specify UEFI, legacy BIOS or a supported preference. The underlying operating system needs to support the effective boot choice. A metadata field alone cannot retrofit a missing bootloader. Depending on platform and image, compatible virtualization, drivers and other features matter too. Resolve those before launching and still verify a real boot on the chosen test instance.
Launch templates store reusable values such as an AMI ID, instance type and network settings. They can have numbered versions. Choosing image version three in a build pipeline does not automatically update a fleet that references the launch template's default or a specifically older version. Record both IDs. Check which version an Auto Scaling group, deployment or operator actually uses before you update or retire an image. The image can be good and available while a launch still uses yesterday's version because it followed a different version reference.
Capture from an intentional builder and verify what was written
Begin with a dedicated image builder whenever possible. Install and configure what every instance should share. Record the source image ID, operating system patches, package versions and the application release you intend to bake in. Keep build logs and the owner criteria outside the candidate image. Choose which configuration belongs in the disk image and which belongs at launch. For example, a generic startup service is reusable. A machine-specific private backend address, cached short-lived credentials or an old hostname may not be appropriate. A secret saved into an included disk can become part of the image and reachable by someone who can launch or read that backing data.
Inspect the builder's intended volumes for access tokens, service credentials, shell artifacts, private keys, private user data or sensitive logs. Removing one shell history file is not a full image sanitization plan. If a credential was already exposed, follow your credential response and rotation process. Provide the runtime with its approved role and secret mechanism. For a replacement, a trusted startup method can use its own identity rather than reusing a credential copied from an old instance. Keep the AMI's launch rights limited to the intended accounts or organizations under the sharing plan.
On an EBS-backed instance, the console's image-creation action registers an AMI and creates the backing snapshots. Review the intended volumes and device mappings before submitting. Decide how to handle writing applications. With the default reboot behavior, the operation reboots the instance to help reach a consistent volume state. A running source serving customers can be interrupted, so use a dedicated builder or schedule the impact. An explicit no-reboot choice skips that reboot and creates crash-consistent snapshots of associated EBS volumes. These capture the written data. Buffered changes and memory not written to the volumes are outside that captured state.
A crash-consistent result resembles what storage contains after an abrupt interruption. An application may be able to recover using its journal or write-ahead log, but verify its recovery behavior and any relationships across streams and remote services. An application-consistent capture is planned so the relevant data satisfies the application's own consistency requirements. Choose documented quiesce, backup or checkpoint steps for the application and its data stores. A successful AMI registration and completed snapshots alone do not certify that an application transaction, an external database or multiple independent services can be restored together.
Check the resulting image's state and captured device mappings. The image can take time to become available, especially with substantial data and backing snapshot work. Use the documented state observations or a bounded waiter and record failures. If you discover a required volume was excluded, do not try to infer its content from the root filesystem. Decide whether to recapture using the right plan or to restore and attach its separate approved backup. The next EBS snapshot lesson makes independent data restoration concrete.
Verify a fresh launch before trusting it as a recovery option
Choose a representative but isolated destination for the first launch. Match the architecture, boot mode, root device and expected instance features. Use the intended launch template version or equivalent documented parameters. The subnet and security group decide the network path. Set the approved instance profile so the new instance can use its own role where required. Supply only the intended launch-time data. A launch template allows you to reproduce those parameters separately from saving operating system and app files in the AMI.
Watch the state transitions at three levels. First the AMI should be available and visible to the intended account in the target Region. Next the instance should launch with its expected ID, reach the relevant status checks and expose the expected booted configuration. Finally, verify the app on a network path it is intended to serve. Read the version marker and a known record. Check any extra volume is attached and mounted under the path your program actually uses. Stopping the review when EC2 says “running” would miss an instance with no useful app listener, output from a default site or data from the wrong environment.
For example, the new inventory app should return its build marker and the expected eight cartons for item A-17. Test through its designated hostname so the right web configuration handles the request. If its launch script failed, the server can still boot and pass a lower-level check. Inspect launch or cloud-init logs and the actual runtime manager for evidence of startup and dependency failures. A database network rule or credential can be wrong even with the expected image build. If the migration plan uses an Elastic IP, keep it on the previous target until the candidate satisfies the separate launch and application checks.
These AWS CLI examples are read-only and are shown for an authorized lab operator with the intended account and Region selected. Use the correct owner and exact image ID for the release you chose. A result should be compared with the build record, not accepted simply because its name looks familiar.
aws --profile "$lab_profile" --region "$lab_region" ec2 describe-images \
--owners self --image-ids "$candidate_ami" --output json --no-cli-pager
aws --profile "$lab_profile" --region "$lab_region" ec2 describe-instance-types \
--instance-types "$candidate_type" --output json --no-cli-pager
aws --profile "$lab_profile" --region "$lab_region" ec2 describe-instances \
--instance-ids "$launched_instance" --output json --no-cli-pager
The original owner lookup matters for public and shared images as well. Confirm the publisher through a trustworthy channel and record the actual ID selected for the deployment rather than trusting a matching public name. An AMI can carry software terms or fees depending on its source. Review licensing, support and operating system defaults before adopting an image. A candidate for a classroom exercise that boots and serves a page is a different assurance level from a maintained production base image.
Copy or share the image with the destination requirements in view
An AMI ID is regional. The image resource used in one Region must exist in the Region where you plan to launch. Copying an EBS-backed AMI to another supported Region makes a target image and copies or creates the relevant snapshot backing under the copy rules. The resulting AMI has a destination ID. Record the exact destination Region, image ID, encryption and any destination key requirements. Check the copy state there and perform a new test launch. Copy work itself can bring snapshot storage, data transfer or optional time-based copy charges under the documented rules.
Suppose a recovery plan starts with a source AMI in Mumbai and creates a destination image in Hyderabad. The existing source launch template probably refers to Region-specific subnets, security groups, keys and IDs. Copying the AMI does not transform those launch parameters into resources in Hyderabad. Update an independently reviewed destination launch plan. Ensure the appropriate account can use its intended key and attached snapshots. Verify the destination runtime configuration, data source and public or private service entry. An image copy that becomes available still leaves those dependencies to the recovery design.
Launch permissions are scoped to the AMI resource. AWS does not automatically copy the source AMI's launch permissions to a new AMI. Reapply only the desired permissions in the destination after checking the copy. Sharing privately grants specific accounts access to launch the image where allowed. It keeps ownership with the original account. Copying a shared AMI can produce a separately owned image in the receiving account if the required backing-storage and key access are in place. Check the official permissions for that particular operation instead of assuming that the ability to list an image gives permission to copy it.
For an image with encrypted snapshots, separate the image launch permission from the KMS key authorization. AWS KMS is the service managing encryption keys and their access policy. An AMI backed by snapshots encrypted with the default AWS managed EBS key cannot be shared across accounts in this way. Customer managed keys can support the documented cross-account permission model when the account and identities are authorized to use the appropriate key. Confirm the source and destination policies and actual launch or copy result. Do not set a broad key policy to make a practice error disappear. The image, volume snapshot, account identity and KMS key have distinct roles.
Use a staged rollout for a standard or golden image. A golden image is the team's approved reusable baseline, maintained with an intentional update and test process. Keep versioned build inputs, record which instance types and deployment profiles passed and promote the tested image ID through an approved version of the launch template. A new build can retain old tests and still prove patches and runtime dependencies. Revise the image over time. Launching fresh instances from it creates a repeatable starting environment, but startup inputs and data can still differ among instances.
Retire images and their snapshot dependencies deliberately
An already running instance continues using its own volumes if the image it was launched from is deregistered. Deregistering changes the ability to launch new instances from that image. This matters for auto scaling, disaster recovery or a future rollback even when existing fleet members appear healthy. Check all deployed launch template versions, deployment automation, other account consumers and planned retained versions before removing an image. An older resource can still be active in a launch or rollback plan.
By default, deregistering an EBS-backed AMI leaves its backing snapshots. EC2 also offers an option to delete associated snapshots during deregistration. A snapshot referenced by multiple AMIs will not be deleted by that combined operation even if requested. Verify the actual results and ownership for each item. A name or description that contains a target AMI ID is useful context, but it does not establish that the associated backing snapshot is unneeded. Treat image and data retention separately and check use by recoveries or other launchable images.
Check whether your organization uses deregistration protection or a Recycle Bin retention rule for relevant assets. Such features have their own policies and scope. Without an applicable recovery path, retiring an image can leave the desired launch version unavailable. The safe learning exercise keeps all its changes in a scratch tree. For live resources use your team's authorized retention plan. Record which images, snapshots, volumes and test instances remain after cleanup, and review incurred storage charges against actual inventory.
Lab: verify compatibility and test two launches from one local release
Use an ordinary Bash shell and Python 3. The first check replays selected AWS metadata fields and local launch instructions. The second check starts two actual loopback HTTP services from copies of one tiny release tree. It demonstrates an image's reusable content and the separate launch-specific runtime settings and data. A file copy on your laptop cannot boot an EC2 instance or create an AMI. The fixture only covers those distinctions and the reported acceptance checks. It needs no AWS profile, host privileges or existing database.
Step 1. Prepare sample image and launch choices
set -eu
command -v python3 >/dev/null
umask 077
ami_lab=$(mktemp -d /tmp/rb-ami-release.XXXXXX)
ami_cleanup() {
case "$ami_lab" in
/tmp/rb-ami-release.??????) rm -rf -- "$ami_lab" ;;
esac
}
trap ami_cleanup EXIT
mkdir "$ami_lab/image"
printf '%s\n' '{"service":"inventory","release":"2026.11-green"}' > "$ami_lab/image/release.json"
cat > "$ami_lab/metadata.json" <<'JSON'
{
"region": "ap-south-1",
"expected_owner": "111122223333",
"image": {
"ImageId": "ami-00000000000001101",
"OwnerId": "111122223333",
"State": "available",
"Architecture": "x86_64",
"BootMode": "uefi",
"RootDeviceType": "ebs",
"RootDeviceName": "/dev/xvda",
"VirtualizationType": "hvm",
"BlockDeviceMappings": [
{
"DeviceName": "/dev/xvda",
"Ebs": { "SnapshotId": "snap-00000000000001101", "Encrypted": true }
},
{
"DeviceName": "/dev/sdf",
"Ebs": { "SnapshotId": "snap-00000000000001102", "Encrypted": true }
}
]
},
"target": {
"Region": "ap-south-1",
"ProcessorInfo": { "SupportedArchitectures": ["x86_64"] },
"SupportedBootModes": ["uefi", "legacy-bios"],
"SupportedRootDeviceTypes": ["ebs"],
"SupportedVirtualizationTypes": ["hvm"],
"RequiredDataDevice": "/dev/sdf"
}
}
JSON
Find the root and data snapshot records separately. The root entry supplies the boot filesystem in this example. The app requires the data mapping too. The target has a requested deployment Region and other normalized settings in addition to selected type characteristics. Region and application storage requirements come from your chosen context, rather than appearing as those fields in an AWS type response. The fixture labels the disk image release once. Each started app receives its own runtime data after this step.
Step 2. Check the plan, then test two independent launches of the sample application
cat > "$ami_lab/check.py" <<'PY'
from contextlib import contextmanager
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.request import ProxyHandler, build_opener
import json
import shutil
import sys
import threading
root = Path(sys.argv[1])
record = json.loads((root / "metadata.json").read_text())
def require(value, message):
if not value:
raise ValueError(message)
def check_launch(image, target):
require(target["Region"] == record["region"], "image not in target Region")
require(image["OwnerId"] == record["expected_owner"], "unexpected image owner")
require(image["State"] == "available", "image is not available")
require(image["Architecture"] in target["ProcessorInfo"]["SupportedArchitectures"],
"processor architecture mismatch")
require(image["BootMode"] in target["SupportedBootModes"], "boot mode mismatch")
require(image["RootDeviceType"] in target["SupportedRootDeviceTypes"], "root type mismatch")
require(image["VirtualizationType"] in target["SupportedVirtualizationTypes"],
"virtualization type mismatch")
snapshots = {
entry["DeviceName"]: entry.get("Ebs", {}).get("SnapshotId")
for entry in image["BlockDeviceMappings"]
}
require(snapshots.get(image["RootDeviceName"]), "missing root snapshot")
require(snapshots.get(target["RequiredDataDevice"]), "missing required data snapshot")
def reject(action, expected):
try:
action()
except ValueError as error:
require(str(error) == expected, f"wrong rejection: {error}")
print("Rejected:", error)
else:
raise AssertionError("unexpected acceptance")
image, target = record["image"], record["target"]
check_launch(image, target)
print("Selected image and test target match the sample launch requirements.")
reject(lambda: check_launch(image, {**target, "Region": "ap-south-2"}),
"image not in target Region")
reject(lambda: check_launch(image, {
**target, "ProcessorInfo": {"SupportedArchitectures": ["arm64"]},
}), "processor architecture mismatch")
reject(lambda: check_launch(image, {**target, "SupportedBootModes": ["legacy-bios"]}),
"boot mode mismatch")
reject(lambda: check_launch({**image, "BlockDeviceMappings": image["BlockDeviceMappings"][:1]}, target),
"missing required data snapshot")
def create_copy(label, count):
destination = Path(shutil.copytree(root / "image", root / label))
(destination / "instance.json").write_text(json.dumps({"instance": label, "stock": count}))
return destination
@contextmanager
def launched_at(destination):
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path != "/inventory-check":
self.send_error(404)
return
base = json.loads((destination / "release.json").read_text())
launch = json.loads((destination / "instance.json").read_text())
payload = (json.dumps({**base, **launch}) + "\n").encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
self.wfile.write(payload)
def log_message(self, format, *args):
pass
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
worker = threading.Thread(target=server.serve_forever)
worker.start()
try:
yield f"http://127.0.0.1:{server.server_port}/inventory-check"
finally:
server.shutdown()
server.server_close()
worker.join()
client = build_opener(ProxyHandler({}))
def read(address):
with client.open(address, timeout=4) as reply:
require(reply.status == 200, "HTTP request failed")
return json.load(reply)
def accept(result, instance):
require(result["release"] == "2026.11-green", "wrong app release")
require(result["instance"] == instance, "wrong test target")
require(type(result["stock"]) is int and result["stock"] == 8, "wrong application data")
first = create_copy("test-blue", 8)
second = create_copy("test-green", 0)
with launched_at(first) as first_url, launched_at(second) as second_url:
accept(read(first_url), "test-blue")
reject(lambda: accept(read(second_url), "test-green"), "wrong application data")
(second / "instance.json").write_text(json.dumps({"instance": "test-green", "stock": 8}))
accept(read(second_url), "test-green")
accept(read(first_url), "test-blue")
print("Both copies now serve their distinct identity, expected release and stock.")
require((root / "image" / "release.json").read_bytes() == (second / "release.json").read_bytes(),
"source release changed")
require(not (root / "image" / "instance.json").exists(), "launch data leaked into the image")
PY
python3 "$ami_lab/check.py" "$ami_lab"
The plan rejects an image scoped to the wrong Region, a candidate CPU mismatch, a missing firmware mode and an excluded data snapshot. This code validates a selected known case. It is not a general EC2 launch planner and doesn't check every possible offering, key, driver or AMI policy. In particular it assumes a UEFI-only requirement for this image. uefi-preferred or an absent value would need the appropriate AWS decision rules. A clean metadata check leaves the need to try a real approved launch intact.
The two Python servers have different instance identifiers and separate launch files, but the same version from the image-like release tree. Both initially answer HTTP 200. The second still fails the known data check. Correcting its fixture's attached runtime data produces the expected result and the first app still passes. Confirm that the source directory retained only reusable release content. The count update in one copy does not overwrite any baked release or peer data. The servers close their own ephemeral loopback ports when the check finishes.
Step 3. Remove the learning fixture
ami_cleanup
trap - EXIT
test ! -e "$ami_lab"
printf 'Local AMI rehearsal files removed.\n'
The scratch cleanup removes only directories and files created by the exercise. In a separate real EC2 lab, record actual test instances, their volumes, retained image, and captured snapshots. Clean up only the objects that your owner has marked for deletion. Inspect the actual resource state after any permitted cleanup. Keeping a tested image for a later recovery and deleting a disposable local directory are different retention decisions.
Follow the data device from the launch record to the application mount
Take the sample builder's root mapping /dev/xvda and extra mapping /dev/sdf. The first points to a root snapshot that provides the software. The second points to an approved captured data volume for the exercise. After a launch from these mappings, you can observe two new volume IDs. These are the individual EBS volumes created for this instance. A second launch can use the same snapshot references and still get different volume IDs. In the cloud management view, check which new EBS volume corresponds to each intended mapping and snapshot.
Inside a Linux guest on an applicable Nitro-based instance, the OS can expose EBS devices with names such as /dev/nvme0n1 and /dev/nvme1n1. Their enumeration order may differ across starts. The label used in the AMI block device mapping is not necessarily the name the guest program sees. Use supported device identification to cross-check the EBS volume ID, partitions and filesystem. Inspect the actual mount before performing any filesystem action. An image copied from an old host can still contain a mount setting that assumes an unreliable name. That problem can show up when testing a fresh compatible instance with otherwise valid snapshots.
On an authorized test Linux instance, use a read-only listing such as lsblk to inspect devices, partitions and filesystems, and use findmnt to show the source behind the intended application mount. Consult the AWS method for identifying EBS volumes on the selected OS. Updated deployment procedures can refer to a suitable stable identifier, but check for duplicate filesystem identifiers when reattaching copies. The final evidence should connect the intended EC2 volume, the guest filesystem and the application input. A path can exist on the root filesystem even when the expected extra volume was never mounted there.
For example, the inventory service starts from the expected image and reads the directory /srv/inventory-data. If the intended filesystem didn't mount, that directory could be empty or contain older builder data. The app might create a fresh local file and return a successful response with default stock. Comparing the image marker and HTTP status wouldn't catch it. Check the actual mount and the expected item. Keep the recovery test isolated so a mistaken path cannot write into the wrong production store.
Think about what evidence remains if you retain the image for a future launch. Record the relevant snapshot and intended additional device. Keep the guest's mount and setup procedure versioned with the launch settings. If the data will be restored independently under its own policy, record that relationship and the required timing. A clean future launch should demonstrate the correct captured app release and mount distinct new volumes before it receives the production network entry.
If the mount tests pass but the service still opens the wrong file, inspect the configuration loaded by the running process. A stored path, environment variable or application config can override an expected mount. The verification should report the effective storage path and the observed record. These details make a failure actionable after the builder instance has already been removed.
Decide what to restore when an application release fails
Suppose your team upgrades a dependency on inventory release one. After the upgrade the web service still answers a status request, but orders no longer see the latest stock data. A teammate suggests “undo the server with the AMI.” Start by naming what you intend to go back to. An AMI can supply a previous replaceable host build. If the current database schema or latest transactions changed after that AMI was captured, launching the old host may not give the correct data or understand its current schema. The image recovery plan and the data recovery plan must agree about what the older application can use.
On an intentionally replaceable web tier, you could keep a known launch template version referencing a tested older AMI. Launch a replacement privately with the intended current configuration and data access. Test its exact release, a known inventory item and any important write or authorization workflow in an approved test environment. If those results meet the rollback plan, switch the customer entry to the ready service. This may involve a target group or another traffic mechanism, among other options. Verify the request at the actual entry and protect other site traffic. The image by itself does not shift customer routing.
Consider a different application whose database lives on a separately attached EBS volume. Keeping a root image without a copy of the data volume might still allow you to start the host and its process. Querying the mounted directory can return empty or stale state if the new instance uses a different device or no device at all. The device mapping helps attach a new filesystem based on an included snapshot. The guest still has to mount it at the right path, potentially using its filesystem UUID or another documented identity. Check the mounted device and a known record rather than assuming that an EC2 attachment means data is mounted. Storage outside the image must follow its own restore procedure.
Protect accidental repeat launches by controlling what starts on a replacement instance. An image baked from a scheduled worker can contain a service that starts doing real work as soon as the candidate has network access. A second process could duplicate scheduled operations during a rehearsal. Plan the launch-time identity, task enablement, and approved isolated data or service endpoints. Test its role before it interacts with customer systems. It is easier to validate a sanitized reusable builder than to copy an arbitrary production machine and retrospectively find all the services it might start.
Add two independent time targets to your plan. The first describes how much recovery time you aim for, which includes launching, readiness tests and traffic changes. The second describes how much accepted data change you can afford to lose, if any. An image date alone cannot demonstrate either. Measure an actual authorized recovery rehearsal with the real dependencies or an appropriate isolated representation. Record how you validate data that was accepted after the image was created. This prevents an old working root volume from being mistaken for a full business recovery point.
Suppose the replacement has the expected release marker but responds with the same instance identity or hostname as the original. It may have inherited unsuitable local instance-specific state through the build. Review how the operating system and initialization tooling prepare newly launched machines, including identity, host keys and any centralized registrations. Use that platform's supported image-preparation process on a dedicated builder. In an acceptance check compare an expected shared release and distinct instance identities. A basic HTTP status would see only that a web server exists.
Write a promotion record that follows the exact image through its lifecycle
A small promotion record improves reusability. Record the source base image and ownership, the image built for your project, firmware and architecture requirements, mapped snapshot IDs, and how the fleet starts it. Use test data, network and key policies suitable for the destination. Include release marker, known record and successful launch timestamp. Keep the build inputs and logs under version control or an appropriate archive. A descriptive AMI name is useful to a person scrolling the console. The image ID, owner and Region are more dependable keys for an exact launch and review.
| Stage | Evidence to keep | Example issue it can catch |
|---|---|---|
| Image capture | Builder, approved volumes, capture mode, registered identity and owner | Required data device excluded, or sensitive file captured |
| Copy or sharing | Destination image and account, required key and launch permissions | Destination lacks the source permission or cannot access its key |
| Candidate launch | Exact template version, compatible type and intended mounted devices | Old launch-template version or wrong firmware support |
| App test | Expected endpoint, version marker, known record and process logs | Running instance returns a default page or stale inventory |
| Retirement | Remaining launches and rollback references, image and snapshot dependencies | Deregistering an image used by a scaled replacement |
Walk through a concrete example. The build creates image ID one in Mumbai and copy ID two in Hyderabad. The app release string is still 2026.11-green on both. The destination uses template version seven and its own approved network, with an account role that can reach its appropriate data and key. The image owner shares the intended image as documented. The receiving account must test actual launch using its launch identity and selected target, since merely seeing the AMI in a list proves one permissions check at most. Compute and data assumptions may differ between Regions even for equivalent images.
Suppose a launch template in the destination still refers to image ID one from Mumbai. Its version number and the expected AMI name in a handwritten runbook look right, but the destination still has no valid reference for that launch. Update the approved version to the copied ID and verify which consumers selected that version. This is also why you should treat “latest template” and “default template” as specific configuration choices. Pinning a known version in an explicit test clarifies which parameters were actually exercised. Updating one template version cannot change existing app instances unless a wider rollout replaces them.
When a newer image is proven, decide how to discourage new use of the old one while preserving any approved rollback. Deprecating an image usually hides it from ordinary discovery for consumers, but existing launch references that name its ID can still use it. It is a lifecycle signal. Deregistering removes normal launch availability and affects future capacity creation even if the existing service stays healthy. Review the actual consumers and retention plan before either action. Include snapshot links in that review because storage can remain after an AMI is retired.
For a stored asset backed by a customer managed key, key plans need to outlast any authorized recovery that depends on it. Confirm the key's status, use rights and the destination Region's key choice for a copy. A snapshot retained for months may be useless to a recovery workflow that loses permission to decrypt it. Demonstrate it with a test launch or supported restore in the intended account. Stating “encrypted backup exists” does not demonstrate recoverability. Key access, image permission and data integrity are separate observations.
Explain the launch and recovery choices
Interview questions
What does an EBS-backed AMI supply when you launch an EC2 instance?
It provides a software image and EC2 registration properties, including boot and architecture details and the device mappings that can reference EBS snapshots. Launch creates a distinct instance with its own runtime settings and volumes. A launch template can name that image while supplying the launch parameters. Verify the actual app and required data after it boots.
What changes when using the no-reboot option to create an AMI?
EC2 skips rebooting the source and creates crash-consistent snapshots from the written volume blocks. Buffered data and process memory aren't included. This may be appropriate for a controlled builder or a quiesced app under its documented procedure. Plan a separate app or data restore check rather than relying on an available status.
Why can a copied AMI fail when the source launches successfully?
The destination has its own image ID and launch settings. It may use different network, instance offering, role, permissions and KMS requirements. Copying the image doesn't move a live resource or transfer its launch permissions automatically. Verify a candidate in the intended destination with a real application request.
What can break if you deregister an image that no running instance currently needs for I/O?
New launches using that ID can fail, including auto scaling replacements or a planned rollback. The existing instance uses its own current volumes, so it may still work. Review future launch references and snapshot dependencies before retiring the resource.
What makes a golden AMI useful?
It gives repeated launches an approved operating system and software baseline that is produced, tested and versioned deliberately. The launch plan can still provide environment-specific identity and configuration. A maintained image pipeline can automate building and testing, then the release decision selects which version to use.
Quick quiz
A ready x86_64 AMI is visible in the correct Region. Can its availability substitute for checking an arm64 instance type?
Check architecture compatibility separately. The operating system and native software built for x86_64 need a compatible target. Select an appropriate instance type or build and test an arm64 image as a separate candidate.
A test launch gives HTTP 200 with a release you expect but the wrong stock. Has the image passed recovery?
The expected data check is still unresolved. The build and listener participated. Check which runtime dataset and device the application uses, then assert the known result. Returning successful HTTP bytes is a smaller claim than recovering an application.
Will every referenced snapshot disappear when you deregister the AMI?
Inspect the configured cleanup and resulting snapshots. The default keeps the snapshots. You can request associated deletion, but a snapshot shared by several AMIs is not deleted by that request. Keep assets needed for another image or restore plan.
Practice tasks
- Change the offline sample so the metadata still shows the correct image and root snapshot but leaves out its required data mapping. Predict the exact failed condition and explain why a root boot cannot cover it.
- Design a two-Region launch record for one build release. Include both image IDs, the target template version, intended owner, encryption permissions and a verified app result.
- Describe which changes would be required to retire the original image while keeping an approved rollback available. Identify the template references and backing snapshots to review.
Image and launch settings
The AMI supplies the bootable baseline and mappings. A launch template selects it along with runtime parameters.
Verify a new launch
Check scope, architecture, boot mode, actual app version and a known data path.
Copying creates a destination ID
Check Region, permissions, destination key access and the target's launch template version.
Retire with dependency awareness
Review future launches and snapshot references. Running instances use their own provisioned volumes.
Official references
- EC2 Amazon Machine Images and characteristics
- Creating Amazon EBS-backed AMIs
- AWS CLI image-capture settings and no-reboot behavior
- EC2 boot modes and image behavior
- EC2 launch template parameters and versions
- EC2 AMI copying, permissions and costs
- Private AMI sharing and encryption access
- Deregistering an AMI and snapshot retention
- EC2 AMI deprecation behavior
- EC2 Image Builder pipelines
- Mapping EBS volume identity to guest NVMe devices