Reputation: 25
I want to create a lambda that will monitor a s3 bucket for every one hour. the conditions for the lambda should be like:
If files are uploaded today lambda should take the list of objects and check if the lastmodified is more than 1 hour from now.
if no files are uploaded today, lambda should do nothing. I tried below code, but it gives me all the older files. I don`t want lambda to check files that are uploaded yesterday or any previous to that. It should only check those files that are uploaded today and tell me if the files are older than 1 hour from now.
I don`t want s3 event notification.
Please help me how to achieve this
import boto3
import os
from datetime import datetime, timedelta, timezone
from dateutil.tz import tzutc, UTC
TOPIC_ARN = 'mysnstopicarn'
s3_resource = boto3.client('s3')
sns_resource = boto3.resource('sns')
sns_topic = sns_resource.Topic(TOPIC_ARN)
lessthan = []
greaterthan = []
result = []
listobjects = s3_resource.list_objects(Bucket='mybucketname',Delimiter='Archives')['Contents']
def lambda_handler(event, context):
for key in listobjects:
if key['LastModified'] < datetime.now(timezone.utc) - timedelta(hours=1):
lessthan.append(key['Key'])
for i in lessthan:
path, filename = os.path.split(i)
result.append(filename)
final = list(filter(None, result))
sns_topic.publish(Message=f"This object {final} is more than one hour old")
Upvotes: 1
Views: 1079
Reputation: 25669
You are looking for the the most recent files, so you should look for LastModified
values greater than your target date.
# if LastModified is greater than (not less than) the target
if key['LastModified'] > datetime.now(timezone.utc) - timedelta(hours=1):
Upvotes: 2