Chatwithcloud logo

ChatWithCloud

AWS GenAI Tools

Cleanup Unused AMI Images and Snapshots That Are Older Than 30 Days

The following script helps in cleaning up the Amazon Machine Images (AMIs) and their associated Snapshots, which have not been used for the last 30 days.

Code

Here is the JavaScript code that accomplishes this task.

const AWS = require("aws-sdk"); AWS.config.update({region: 'us-west-1'}); const ec2 = new AWS.EC2(); async function fetchImages () { const reqParams = { Filters: [ { Name: "is-public", Values: ["false"] } ] }; const data = await ec2.describeImages(reqParams).promise(); const oldImages = data.Images.filter( image => new Date(image.CreationDate).getTime() < (Date.now() - 30*24*60*60*1000) ) return oldImages; } async function deleteImages(images) { const unpromisedDeletes = images.map(async (image) => { const reqParam= { ImageId : image.ImageId }; await ec2.deregisterImage(reqParam).promise(); const snapshotReqParams = { SnapshotId: image.BlockDeviceMappings[0].Ebs.SnapshotId }; return await ec2.deleteSnapshot(snapshotReqParams).promise(); }) const results = await Promise.all(unpromisedDeletes); return results; } fetchImages().then(images => deleteImages(images)) .then(res => console.log("Deleted ", res.length )) .catch(err => console.log(err.message));

Detailed Code Explanation

Expected Output

The expected output of the code block would be a simple statement logging the number of images deleted.

Here is an example of the output:

"Deleted ", 3

Considerations & Caveats

Required IAM permissions and example policy

This script requires the following IAM permissions:

  1. ec2:DescribeImages
  2. ec2:DeregisterImage
  3. ec2:DeleteSnapshot

Here is an example of an IAM policy granting these permissions:

{ "Version": "2012-10-17", "Statement": [ { "Sid": "VisualEditor0", "Effect": "Allow", "Action": [ "ec2:DescribeImages", "ec2:DeregisterImage", "ec2:DeleteSnapshot" ], "Resource": "*" } ] }

FAQ

  1. What does filtering by 'is-public' do?

    • The filter for 'is-public' set to 'false' limits the images returned to only those owned by the account running the script.
  2. Is it possible to change the duration determining 'old images'?

    • Yes, by changing the value multiplying 24*60*60*1000 in the fetchImages function, you can set the duration based on your needs.
  3. What will happen if an old AMI is in use when the script runs?

    • AMIs currently in use or attached to a running instance won't be affected when deregistered. A deregistered AMI remains available for use until its associated instances are terminated.
  4. Can I run this script in any AWS region?

    • Yes, but you must make sure to set the 'region' in the AWS Config object to the correct region where your resources exist.




Related articles
Monitor and Notify When Approaching Service LimitsGet Current IAM Identity TypeScriptCalculate the Size of Each S3 Bucket and Find the One with the Most Data