Reputation:
I am working on a Boto script to delete the resource when invoked by a lambda function, I am not sure how to invoke the delete function using Lambda, "path"
has the resource to be deleted and below is the lambda function being used to delete the resource . Thanks in advance.
print(path)
def delete_bucket(path):
while True:
objects = s3.list_objects(Bucket=path)
content = objects.get('Contents', [])
if len(content) == 0:
break
for obj in content:
s3.delete_object(Bucket=path, Key=obj['Key'])
s3.delete_bucket(Bucket=path)
def lambda_handler(event, context):
delete_bucket(path)
Upvotes: 0
Views: 5977
Reputation: 1532
Following code is verified on Python 3.8;
import boto3
def get_s3_client():
return boto3.client('s3', region_name='eu-west-1') #change region_name as per your setup
def delete_bucket(bucket_name): #here bucket_name can be path as per logic in your code
s3_client = get_s3_client()
while True:
objects = s3_client.list_objects(Bucket=bucket_name)
content = objects.get('Contents', [])
if len(content) == 0:
break
for obj in content:
s3_client.delete_object(Bucket=bucket_name, Key=obj['Key'])
s3_client.delete_bucket(Bucket=bucket_name)
def lambda_handler(event, context):
# put your existing logic here
delete_bucket(path)
Note: If you have versioning enabled for the bucket, then you will need extra logic to list objects using list_object_versions
and then iterate over such a version object to delete them using delete_object
Upvotes: 3