{"id":35631,"date":"2026-11-28T22:06:19","date_gmt":"2026-11-28T22:06:19","guid":{"rendered":"https:\/\/www.devopsschool.com\/blog\/?p=35631"},"modified":"2026-11-28T22:06:19","modified_gmt":"2026-11-28T22:06:19","slug":"aws-tutorials-aws-codebuild-buildspec-code-for-creating-ami-from-running-instances","status":"publish","type":"post","link":"https:\/\/www.devopsschool.com\/blog\/aws-tutorials-aws-codebuild-buildspec-code-for-creating-ami-from-running-instances\/","title":{"rendered":"AWS Tutorials: AWS CodeBuild &#8211; Buildspec code for creating AMI from running instances"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">This page has an AWS CodeBuild buildspec that finds every running EC2 instance tagged <code>environment=uat<\/code> 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.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">version: <span class=\"hljs-number\">0.2<\/span>\n\nphases:\n  build:\n    commands:\n      - |\n        <span class=\"hljs-comment\">#!\/bin\/bash<\/span>\n\n\t\t<span class=\"hljs-comment\"># Author - Rajesh Kumar<\/span>\n\t\t\n        <span class=\"hljs-comment\"># Set AWS region<\/span>\n        export AWS_DEFAULT_REGION=us-east<span class=\"hljs-number\">-1<\/span>\n\n        <span class=\"hljs-comment\"># Get running all instance IDs<\/span>\n        instance_ids=$(aws ec2 describe-instances --filters <span class=\"hljs-string\">\"Name=instance-state-name,Values=running\"<\/span> <span class=\"hljs-string\">\"Name=tag:environment,Values=uat\"<\/span> --query <span class=\"hljs-string\">'Reservations&#91;].Instances&#91;].InstanceId'<\/span> --output text)\n\n        <span class=\"hljs-keyword\">echo<\/span> <span class=\"hljs-string\">\"List of Instances: $instance_ids\"<\/span>\n\n        <span class=\"hljs-comment\"># Create AMIs from instance IDs<\/span>\n        <span class=\"hljs-keyword\">for<\/span> instance_id in $instance_ids; <span class=\"hljs-keyword\">do<\/span>\n          instance_name=$(aws ec2 describe-instances --instance-ids $instance_id --query <span class=\"hljs-string\">'Reservations&#91;].Instances&#91;].Tags&#91;?Key==`Name`].Value'<\/span> --output text)\n          timestamp=$(date +%Y-%m-%d-%H-%M-%S)\n          ami_name=<span class=\"hljs-string\">\"$instance_name-$timestamp\"<\/span>\n          aws ec2 create-image --instance-id $instance_id --name <span class=\"hljs-string\">\"$ami_name\"<\/span> --no-reboot\n        done\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"JSON \/ JSON with Comments\" data-shcb-language-slug=\"json\"><span><code class=\"hljs language-json\">{\r\n    <span class=\"hljs-attr\">\"Version\"<\/span>: <span class=\"hljs-string\">\"2012-10-17\"<\/span>,\r\n    <span class=\"hljs-attr\">\"Statement\"<\/span>: &#91;\r\n        {\r\n            <span class=\"hljs-attr\">\"Sid\"<\/span>: <span class=\"hljs-string\">\"EC2Read\"<\/span>,\r\n            <span class=\"hljs-attr\">\"Effect\"<\/span>: <span class=\"hljs-string\">\"Allow\"<\/span>,\r\n            <span class=\"hljs-attr\">\"Action\"<\/span>: &#91;\r\n                <span class=\"hljs-string\">\"ec2:DescribeInstances\"<\/span>,\r\n                <span class=\"hljs-string\">\"ec2:DescribeImages\"<\/span>,\r\n                <span class=\"hljs-string\">\"ec2:CreateImage\"<\/span>\r\n            ],\r\n            <span class=\"hljs-attr\">\"Resource\"<\/span>: <span class=\"hljs-string\">\"*\"<\/span>\r\n        }\r\n    ]\r\n}\r\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JSON \/ JSON with Comments<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">json<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<script src=\"https:\/\/gist.github.com\/devops-school\/2f6267ed106521e24e82b1e365845087.js\"><\/script>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">How the buildspec works<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The example above runs a single multi-line shell command in the <code>build<\/code> phase. CodeBuild starts a container, and the AWS CLI inside it uses the project&#039;s service role for credentials, so no access keys are needed. The script has three stages: it lists matching instances, looks up each instance&#039;s <code>Name<\/code> tag, and calls <code>create-image<\/code> once per instance.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Line<\/th><th>What it does<\/th><\/tr><\/thead><tbody><tr><td><code>version: 0.2<\/code><\/td><td>Buildspec format version. In 0.2, all commands in a phase run in the same shell instance.<\/td><\/tr><tr><td><code>- |<\/code><\/td><td>YAML literal block. Everything indented below it is passed to the shell as one script.<\/td><\/tr><tr><td><code>describe-instances --filters ...<\/code><\/td><td>Returns the IDs of instances that are <code>running<\/code> and carry the tag <code>environment=uat<\/code>. Tag keys and values are case-sensitive.<\/td><\/tr><tr><td><code>--query &#039;Reservations[].Instances[].InstanceId&#039; --output text<\/code><\/td><td>Uses JMESPath to flatten the response into a space-separated list of IDs that the <code>for<\/code> loop can iterate over.<\/td><\/tr><tr><td><code>Tags[?Key==<\/code>Name<code>].Value<\/code><\/td><td>Pulls out the value of the instance&#039;s <code>Name<\/code> tag so the AMI gets a readable name.<\/td><\/tr><tr><td><code>create-image --no-reboot<\/code><\/td><td>Starts AMI creation without stopping the instance. The call returns at once with an <code>ImageId<\/code>. The AMI stays <code>pending<\/code> while EBS snapshots are taken.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> <code>--no-reboot<\/code> 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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Prerequisites and project setup<\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Tag the instances you want to back up, for example <code>environment=uat<\/code>. Give each one a <code>Name<\/code> tag.<\/li>\n\n\n<li>In the CodeBuild console, create a build project. If the buildspec does not live in a repository, set <strong>Source<\/strong> to <strong>No source<\/strong>. Then use <strong>Insert build commands<\/strong> and paste the buildspec into the editor. A project with no source must have an inline buildspec.<\/li>\n\n\n<li>For <strong>Environment<\/strong>, pick a managed Amazon Linux standard image. These images include AWS CLI v2.<\/li>\n\n\n<li>Let CodeBuild create a new service role. That role already has the CloudWatch Logs permissions needed for build logs.<\/li>\n\n\n<li>Attach the EC2 policy from the IAM section below to the service role.<\/li>\n\n\n<li>Start a build and read the build log to confirm which AMIs were created.<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\">Corrected and production-ready buildspec<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The version below fixes the problems in the example above. It runs under bash, handles instances with no <code>Name<\/code> tag or with invalid characters in it, tags the AMI and its snapshots for later cleanup, and fails the build if any <code>create-image<\/code> call fails.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">version: <span class=\"hljs-number\">0.2<\/span>\n\nenv:\n  shell: bash\n  variables:\n    TARGET_ENV: <span class=\"hljs-string\">\"uat\"<\/span>\n\nphases:\n  build:\n    commands:\n      - |\n        set -uo pipefail\n        export AWS_DEFAULT_REGION=<span class=\"hljs-string\">\"${AWS_DEFAULT_REGION:-us-east-1}\"<\/span>\n        timestamp=$(date -u +%Y-%m-%d-%H-%M-%S)\n        failed=<span class=\"hljs-number\">0<\/span>\n\n        instance_ids=$(aws ec2 describe-instances \\\n          --filters <span class=\"hljs-string\">\"Name=instance-state-name,Values=running\"<\/span> <span class=\"hljs-string\">\"Name=tag:environment,Values=${TARGET_ENV}\"<\/span> \\\n          --query <span class=\"hljs-string\">'Reservations&#91;].Instances&#91;].InstanceId'<\/span> --output text) || failed=<span class=\"hljs-number\">1<\/span>\n\n        <span class=\"hljs-keyword\">if<\/span> &#91; -z <span class=\"hljs-string\">\"${instance_ids:-}\"<\/span> ]; then\n          <span class=\"hljs-keyword\">echo<\/span> <span class=\"hljs-string\">\"No running instances tagged environment=${TARGET_ENV}\"<\/span>\n        <span class=\"hljs-keyword\">else<\/span>\n          <span class=\"hljs-keyword\">echo<\/span> <span class=\"hljs-string\">\"Instances: $instance_ids\"<\/span>\n        fi\n\n        <span class=\"hljs-keyword\">for<\/span> instance_id in ${instance_ids:-}; <span class=\"hljs-keyword\">do<\/span>\n          instance_name=$(aws ec2 describe-instances --instance-ids <span class=\"hljs-string\">\"$instance_id\"<\/span> \\\n            --query <span class=\"hljs-string\">'Reservations&#91;0].Instances&#91;0].Tags&#91;?Key==`Name`].Value | &#91;0]'<\/span> --output text)\n          <span class=\"hljs-keyword\">if<\/span> &#91; -z <span class=\"hljs-string\">\"$instance_name\"<\/span> ] || &#91; <span class=\"hljs-string\">\"$instance_name\"<\/span> = <span class=\"hljs-string\">\"None\"<\/span> ]; then\n            instance_name=<span class=\"hljs-string\">\"$instance_id\"<\/span>\n          fi\n          <span class=\"hljs-comment\"># Keep only characters allowed in AMI names and leave room for the timestamp<\/span>\n          instance_name=$(printf <span class=\"hljs-string\">'%s'<\/span> <span class=\"hljs-string\">\"$instance_name\"<\/span> | tr -c <span class=\"hljs-string\">'A-Za-z0-9().\/@_-'<\/span> <span class=\"hljs-string\">'-'<\/span>)\n          ami_name=<span class=\"hljs-string\">\"${instance_name:0:100}-${timestamp}\"<\/span>\n\n          <span class=\"hljs-keyword\">if<\/span> image_id=$(aws ec2 create-image \\\n              --instance-id <span class=\"hljs-string\">\"$instance_id\"<\/span> \\\n              --name <span class=\"hljs-string\">\"$ami_name\"<\/span> \\\n              --description <span class=\"hljs-string\">\"Automated AMI of $instance_id created by CodeBuild\"<\/span> \\\n              --no-reboot \\\n              --tag-specifications \\\n                <span class=\"hljs-string\">\"ResourceType=image,Tags=&#91;{Key=environment,Value=${TARGET_ENV}},{Key=source-instance,Value=${instance_id}},{Key=created-by,Value=codebuild}]\"<\/span> \\\n                <span class=\"hljs-string\">\"ResourceType=snapshot,Tags=&#91;{Key=environment,Value=${TARGET_ENV}},{Key=source-instance,Value=${instance_id}},{Key=created-by,Value=codebuild}]\"<\/span> \\\n              --query ImageId --output text); then\n            <span class=\"hljs-keyword\">echo<\/span> <span class=\"hljs-string\">\"Created $image_id ($ami_name) from $instance_id\"<\/span>\n          <span class=\"hljs-keyword\">else<\/span>\n            <span class=\"hljs-keyword\">echo<\/span> <span class=\"hljs-string\">\"ERROR: create-image failed for $instance_id\"<\/span>\n            failed=<span class=\"hljs-number\">1<\/span>\n          fi\n        done\n\n        &#91; <span class=\"hljs-string\">\"$failed\"<\/span> -eq <span class=\"hljs-number\">0<\/span> ]<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<ul class=\"wp-block-list\">\n<li><code>env.shell: bash<\/code> makes CodeBuild run the commands with bash. A <code>#!\/bin\/bash<\/code> line inside a command is only a comment and does not change the shell.<\/li>\n\n\n<li><code>TARGET_ENV<\/code> is a project variable. You can override it per build, for example with <code>--environment-variables-override<\/code> on <code>start-build<\/code>, without editing the script.<\/li>\n\n\n<li><code>date -u<\/code> uses 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.<\/li>\n\n\n<li>The <code>tr<\/code> line replaces characters that AMI names do not allow, such as <code>:<\/code> or <code>,<\/code>, with <code>-<\/code>. Names may be 3 to 128 characters long.<\/li>\n\n\n<li>The final <code>[ &quot;$failed&quot; -eq 0 ]<\/code> gives a non-zero exit status if any call failed, which marks the build as failed. Using a test instead of <code>exit<\/code> avoids ending the shell CodeBuild is managing.<\/li>\n\n\n<li>Tags on images and snapshots make it possible to find, audit and clean up these AMIs later.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">IAM permissions for the CodeBuild service role<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The original policy works for the original script, but its <code>Sid<\/code> says read-only even though it grants <code>ec2:CreateImage<\/code>. The corrected script also adds tags when it creates the image, which needs <code>ec2:CreateTags<\/code>. The policy below limits that permission to tagging done as part of <code>CreateImage<\/code>.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"JSON \/ JSON with Comments\" data-shcb-language-slug=\"json\"><span><code class=\"hljs language-json\">{\n  <span class=\"hljs-attr\">\"Version\"<\/span>: <span class=\"hljs-string\">\"2012-10-17\"<\/span>,\n  <span class=\"hljs-attr\">\"Statement\"<\/span>: &#91;\n    {\n      <span class=\"hljs-attr\">\"Sid\"<\/span>: <span class=\"hljs-string\">\"DescribeEc2\"<\/span>,\n      <span class=\"hljs-attr\">\"Effect\"<\/span>: <span class=\"hljs-string\">\"Allow\"<\/span>,\n      <span class=\"hljs-attr\">\"Action\"<\/span>: &#91;<span class=\"hljs-string\">\"ec2:DescribeInstances\"<\/span>, <span class=\"hljs-string\">\"ec2:DescribeImages\"<\/span>],\n      <span class=\"hljs-attr\">\"Resource\"<\/span>: <span class=\"hljs-string\">\"*\"<\/span>\n    },\n    {\n      <span class=\"hljs-attr\">\"Sid\"<\/span>: <span class=\"hljs-string\">\"CreateAmi\"<\/span>,\n      <span class=\"hljs-attr\">\"Effect\"<\/span>: <span class=\"hljs-string\">\"Allow\"<\/span>,\n      <span class=\"hljs-attr\">\"Action\"<\/span>: <span class=\"hljs-string\">\"ec2:CreateImage\"<\/span>,\n      <span class=\"hljs-attr\">\"Resource\"<\/span>: <span class=\"hljs-string\">\"*\"<\/span>\n    },\n    {\n      <span class=\"hljs-attr\">\"Sid\"<\/span>: <span class=\"hljs-string\">\"TagOnCreateImageOnly\"<\/span>,\n      <span class=\"hljs-attr\">\"Effect\"<\/span>: <span class=\"hljs-string\">\"Allow\"<\/span>,\n      <span class=\"hljs-attr\">\"Action\"<\/span>: <span class=\"hljs-string\">\"ec2:CreateTags\"<\/span>,\n      <span class=\"hljs-attr\">\"Resource\"<\/span>: &#91;\n        <span class=\"hljs-string\">\"arn:aws:ec2:*::image\/*\"<\/span>,\n        <span class=\"hljs-string\">\"arn:aws:ec2:*::snapshot\/*\"<\/span>\n      ],\n      <span class=\"hljs-attr\">\"Condition\"<\/span>: {\n        <span class=\"hljs-attr\">\"StringEquals\"<\/span>: { <span class=\"hljs-attr\">\"ec2:CreateAction\"<\/span>: <span class=\"hljs-string\">\"CreateImage\"<\/span> }\n      }\n    }\n  ]\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JSON \/ JSON with Comments<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">json<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> If you also run the cleanup script below from CodeBuild, add <code>ec2:DeregisterImage<\/code> and <code>ec2:DeleteSnapshot<\/code>. Use a separate project and role for cleanup if you want to keep delete rights away from the backup job.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Running and scheduling the build<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Start a build from the CLI and check that the new AMIs appear:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">aws codebuild start-build --project-name ami-backup-uat\n\n<span class=\"hljs-comment\"># Override the target environment for one run<\/span>\naws codebuild start-build --project-name ami-backup-uat \\\n  --environment-variables-override name=TARGET_ENV,value=staging,type=PLAINTEXT\n\n<span class=\"hljs-comment\"># List AMIs created by the job<\/span>\naws ec2 describe-images --owners <span class=\"hljs-keyword\">self<\/span> \\\n  --filters <span class=\"hljs-string\">\"Name=tag:created-by,Values=codebuild\"<\/span> \\\n  --query <span class=\"hljs-string\">'Images&#91;].&#91;ImageId,Name,State,CreationDate]'<\/span> --output table<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">The build log should show something like this:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\">Instances: i<span class=\"hljs-number\">-0<\/span>a1b2c3d4e5f60718 i<span class=\"hljs-number\">-0<\/span>f9e8d7c6b5a40312\nCreated ami<span class=\"hljs-number\">-0123456789<\/span>abcdef0 (uat-web<span class=\"hljs-number\">-01<\/span><span class=\"hljs-number\">-2023<\/span><span class=\"hljs-number\">-06<\/span><span class=\"hljs-number\">-01<\/span><span class=\"hljs-number\">-02<\/span><span class=\"hljs-number\">-00<\/span><span class=\"hljs-number\">-05<\/span>) <span class=\"hljs-keyword\">from<\/span> i<span class=\"hljs-number\">-0<\/span>a1b2c3d4e5f60718\nCreated ami<span class=\"hljs-number\">-0<\/span>fedcba9876543210 (uat-api<span class=\"hljs-number\">-01<\/span><span class=\"hljs-number\">-2023<\/span><span class=\"hljs-number\">-06<\/span><span class=\"hljs-number\">-01<\/span><span class=\"hljs-number\">-02<\/span><span class=\"hljs-number\">-00<\/span><span class=\"hljs-number\">-05<\/span>) <span class=\"hljs-keyword\">from<\/span> i<span class=\"hljs-number\">-0<\/span>f9e8d7c6b5a40312<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">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, <code>cron(0 2 * * ? *)<\/code> runs every day at 02:00 UTC. EventBridge needs an IAM role that allows <code>codebuild:StartBuild<\/code> on the project.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Cleaning up old AMIs<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-comment\">#!\/bin\/bash<\/span>\nset -uo pipefail\nRETENTION_DAYS=<span class=\"hljs-number\">7<\/span>\ncutoff=$(date -u -d <span class=\"hljs-string\">\"-${RETENTION_DAYS} days\"<\/span> +%Y-%m-%dT%H:%M:%S)\n\naws ec2 describe-images --owners <span class=\"hljs-keyword\">self<\/span> \\\n  --filters <span class=\"hljs-string\">\"Name=tag:created-by,Values=codebuild\"<\/span> <span class=\"hljs-string\">\"Name=tag:environment,Values=uat\"<\/span> \\\n  --query <span class=\"hljs-string\">'Images&#91;].&#91;ImageId,CreationDate]'<\/span> --output text |\n<span class=\"hljs-keyword\">while<\/span> read -r ami created; <span class=\"hljs-keyword\">do<\/span>\n  <span class=\"hljs-keyword\">if<\/span> &#91;&#91; <span class=\"hljs-string\">\"$created\"<\/span> &lt; <span class=\"hljs-string\">\"$cutoff\"<\/span> ]]; then\n    snaps=$(aws ec2 describe-images --image-ids <span class=\"hljs-string\">\"$ami\"<\/span> \\\n      --query <span class=\"hljs-string\">'Images&#91;0].BlockDeviceMappings&#91;].Ebs.SnapshotId'<\/span> --output text)\n    <span class=\"hljs-keyword\">echo<\/span> <span class=\"hljs-string\">\"Deregistering $ami (created $created)\"<\/span>\n    aws ec2 deregister-image --image-id <span class=\"hljs-string\">\"$ami\"<\/span>\n    <span class=\"hljs-keyword\">for<\/span> snap in $snaps; <span class=\"hljs-keyword\">do<\/span>\n      &#91; <span class=\"hljs-string\">\"$snap\"<\/span> != <span class=\"hljs-string\">\"None\"<\/span> ] &amp;&amp; aws ec2 delete-snapshot --snapshot-id <span class=\"hljs-string\">\"$snap\"<\/span>\n    done\n  fi\ndone<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">The date check runs in bash and not in the JMESPath query, because JMESPath ordering operators such as <code>&lt;<\/code> are only defined for numbers. <code>CreationDate<\/code> values use ISO 8601, so comparing them as strings sorts them correctly.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Troubleshooting common errors<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Symptom<\/th><th>Cause<\/th><th>Fix<\/th><\/tr><\/thead><tbody><tr><td><code>YAML_FILE_ERROR<\/code> when the build starts<\/td><td>Tab characters in the buildspec, such as the tab-indented <code># Author<\/code> line in the on-page example<\/td><td>Indent with spaces only, and keep every line of the <code>- |<\/code> block at the same indentation or deeper<\/td><\/tr><tr><td><code>UnauthorizedOperation<\/code> on <code>DescribeInstances<\/code> or <code>CreateImage<\/code><\/td><td>The policy is not attached to the project&#039;s service role<\/td><td>Attach the policy to the role shown under the project&#039;s <strong>Environment<\/strong> settings<\/td><\/tr><tr><td><code>UnauthorizedOperation<\/code> only after adding <code>--tag-specifications<\/code><\/td><td><code>ec2:CreateTags<\/code> is missing<\/td><td>Add the <code>TagOnCreateImageOnly<\/code> statement shown above<\/td><\/tr><tr><td>Empty instance list<\/td><td>Tag key or value does not match exactly (<code>Environment<\/code> vs <code>environment<\/code>), or the build runs in another Region<\/td><td>Check the tags with <code>aws ec2 describe-tags<\/code> and check <code>AWS_DEFAULT_REGION<\/code><\/td><\/tr><tr><td><code>InvalidAMIName.Duplicate<\/code><\/td><td>An AMI with the same name already exists in the account and Region<\/td><td>Keep the timestamp in the name. Do not run two builds in the same second<\/td><\/tr><tr><td><code>InvalidParameterValue<\/code> for the AMI name<\/td><td>The <code>Name<\/code> tag contains characters AMI names do not allow<\/td><td>Use the sanitising <code>tr<\/code> line from the corrected script<\/td><\/tr><tr><td>Build succeeds but the AMI shows <code>pending<\/code><\/td><td>AMI creation runs in the background<\/td><td>This is expected. Wait, or run <code>aws ec2 wait image-available --image-ids &lt;id&gt;<\/code>. The waiter can time out on large volumes<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Best practices and managed alternatives<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Restrict the job to clearly tagged instances. Never run it against every running instance in an account.<\/li>\n\n\n<li>Keep <code>TARGET_ENV<\/code> and the Region as project variables instead of editing the script for each environment.<\/li>\n\n\n<li>Use a reboot or an application-level freeze for instances where crash-consistent images are not good enough.<\/li>\n\n\n<li>Always pair AMI creation with a retention process, or snapshot costs will keep growing.<\/li>\n\n\n<li>For simple scheduled AMI backups, consider <strong>Amazon Data Lifecycle Manager<\/strong>, which supports EBS-backed AMI policies that target instances by tag and handle retention. Another option is <strong>AWS Backup<\/strong>, which manages EC2 backups centrally. Use the CodeBuild approach when you need custom logic or want backups inside an existing pipeline.<\/li>\n\n\n<li>AMIs work well as golden images for scaling groups. See <a href=\"https:\/\/www.devopsschool.com\/blog\/aws-tutorials-auto-scaling-group\/\">AWS Tutorials: Auto Scaling Group<\/a>.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Frequently asked questions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Does aws ec2 create-image with &#8211;no-reboot cause downtime?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Can AWS CodeBuild create AMIs on a schedule?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Does deregistering an AMI delete its EBS snapshots?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How long does it take to create an AMI from a running instance?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Should I use CodeBuild, Data Lifecycle Manager or AWS Backup for AMI backups?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Related tutorials<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/category\/cloud-computing\/aws\/\">More AWS tutorials<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/aws-tutorials-auto-scaling-group\/\">AWS Tutorials: Auto Scaling Group<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/aws-tutorials-aws-identity-center-guide\/\">AWS Tutorials: AWS Identity Center Guide<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>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&#8230; <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_joinchat":[],"footnotes":""},"categories":[5633],"tags":[3354,1392,137],"class_list":["post-35631","post","type-post","status-publish","format-standard","hentry","category-aws","tag-amazon-ec2","tag-aws-cli","tag-bash"],"_links":{"self":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/35631","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/comments?post=35631"}],"version-history":[{"count":3,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/35631\/revisions"}],"predecessor-version":[{"id":80402,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/35631\/revisions\/80402"}],"wp:attachment":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/media?parent=35631"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/categories?post=35631"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/tags?post=35631"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}