Backing up your EC2 instances is essential β especially before major updates, deployments, or patching. While it’s common practice to stop instances before creating AMIs (Amazon Machine Images), you can also create AMIs from running instances. This blog explores that option and walks you through a working Bash script that does it automatically.
π§ Why Create AMIs from Running EC2 Instances?
Creating AMIs from running instances allows you to:
- Avoid downtime
- Maintain service availability
- Automate regular backups without manual intervention
However, it comes with a caveat: the snapshot may not be fully consistent if disk writes are happening at the time. Still, for many applications, this is acceptable or mitigated by application-level consistency mechanisms.
π οΈ Prerequisites
Before you proceed, ensure:
- You have AWS CLI installed and configured (
aws configure
or use named profiles) - The IAM user/role has permissions:
ec2:DescribeInstances
,ec2:CreateImage
- Your EC2 instances are tagged with Name
π Bash Script to Create AMIs from Running Instances
Hereβs a Bash script that automatically creates AMIs for EC2 instances without stopping them:
#!/bin/bash
# List of EC2 Name tags to create AMIs for
INSTANCE_NAMES=("server-1" "server-2" "server-3")
DATE=$(date +%Y-%m-%d)
for NAME in "${INSTANCE_NAMES[@]}"
do
INSTANCE_ID=$(aws ec2 describe-instances \
--profile nu \
--filters "Name=tag:Name,Values=${NAME}" \
--query "Reservations[].Instances[].InstanceId" \
--output text)
if [ -n "$INSTANCE_ID" ]; then
echo "π¦ Creating AMI for running instance: $NAME (ID: $INSTANCE_ID)..."
aws ec2 create-image \
--profile nu \
--instance-id "$INSTANCE_ID" \
--name "${NAME}-${DATE}" \
--description "AMI backup of $NAME on ${DATE}" \
--no-reboot
else
echo "β Instance named '$NAME' not found."
fi
done
β Key Highlights
--no-reboot
: Ensures the instance is not rebooted during AMI creation.- The script works even if the instance is running, unlike the earlier version filtered by
stopped
state. - Uses the
Name
tag to target instances.
π Best Practices
- Use Application Snapshots: If your instance runs a DB, consider creating a DB dump before backup.
- Label AMIs Clearly: Include dates in names to easily identify.
- Set a Retention Policy: Automate deletion of older AMIs using Lambda or lifecycle policies.
π§ͺ Real Use Case
This approach works well when:
- Your infrastructure must remain always on
- You need frequent backups (e.g., daily)
- You’re doing automated CI/CD and want to preserve current state
π§― When Not to Use This
Avoid this method if:
- Your application writes lots of data constantly (e.g., high-write databases)
- You need point-in-time consistency (e.g., financial transactions)
π§΅ Wrapping Up
Creating AMIs from running EC2 instances is a powerful strategy for zero-downtime backups. With tools like Bash and AWS CLI, you can automate the entire process and integrate it into your DevOps pipelines.