This page has an AWS CodeBuild buildspec that finds every running EC2 instance tagged environment=uat and creates an AMI from each one with the AWS CLI. It also has the IAM policy the CodeBuild service role needs. Below the original you will find how the script works, a corrected and safer version, how to schedule it, how to clean up old AMIs, and fixes for common errors.
version: 0.2
phases:
build:
commands:
- |
#!/bin/bash
# Author - Rajesh Kumar
# Set AWS region
export AWS_DEFAULT_REGION=us-east-1
# Get running all instance IDs
instance_ids=$(aws ec2 describe-instances --filters "Name=instance-state-name,Values=running" "Name=tag:environment,Values=uat" --query 'Reservations[].Instances[].InstanceId' --output text)
echo "List of Instances: $instance_ids"
# Create AMIs from instance IDs
for instance_id in $instance_ids; do
instance_name=$(aws ec2 describe-instances --instance-ids $instance_id --query 'Reservations[].Instances[].Tags[?Key==`Name`].Value' --output text)
timestamp=$(date +%Y-%m-%d-%H-%M-%S)
ami_name="$instance_name-$timestamp"
aws ec2 create-image --instance-id $instance_id --name "$ami_name" --no-reboot
done
Code language: PHP (php)
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "EC2Read",
"Effect": "Allow",
"Action": [
"ec2:DescribeInstances",
"ec2:DescribeImages",
"ec2:CreateImage"
],
"Resource": "*"
}
]
}
Code language: JSON / JSON with Comments (json)
How the buildspec works
The example above runs a single multi-line shell command in the build phase. CodeBuild starts a container, and the AWS CLI inside it uses the project's service role for credentials, so no access keys are needed. The script has three stages: it lists matching instances, looks up each instance's Name tag, and calls create-image once per instance.
| Line | What it does |
|---|---|
version: 0.2 | Buildspec format version. In 0.2, all commands in a phase run in the same shell instance. |
- | | YAML literal block. Everything indented below it is passed to the shell as one script. |
describe-instances --filters ... | Returns the IDs of instances that are running and carry the tag environment=uat. Tag keys and values are case-sensitive. |
--query 'Reservations[].Instances[].InstanceId' --output text | Uses JMESPath to flatten the response into a space-separated list of IDs that the for loop can iterate over. |
Tags[?Key==Name].Value | Pulls out the value of the instance's Name tag so the AMI gets a readable name. |
create-image --no-reboot | Starts AMI creation without stopping the instance. The call returns at once with an ImageId. The AMI stays pending while EBS snapshots are taken. |
Note: --no-reboot avoids downtime, but AWS cannot guarantee file system integrity for the image. Data still in memory or in application buffers may be missing. For databases, flush or freeze writes first, or accept a reboot in a maintenance window.
Prerequisites and project setup
- Tag the instances you want to back up, for example
environment=uat. Give each one aNametag. - In the CodeBuild console, create a build project. If the buildspec does not live in a repository, set Source to No source. Then use Insert build commands and paste the buildspec into the editor. A project with no source must have an inline buildspec.
- For Environment, pick a managed Amazon Linux standard image. These images include AWS CLI v2.
- Let CodeBuild create a new service role. That role already has the CloudWatch Logs permissions needed for build logs.
- Attach the EC2 policy from the IAM section below to the service role.
- Start a build and read the build log to confirm which AMIs were created.
Corrected and production-ready buildspec
The version below fixes the problems in the example above. It runs under bash, handles instances with no Name tag or with invalid characters in it, tags the AMI and its snapshots for later cleanup, and fails the build if any create-image call fails.
version: 0.2
env:
shell: bash
variables:
TARGET_ENV: "uat"
phases:
build:
commands:
- |
set -uo pipefail
export AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}"
timestamp=$(date -u +%Y-%m-%d-%H-%M-%S)
failed=0
instance_ids=$(aws ec2 describe-instances \
--filters "Name=instance-state-name,Values=running" "Name=tag:environment,Values=${TARGET_ENV}" \
--query 'Reservations[].Instances[].InstanceId' --output text) || failed=1
if [ -z "${instance_ids:-}" ]; then
echo "No running instances tagged environment=${TARGET_ENV}"
else
echo "Instances: $instance_ids"
fi
for instance_id in ${instance_ids:-}; do
instance_name=$(aws ec2 describe-instances --instance-ids "$instance_id" \
--query 'Reservations[0].Instances[0].Tags[?Key==`Name`].Value | [0]' --output text)
if [ -z "$instance_name" ] || [ "$instance_name" = "None" ]; then
instance_name="$instance_id"
fi
# Keep only characters allowed in AMI names and leave room for the timestamp
instance_name=$(printf '%s' "$instance_name" | tr -c 'A-Za-z0-9()./@_-' '-')
ami_name="${instance_name:0:100}-${timestamp}"
if image_id=$(aws ec2 create-image \
--instance-id "$instance_id" \
--name "$ami_name" \
--description "Automated AMI of $instance_id created by CodeBuild" \
--no-reboot \
--tag-specifications \
"ResourceType=image,Tags=[{Key=environment,Value=${TARGET_ENV}},{Key=source-instance,Value=${instance_id}},{Key=created-by,Value=codebuild}]" \
"ResourceType=snapshot,Tags=[{Key=environment,Value=${TARGET_ENV}},{Key=source-instance,Value=${instance_id}},{Key=created-by,Value=codebuild}]" \
--query ImageId --output text); then
echo "Created $image_id ($ami_name) from $instance_id"
else
echo "ERROR: create-image failed for $instance_id"
failed=1
fi
done
[ "$failed" -eq 0 ]Code language: PHP (php)
env.shell: bashmakes CodeBuild run the commands with bash. A#!/bin/bashline inside a command is only a comment and does not change the shell.TARGET_ENVis a project variable. You can override it per build, for example with--environment-variables-overrideonstart-build, without editing the script.date -uuses one UTC timestamp for the whole run, so AMIs from the same run share a suffix. Names stay unique because each one includes the instance name or ID.- The
trline replaces characters that AMI names do not allow, such as:or,, with-. Names may be 3 to 128 characters long. - The final
[ "$failed" -eq 0 ]gives a non-zero exit status if any call failed, which marks the build as failed. Using a test instead ofexitavoids ending the shell CodeBuild is managing. - Tags on images and snapshots make it possible to find, audit and clean up these AMIs later.
IAM permissions for the CodeBuild service role
The original policy works for the original script, but its Sid says read-only even though it grants ec2:CreateImage. The corrected script also adds tags when it creates the image, which needs ec2:CreateTags. The policy below limits that permission to tagging done as part of CreateImage.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "DescribeEc2",
"Effect": "Allow",
"Action": ["ec2:DescribeInstances", "ec2:DescribeImages"],
"Resource": "*"
},
{
"Sid": "CreateAmi",
"Effect": "Allow",
"Action": "ec2:CreateImage",
"Resource": "*"
},
{
"Sid": "TagOnCreateImageOnly",
"Effect": "Allow",
"Action": "ec2:CreateTags",
"Resource": [
"arn:aws:ec2:*::image/*",
"arn:aws:ec2:*::snapshot/*"
],
"Condition": {
"StringEquals": { "ec2:CreateAction": "CreateImage" }
}
}
]
}Code language: JSON / JSON with Comments (json)
Note: If you also run the cleanup script below from CodeBuild, add ec2:DeregisterImage and ec2:DeleteSnapshot. Use a separate project and role for cleanup if you want to keep delete rights away from the backup job.
Running and scheduling the build
Start a build from the CLI and check that the new AMIs appear:
aws codebuild start-build --project-name ami-backup-uat
# Override the target environment for one run
aws codebuild start-build --project-name ami-backup-uat \
--environment-variables-override name=TARGET_ENV,value=staging,type=PLAINTEXT
# List AMIs created by the job
aws ec2 describe-images --owners self \
--filters "Name=tag:created-by,Values=codebuild" \
--query 'Images[].[ImageId,Name,State,CreationDate]' --output tableCode language: PHP (php)
The build log should show something like this:
Instances: i-0a1b2c3d4e5f60718 i-0f9e8d7c6b5a40312
Created ami-0123456789abcdef0 (uat-web-01-2023-06-01-02-00-05) from i-0a1b2c3d4e5f60718
Created ami-0fedcba9876543210 (uat-api-01-2023-06-01-02-00-05) from i-0f9e8d7c6b5a40312Code language: JavaScript (javascript)
To run the job on a schedule, create an Amazon EventBridge rule or an EventBridge Scheduler schedule with the CodeBuild project as the target. For example, cron(0 2 * * ? *) runs every day at 02:00 UTC. EventBridge needs an IAM role that allows codebuild:StartBuild on the project.
Cleaning up old AMIs
Each AMI keeps its EBS snapshots, and you pay for snapshot storage until they are deleted. Deregistering an AMI does not delete its snapshots, so the script below does both. It removes AMIs older than seven days that this job created:
#!/bin/bash
set -uo pipefail
RETENTION_DAYS=7
cutoff=$(date -u -d "-${RETENTION_DAYS} days" +%Y-%m-%dT%H:%M:%S)
aws ec2 describe-images --owners self \
--filters "Name=tag:created-by,Values=codebuild" "Name=tag:environment,Values=uat" \
--query 'Images[].[ImageId,CreationDate]' --output text |
while read -r ami created; do
if [[ "$created" < "$cutoff" ]]; then
snaps=$(aws ec2 describe-images --image-ids "$ami" \
--query 'Images[0].BlockDeviceMappings[].Ebs.SnapshotId' --output text)
echo "Deregistering $ami (created $created)"
aws ec2 deregister-image --image-id "$ami"
for snap in $snaps; do
[ "$snap" != "None" ] && aws ec2 delete-snapshot --snapshot-id "$snap"
done
fi
doneCode language: PHP (php)
The date check runs in bash and not in the JMESPath query, because JMESPath ordering operators such as < are only defined for numbers. CreationDate values use ISO 8601, so comparing them as strings sorts them correctly.
Troubleshooting common errors
| Symptom | Cause | Fix |
|---|---|---|
YAML_FILE_ERROR when the build starts | Tab characters in the buildspec, such as the tab-indented # Author line in the on-page example | Indent with spaces only, and keep every line of the - | block at the same indentation or deeper |
UnauthorizedOperation on DescribeInstances or CreateImage | The policy is not attached to the project's service role | Attach the policy to the role shown under the project's Environment settings |
UnauthorizedOperation only after adding --tag-specifications | ec2:CreateTags is missing | Add the TagOnCreateImageOnly statement shown above |
| Empty instance list | Tag key or value does not match exactly (Environment vs environment), or the build runs in another Region | Check the tags with aws ec2 describe-tags and check AWS_DEFAULT_REGION |
InvalidAMIName.Duplicate | An AMI with the same name already exists in the account and Region | Keep the timestamp in the name. Do not run two builds in the same second |
InvalidParameterValue for the AMI name | The Name tag contains characters AMI names do not allow | Use the sanitising tr line from the corrected script |
Build succeeds but the AMI shows pending | AMI creation runs in the background | This is expected. Wait, or run aws ec2 wait image-available --image-ids <id>. The waiter can time out on large volumes |
Best practices and managed alternatives
- Restrict the job to clearly tagged instances. Never run it against every running instance in an account.
- Keep
TARGET_ENVand the Region as project variables instead of editing the script for each environment. - Use a reboot or an application-level freeze for instances where crash-consistent images are not good enough.
- Always pair AMI creation with a retention process, or snapshot costs will keep growing.
- For simple scheduled AMI backups, consider Amazon Data Lifecycle Manager, which supports EBS-backed AMI policies that target instances by tag and handle retention. Another option is AWS Backup, which manages EC2 backups centrally. Use the CodeBuild approach when you need custom logic or want backups inside an existing pipeline.
- AMIs work well as golden images for scaling groups. See AWS Tutorials: Auto Scaling Group.
Frequently asked questions
Does aws ec2 create-image with –no-reboot cause downtime?
No. The instance keeps running while the snapshots are taken. The trade-off is that file system consistency is not guaranteed, so data still in memory may not be in the image.
Can AWS CodeBuild create AMIs on a schedule?
Yes. Point an Amazon EventBridge rule or EventBridge Scheduler schedule at the CodeBuild project with a cron or rate expression. Give it a role that allows codebuild:StartBuild.
Does deregistering an AMI delete its EBS snapshots?
No. Snapshots remain, and you keep paying for them, until you delete them with aws ec2 delete-snapshot. The cleanup script on this page does both steps.
How long does it take to create an AMI from a running instance?
It depends on the volume sizes and how much data has changed since the last snapshot. The create-image call returns at once, and the AMI stays in the pending state until its snapshots finish.
Should I use CodeBuild, Data Lifecycle Manager or AWS Backup for AMI backups?
For plain scheduled AMIs with retention, Data Lifecycle Manager or AWS Backup needs less maintenance. CodeBuild fits when you need custom naming, extra checks, or AMI creation as one step in a larger pipeline.
Related tutorials
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals