Enable EBS Encryption from CloudFormation

Enable EBS Encryption from CloudFormation

Sample Scenario:

You created an EC2 Instance using a CloudFormation Template. By default the disk attached i.e. EBS Volume attached to the EC2 is not encrypted. You company follow compliance standards that requires storage volumes to be encrypted.

Problem

Your EC2 is stateful. Changing EBS Encryption to True in cloudformation will delete the previous volume. You do not want your data to be deleted.

Solution

Situations like this can get tricky due unavailability of straightforward solution and due to lack of resource.

Here is a workaround

1. Create an AMI from your instance

Creating an AMI automatically creates a snapshot. So you also have a backup snapshot. You can use this backup in case of any disaster. Below is a PowerShell command to do the same

$INSTANCE_ID="i-xxxxxxxxxxxx"
$AMI_NAME="UNENCRYPTED_AMI"
$SNAPSHOT_NAME="UNENCRYPTED_SNAPSHOT"
aws ec2 create-image  --instance-id $INSTANCE_ID  --name $AMI_NAME  --description $AMI_NAME  --tag-specifications "ResourceType=image,Tags=[{Key=Name,Value=$($AMI_NAME)}]" "ResourceType=snapshot,Tags=[{Key=Name,Value=$($SNAPSHOT_NAME)}]"

You can even do the same step manually 

2. Create a Copy of your AMI

AMI creation takes time. Once an unencrypted AMI is created, create a copy of your AMI. While making a copy, we have to enable encryption. Enabling encryption at this stage is very important. All EBS created from an encrypted AMI will always be encrypted. For Encryption, AWS will ask for the KMS Key. You can leave all values to default and let AWS create and manage the KMS Key for you.

Below is a PowerShell command to do the same

Modify REGION and AMI_ID_TO_COPY accordingly

$REGION="us-east-1"
$AMI_NAME="ENCRYPTED_AMI"
$AMI_ID_TO_COPY="ami-xxxxxxxxxxxxxx" #Copy AMI ID you get after completing Step 1
aws ec2 copy-image  --region $REGION  --name $AMI_NAME --source-region $REGION  --source-image-id $AMI_ID_TO_COPY  --description $AMI_NAME --encrypted

You can even do the same step manually 

3. Modify the AMI ID in your CloudFormation Template

Go to your CloudFormation Template, where EC2 is created. Now, you need to make sure that the Input AMI ID for your instance is modified and replaced with this new one. 

4. Create a Change Set in your CloudFormation Stack and deploy the changes

If your Stack is small, you can directly update your cloudformation template, or if your Stack is huge, then you can create a change set and deploy your CloudFormation Template. 

to the unavailability of a straightforward solution and due to a lack of resources

5. Verify the new EC2 in the EC2 Console

A new EC2 starts with an encrypted Volume. Go to your EC2 console and verify that a new instance is started and has an encrypted volume.

Shivam Anand