You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

75 lines
2.4 KiB

  1. from datetime import date
  2. import boto3
  3. from botocore.exceptions import ClientError
  4. ################################################################################################
  5. #
  6. # Configuration Parameters
  7. #
  8. ################################################################################################
  9. endpoint_url = "http://localhost.localstack.cloud:4566"
  10. # you need to create a bucket in S3, here in this demo it is called "cloudcomp-counter", but
  11. # bucket names need to be world wide unique ;) The demo looks for a file that is named
  12. # "us-east-1" (same as our default region) in the bucket and expects a number in it to increase
  13. groupNr = 22
  14. currentYear = date.today().year
  15. globallyUniqueS3GroupBucketName = "cloudcomp-counter-" + str(currentYear) + "-group" + str(groupNr)
  16. # region = 'eu-central-1'
  17. region = 'us-east-1'
  18. functionName = 'cloudcomp-counter-lambda-demo'
  19. ################################################################################################
  20. #
  21. # boto3 code
  22. #
  23. ################################################################################################
  24. def cleanup_s3_bucket(s3_bucket):
  25. # Deleting objects
  26. for s3_object in s3_bucket.objects.all():
  27. s3_object.delete()
  28. # Deleting objects versions if S3 versioning enabled
  29. for s3_object_ver in s3_bucket.object_versions.all():
  30. s3_object_ver.delete()
  31. client = boto3.setup_default_session(region_name=region)
  32. s3Client = boto3.client('s3')
  33. s3Resource = boto3.resource('s3', endpoint_url=endpoint_url)
  34. lClient = boto3.client('lambda', endpoint_url=endpoint_url)
  35. apiClient = boto3.client("apigatewayv2", endpoint_url=endpoint_url)
  36. print("Deleting old API gateway...")
  37. print("------------------------------------")
  38. response = apiClient.get_apis()
  39. for api in response["Items"]:
  40. if api["Name"] == functionName + '-api':
  41. responseDelete = apiClient.delete_api(
  42. ApiId=api["ApiId"]
  43. )
  44. print("Deleting old function...")
  45. print("------------------------------------")
  46. try:
  47. response = lClient.delete_function(
  48. FunctionName=functionName,
  49. )
  50. except lClient.exceptions.ResourceNotFoundException:
  51. print('Function not available. No need to delete it.')
  52. print("Deleting old bucket...")
  53. print("------------------------------------")
  54. try:
  55. currentBucket = s3Resource.Bucket(globallyUniqueS3GroupBucketName)
  56. cleanup_s3_bucket(currentBucket)
  57. currentBucket.delete()
  58. except ClientError as e:
  59. print(e)