Amazon AWS - EBS Volume Deletion on Instance Termination

This post explains how to set the DeleteOnTermination flag for an AMI image so that on down-scaling, you don't have to clean up all the EBS volumes that have been retained (which incur extra cost)

Prerequisites:

  • AWS Cli 
    • in ubuntu, apt-get awscli will install this, you will need to run aws configure post installation
  • AMI image which currently have the DeleteOnTermination flag false (When you click on the AMI, see the 'Block Devices'. /dev/sda=snap-snapshot_id:10:false:gp2  - The false indicates that the volume won't be deleted upon instance termination)
Step 1 (Optional) :

Run 

aws ec2 describe-images --image-ids ami-image_id

You will see the details of the image and you can spot   "DeleteOnTermination": false 

Step 2:

What you are going to do is to register a new AMI, which is a clone of the original AMI (with the DeleteOnTermination flag false) and set the DeleteOnTermination flag while registering. And the following command achieves this:

aws ec2 register-image --name "AMI New"  --block-device-mappings "[{\"DeviceName\": \"device_name_of_old\",\"Ebs\": {\"SnapshotId\": \"snap-snapshot_id_of_old_ami\",\"VolumeSize\": volume_size_of_old_ami,\"DeleteOnTermination\": true,\"VolumeType\":\"volume_type_of_old\"}}]"  --architecture architecture_of_old --virtualization-type virtualization_type_of_old --kernel-id kernel_id_of_old --root-device-name "root_device_name_of_old" 

If the command was successful, you will receive the Image ID of the newly registered AMI, which you can use in your code for up-scaling and down-scaling without worrying about unused volumes piling up. You can verify the change by redoing step 1 and replacing the ami-image_id with the image_id of the new AMI