Boto3 and AWS Lambda - deleting snapshots older than
<p>I'm currently utilising AWS Lambda to create snapshots of my database and delete snapshots older than 6 days.  I'm using the Boto3 library to interface with the AWS API. I'm using a CloudWatch rule to trigger the deletion code every day. </p>

<p>Normally this is working fine, but I've come across an issue where at the start of the month (first 6 days) the delete script does not appear to delete any snapshots, even though snapshots older than 6 days exist. </p>

<p>The code is below: </p>

<pre><code>import json
import boto3
from datetime import datetime, timedelta, tzinfo

class Zone(tzinfo):
    def __init__(self,offset,isdst,name):
        self.offset = offset
        self.isdst = isdst
        self.name = name
    def utcoffset(self, dt):
        return timedelta(hours=self.offset) + self.dst(dt)
    def dst(self, dt):
        return timedelta(hours=1) if self.isdst else timedelta(0)
    def tzname(self,dt):
        return self.name

UTC = Zone(10,False,'UTC')

# Setting retention period of 6 days
retentionDate = datetime.now(UTC) - timedelta(days=6)

def lambda_handler(event, context):
    print("Connecting to RDS")
    rds = boto3.setup_default_session(region_name='ap-southeast-2')
    client = boto3.client('rds')
    snapshots = client.describe_db_snapshots(SnapshotType='manual')
    print('Deleting all DB Snapshots older than %s' % retentionDate)

    for i in snapshots['DBSnapshots']:
        if i['SnapshotCreateTime'] &lt; retentionDate:
            print ('Deleting snapshot %s' % i['DBSnapshotIdentifier'])
              client.delete_db_snapshot(DBSnapshotIdentifier=i['DBSnapshotIdentifier']
        )
</code></pre>

<p>Due to the distributed nature of the CloudWatch Events and the target services, the delay between the time the scheduled rule is triggered and the time the target service honors the execution of the target resource might be several seconds. Your scheduled rule will be triggered within that minute but not on the precise 0th second.</p>

<p>In that case, your utc now will may miss a few seconds during execution there by retention date also may miss a few seconds. This should be very minimal but still there is a chance for missed deletion. Going by that, the subsequent run should delete the missed ones in the earlier run.</p>

python aws-lambda boto3