Skip to content

Automation for re-encryption of existing snapshots using password rotated key in CMK

0

I am using CMK with KMS for encrypting the snapshots. As per organization policy, CMK must be rotated after every 45 days. Is there a way to automate the re-encryption of existing snapshots using the new CMK when the password is rotated ? Appreciate your help in this regard.

1 Answer
0
Accepted Answer

Of course you can do it. Let's start from the current encrypted snapshots. Grab the list with this command:

aws ec2 describe-snapshots --filters Name=encrypted,Values=true --query 'Snapshots[].[SnapshotId, KmsKeyId]'

Now you have to copy the snapshots to a new set, with the new CMK. This may do, reiterating for all your snaps.:

aws ec2 copy-snapshot \
    --source-region <region> \
    --source-snapshot-id <source-snapshot-id> \
    --destination-region <region> \
    --kms-key-id <new-key-id>

Alternatively, you can drop this lambda code and call it upon a key rotation event.

import boto3

def lambda_handler(event, context):
    ec2 = boto3.client('ec2', region_name='us-east-1')
    kms = boto3.client('kms', region_name='us-east-1')

    old_key_id = "<old-cmk-id>"  # Replace with actual old CMK ID
    new_key_id = "<new-cmk-id>"  # Replace with actual new CMK ID

    # Step 1: List snapshots with old CMK
    snapshots = ec2.describe_snapshots(
        Filters=[{'Name': 'kms-key-id', 'Values': [old_key_id]}]
    )['Snapshots']

    for snapshot in snapshots:
        snapshot_id = snapshot['SnapshotId']
        print(f"Re-encrypting Snapshot: {snapshot_id}")

        # Step 2: Copy snapshot with new CMK
        ec2.copy_snapshot(
            SourceSnapshotId=snapshot_id,
            SourceRegion='us-east-1',
            KmsKeyId=new_key_id,
            Description=f"Re-encrypted copy of {snapshot_id} with new CMK"
        )

I hope it works for you.

EXPERT

answered 2 years ago

EXPERT

reviewed 2 years ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.