Skip to content

How to automate daily delete snapshots and automate daily copy snapshots between regions

0

Hi re:Post !

Everyday we are manually coping (14) rds postgresql snapshots from one region (N. California us-west-1) to another (Oregon us-west-2). But first, we are manually deleting the oldest (14) from Oregon to make room for the N. California snapshots b/c of the 100 manual copies limit per region.

We would like to automate daily:

  1. Automate deleting the oldest (14) manual snapshot copies in the Oregon region and then
  2. Automate coping the daily newest (14) system snapshots in N. California over to Oregon region. (There are only (14) new snapshots per day in N. California).

We been reading: "https://dev.to/aws-builders/aws-event-bridge-and-lambda-to-copy-rds-snapshots-to-another-region-kl3"

which seems to cover 2) above but before we try that, how would we handle "1) Deleting the oldest (14) manual snapshot copies in the Oregon Region"

We know the exact names of the db snapshots we need to copy over and what to rename name the copied snapshots. This will not change day to day except for the dates.

For example, using today's workflow, below are the renamed copies that end up in Oregon:

copy-rds-db-amgen-2025-06-16

copy-rds-db-alpine-2025-06-16

copy-rds-db-walgreens-2025-06-16

copy-rds-db-vividion-2025-06-16

copy-rds-db-avidity-2025-06-16

copy-rds-db-urovant-2025-06-16

copy-rds-db-atlas-2025-06-16

copy-rds-db-vir-2025-06-16

copy-rds-db-recursion-2025-06-16

copy-rds-db-genentech-2025-06-16

copy-rds-db-pfizer-cbx-2025-06-16

copy-rds-db-kyverna-2025-06-16

copy-rds-db-enveda-2025-06-16

copy-rds-db-syndax-2025-06-16

Thank you for your time and help!

Best Regards,

Donald


July 15, 2025 - New Question based on way below plan from AI tool:

Hi Re:Post ! I'm resurrecting this post ;) ...

Regarding this step from above:

" Create an IAM role for your Lambda function with permissions for:

rds:DescribeDBSnapshots

rds:CopyDBSnapshot

rds:DeleteDBSnapshot

"

I'm at the "Create Role" workflow, which has (3) steps.

I'm not finding these permissions/roles listed at the 2nd step, "Add permissions":

rds:DescribeDBSnapshots

rds:CopyDBSnapshot

rds:DeleteDBSnapshot

Enter image description here Enter image description here

I think I'm missing something!

Please advise.

Thank you for your time and help!

Best Regards, Donald

asked 8 months ago237 views
2 Answers
1
Accepted Answer

You can automate both the deletion of old snapshots and copying of new snapshots between regions using AWS Lambda with EventBridge Scheduler. Here's how to implement this solution:

Option 1: Using a Lambda Function

You can create a Lambda function that performs both tasks:

  1. First, delete the oldest 14 manual snapshots in Oregon (us-west-2)
  2. Then copy the latest 14 system-generated snapshots from N. California (us-west-1) to Oregon

Here's a Python Lambda function that would accomplish this:

import boto3
import os
from datetime import datetime

# Define regions
SOURCE_REGION = "us-west-1"  # N. California
DEST_REGION = "us-west-2"    # Oregon
NUM_SNAPSHOTS = 14           # Number of snapshots to process

def lambda_handler(event, context):
# Create RDS clients for both regions
source_rds = boto3.client('rds', region_name=SOURCE_REGION)
dest_rds = boto3.client('rds', region_name=DEST_REGION)

# Step 1: Delete oldest manual snapshots in destination region
delete_oldest_snapshots(dest_rds, NUM_SNAPSHOTS)

# Step 2: Copy latest system snapshots from source to destination
copy_latest_snapshots(source_rds, dest_rds, NUM_SNAPSHOTS)

return {
'statusCode': 200,
'body': f'Successfully processed {NUM_SNAPSHOTS} snapshots'
}

def delete_oldest_snapshots(dest_rds, count):
# Get all manual snapshots in destination region
response = dest_rds.describe_db_snapshots(SnapshotType='manual')

# Sort snapshots by creation time (oldest first)
snapshots = sorted(response['DBSnapshots'], key=lambda s: s['SnapshotCreateTime'])

# Delete the oldest 'count' snapshots
for i, snapshot in enumerate(snapshots):
if i >= count:
break

snapshot_id = snapshot['DBSnapshotIdentifier']
print(f"Deleting snapshot: {snapshot_id}")

