简体   繁体   中英

Delete CloudTrail along with the S3 bucket attached to it using Boto3

I am working on a python script to delete a CloudTrail along with the S3 bucket associated with it, I am not getting any error but the code also does not delete the S3 bucket.I am able to delete the cloudtrail. This is the code that I have: def lambda_handler(event, context):

   import boto3
   import pprint
   client=boto3.client('ec2')
   s3_resource=boto3.client('s3')
   all_regions=client.describe_regions()
   #pprint.pprint(all_regions)
   list_of_regions=[]
   del_list = []
   Bucket_names=[]
   for each_reg in all_regions['Regions']:
      list_of_regions.append(each_reg['RegionName'])
      #print(each_reg['RegionName'])
   #print(list_of_regions)
   for each_reg in list_of_regions:
      client = boto3.client('cloudtrail', region_name=each_reg)
      trailnames=[trail['TrailARN'] for trail in client.list_trails()['Trails']]
      #print(trailnames,each_reg)#List out the Trails Name
   for data in trailnames:
      #print(data)
      response = client.describe_trails(trailNameList=[data])
      #print(response)
      Bucket_Name =response['trailList'][0].get('S3BucketName')
      #print(Bucket_Name)
      Bucket_names.append(Bucket_Name)
      #print(Bucket_Name)
      #home_region = response['trailList'][0].get('HomeRegion')
      #print(home_region)
      #home_client = boto3.client('cloudtrail', region_name=home_region)
      #print(home_client)
      #del_response =home_client.delete_trail(Name=data)
      #print(data)
   for buckets  in Bucket_names:
      s3_resource = boto3.client('s3', region_name=each_reg)
      #print(buckets)
      objects = s3_resource.list_objects(Bucket=buckets)['Contents']
      #print(objects)
      #a=objects
      #print(a[5].get('Key'))
      file_key_name=objects[0].get('Key')
      #print(file_key_name)
      copy_source_bucket = {'Bucket': buckets, 'Key': file_key_name}
      #s3_resource.copy(copy_source_bucket, buckets, file_key_name, ExtraArgs={'ACL': 'bucket-owner-full-control'})
      copy_objectss=s3_resource.copy_object(Bucket = buckets, Key = file_key_name, CopySource = copy_source_bucket,ACL='bucket-owner-full-control',MetadataDirective='REPLACE')
      print(copy_objectss)
      s3_del = client.delete_bucket(
         Bucket='buckets'
         )

I feel you need to purge all the objects in the S3 bucket before deleting the bucket, see this link for how to delete all objects in a bucket: https://stackoverflow.com/a/43328646/431432

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM