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.

143 lines
4.8 KiB

  1. from datetime import date
  2. import zipfile
  3. import boto3
  4. from botocore.exceptions import ClientError
  5. ################################################################################################
  6. #
  7. # Configuration Parameters
  8. #
  9. ################################################################################################
  10. endpoint_url = "http://localhost.localstack.cloud:4566"
  11. # you need to create a bucket in S3, here in this demo it is called "cloudcomp-counter", but
  12. # bucket names need to be world wide unique ;) The demo looks for a file that is named
  13. # "us-east-1" (same as our default region) in the bucket and expects a number in it to increase
  14. groupNr = 22
  15. currentYear = date.today().year
  16. globallyUniqueS3GroupBucketName = "cloudcomp-counter-" + str(currentYear) + "-group" + str(groupNr)
  17. # region = 'eu-central-1'
  18. region = 'us-east-1'
  19. functionName = 'cloudcomp-counter-lambda-demo'
  20. # see ARN for AWS Academy LabRole function here:
  21. # https://us-east-1.console.aws.amazon.com/iamv2/home?region=us-east-1#/roles/details/LabRole?section=permissions
  22. # roleArn = 'arn:aws:iam::309000625112:role/service-role/cloudcomp-counter-demo-role-6rs7pah3'
  23. # roleArn = 'arn:aws:iam::919927306708:role/cloudcomp-s3-access'
  24. roleArn = 'arn:aws:iam::488766701848:role/LabRole'
  25. ################################################################################################
  26. #
  27. # boto3 code
  28. #
  29. ################################################################################################
  30. def cleanup_s3_bucket(s3_bucket):
  31. # Deleting objects
  32. for s3_object in s3_bucket.objects.all():
  33. s3_object.delete()
  34. # Deleting objects versions if S3 versioning enabled
  35. for s3_object_ver in s3_bucket.object_versions.all():
  36. s3_object_ver.delete()
  37. client = boto3.setup_default_session(region_name=region)
  38. s3Client = boto3.client('s3', endpoint_url=endpoint_url)
  39. s3Resource = boto3.resource('s3', endpoint_url=endpoint_url)
  40. lClient = boto3.client('lambda', endpoint_url=endpoint_url)
  41. apiClient = boto3.client("apigatewayv2", endpoint_url=endpoint_url)
  42. print("Deleting old API gateway...")
  43. print("------------------------------------")
  44. response = apiClient.get_apis()
  45. for api in response["Items"]:
  46. if api["Name"] == functionName + '-api':
  47. responseDelete = apiClient.delete_api(
  48. ApiId=api["ApiId"]
  49. )
  50. print("Deleting old function...")
  51. print("------------------------------------")
  52. try:
  53. response = lClient.delete_function(
  54. FunctionName=functionName,
  55. )
  56. except lClient.exceptions.ResourceNotFoundException:
  57. print('Function not available. No need to delete it.')
  58. print("Deleting old bucket...")
  59. print("------------------------------------")
  60. try:
  61. currentBucket = s3Resource.Bucket(globallyUniqueS3GroupBucketName)
  62. cleanup_s3_bucket(currentBucket)
  63. currentBucket.delete()
  64. except ClientError as e:
  65. print(e)
  66. print("creating S3 bucket (must be globally unique)...")
  67. print("------------------------------------")
  68. try:
  69. response = s3Client.create_bucket(Bucket=globallyUniqueS3GroupBucketName)
  70. response = s3Client.put_object(Bucket=globallyUniqueS3GroupBucketName, Key='us-east-1', Body=str(0))
  71. except ClientError as e:
  72. print(e)
  73. print("creating new function...")
  74. print("------------------------------------")
  75. zf = zipfile.ZipFile('lambda-deployment-archive.zip', 'w', zipfile.ZIP_DEFLATED)
  76. zf.write('lambda_function.py')
  77. zf.close()
  78. lambdaFunctionARN = ""
  79. with open('lambda-deployment-archive.zip', mode='rb') as file:
  80. zipfileContent = file.read()
  81. response = lClient.create_function(
  82. FunctionName=functionName,
  83. Runtime='python3.9',
  84. Role=roleArn,
  85. Code={
  86. 'ZipFile': zipfileContent
  87. },
  88. Handler='lambda_function.lambda_handler',
  89. Publish=True,
  90. Environment={
  91. 'Variables': {
  92. 'bucketName': globallyUniqueS3GroupBucketName
  93. }
  94. }
  95. )
  96. lambdaFunctionARN = response['FunctionArn']
  97. print("Lambda Function and S3 Bucket to store the counter are available.\n"
  98. "\n"
  99. "You can now run invoke-function.py to view an increment the counter.\n"
  100. "Try to understand how Lambda can be used to cut costs regarding cloud services and what its pros\n"
  101. "and cons are.\n")
  102. # sadly, AWS Academy Labs don't allow API gateways
  103. # API gateway would allow getting an HTTP endpoint that we could access directly in the browser,
  104. # that would call our function, as in the provided demo:
  105. #
  106. # https://348yxdily0.execute-api.eu-central-1.amazonaws.com/default/cloudcomp-counter-demo
  107. print("creating API gateway...")
  108. print("------------------------------------")
  109. response = apiClient.create_api(
  110. Name=functionName + '-api',
  111. ProtocolType='HTTP',
  112. Target=lambdaFunctionARN
  113. )
  114. apiArn = response
  115. print("API Endpoint can be reached at: http://" + apiArn["ApiEndpoint"])