try:
dest_rds.delete_db_snapshot(DBSnapshotIdentifier=snapshot_id)
print(f"Successfully deleted snapshot: {snapshot_id}")
except Exception as e:
print(f"Error deleting snapshot {snapshot_id}: {str(e)}")

def copy_latest_snapshots(source_rds, dest_rds, count):
# Get all automated snapshots in source region
response = source_rds.describe_db_snapshots(SnapshotType='automated')

# Sort snapshots by creation time (newest first)
snapshots = sorted(response['DBSnapshots'], 
key=lambda s: s['SnapshotCreateTime'], 
reverse=True)

# Get today's date for naming
today = datetime.now().strftime("%Y-%m-%d")

# Define the database names based on your example
db_names = [
"amgen", "alpine", "walgreens", "vividion", "avidity", 
"urovant", "atlas", "vir", "recursion", "genentech", 
"pfizer-cbx", "kyverna", "enveda", "syndax"
]

# Copy the newest 'count' snapshots
for i, snapshot in enumerate(snapshots[:count]):
if i >= count:
break

source_snapshot_id = snapshot['DBSnapshotIdentifier']
db_instance_id = snapshot['DBInstanceIdentifier']

# Use the corresponding db name from the list if available
db_name = db_names[i] if i < len(db_names) else db_instance_id

# Create target snapshot name
target_snapshot_id = f"copy-rds-db-{db_name}-{today}"

print(f"Copying snapshot {source_snapshot_id} to {target_snapshot_id}")

try:
# Create ARN for source snapshot
source_arn = f"arn:aws:rds:{SOURCE_REGION}:{snapshot['DBSnapshotArn'].split(':')[4]}:{source_snapshot_id}"

# Copy the snapshot
dest_rds.copy_db_snapshot(
SourceDBSnapshotIdentifier=source_arn,
TargetDBSnapshotIdentifier=target_snapshot_id,
SourceRegion=SOURCE_REGION
)
print(f"Successfully initiated copy of {source_snapshot_id} to {target_snapshot_id}")
except Exception as e:
print(f"Error copying snapshot {source_snapshot_id}: {str(e)}")

Option 2: Using RDS Cross-Region Backup Replication

Alternatively, you can enable automated cross-region backup replication directly in RDS:

  1. Open the Amazon RDS console
  2. Navigate to "Automated backups"
  3. Select your database and click "Actions" then "Manage cross-Region replication"
  4. Enable replication to Oregon (us-west-2)
  5. Set the replicated backup retention period to match your needs

This approach handles the copying automatically, but you would still need a Lambda function to handle the deletion of old snapshots.

Implementation Steps:

  1. Create an IAM role for your Lambda function with permissions for:
  • rds:DescribeDBSnapshots
  • rds:CopyDBSnapshot
  • rds:DeleteDBSnapshot
  1. Create the Lambda function using the code above

  2. Set up EventBridge Scheduler to trigger the Lambda function daily:

  • Open the EventBridge console
  • Create a new schedule
  • Set the schedule pattern to run daily
  • Select your Lambda function as the target
  1. Test the function with a small number of snapshots first to ensure it works as expected

This solution will automate your daily workflow of deleting old snapshots and copying new ones between regions.
Sources
How to automate coping snapshots from N.California to Oregon? | AWS re:Post
Community | Protect Your Data in Amazon RDS Against Disaster or Accidental Deletion
Community | Protect Your Data in Amazon RDS Against Disaster or Accidental Deletion
RDS Snapshot | Delete - AMS Advanced Change Type Reference

answered 8 months ago
EXPERT
reviewed 8 months ago
0

Hey DC, its been a while.

I recall you asking the same question a few months ago.. https://repost.aws/questions/QUXX6v4d7JRyeq6YTDhOQZ6A/how-to-automate-coping-snapshots-from-n-california-to-oregon

Not sure if that is still the case still

EXPERT
answered 8 months ago
EXPERT
reviewed 8 months ago
  • Hi Gary! Yes it has been awhile and yes this is essentially the question from a few months ago. The initiative got sidelined but now it's back as a task for me to complete. The AI answer did a really good job - I forgot to mention the naming of the copies as a step in this process but somehow the AI 'realized' this and addressed it as well.

    I'm trying to figure out why we're not using "Option 2" above suggested by the bot. We have these (14) dbs in Ohio, they are setup with automatic backups, with replication to N. California with a retention of 30 days. In Oregon, we already have a group of snapshots being auto replicated there (20) from Ohio backups. Why are we not just adding those (14) snapshots to the auto replication process in place from Ohio to Oregon? Is there a limit?

    Thank you for your time and help! Best Regards, Donald

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.