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.

146 lines
5.0 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. # roleName = 'arn:aws:iam::309000625112:role/service-role/cloudcomp-counter-demo-role-6rs7pah3'
  23. # roleName = 'arn:aws:iam::919927306708:role/cloudcomp-s3-access'
  24. roleName = '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 function...")
  43. print("------------------------------------")
  44. try:
  45. response = lClient.delete_function(
  46. FunctionName=functionName,
  47. )
  48. except lClient.exceptions.ResourceNotFoundException:
  49. print('Function not available. No need to delete it.')
  50. print("Deleting old bucket...")
  51. print("------------------------------------")
  52. try:
  53. currentBucket = s3Resource.Bucket(globallyUniqueS3GroupBucketName)
  54. cleanup_s3_bucket(currentBucket)
  55. currentBucket.delete()
  56. except ClientError as e:
  57. print(e)
  58. print("creating S3 bucket (must be globally unique)...")
  59. print("------------------------------------")
  60. try:
  61. response = s3Client.create_bucket(Bucket=globallyUniqueS3GroupBucketName)
  62. response = s3Client.put_object(Bucket=globallyUniqueS3GroupBucketName, Key='us-east-1', Body=str(0))
  63. except ClientError as e:
  64. print(e)
  65. print("creating new function...")
  66. print("------------------------------------")
  67. zf = zipfile.ZipFile('lambda-deployment-archive.zip', 'w', zipfile.ZIP_DEFLATED)
  68. zf.write('lambda_function.py')
  69. zf.close()
  70. lambdaFunctionARN = ""
  71. with open('lambda-deployment-archive.zip', mode='rb') as file:
  72. zipfileContent = file.read()
  73. response = lClient.create_function(
  74. FunctionName=functionName,
  75. Runtime='python3.9',
  76. Role=roleName,
  77. Code={
  78. 'ZipFile': zipfileContent
  79. },
  80. Handler='lambda_function.lambda_handler',
  81. Publish=True,
  82. Environment={
  83. 'Variables': {
  84. 'bucketName': globallyUniqueS3GroupBucketName
  85. }
  86. }
  87. )
  88. lambdaFunctionARN = response['FunctionArn']
  89. print("Lambda Function and S3 Bucket to store the counter are available. Sadly, AWS Academy labs do not allow\n"
  90. "creating an API gateway to be able to access the Lambda function directly via HTTP from the browser, as\n"
  91. "shown in https://348yxdily0.execute-api.eu-central-1.amazonaws.com/default/cloudcomp-counter-demo.\n"
  92. "\n"
  93. "However you can now run invoke-function.py to view an increment the counter. You can also use \n"
  94. "the test button in the Lambda AWS console. In this case you need to send the content\n"
  95. "\n"
  96. "{\n"
  97. " \"input\": \"1\"\n"
  98. "}\n"
  99. "\n"
  100. "to increment the counter by 1.\n"
  101. "Try to understand how Lambda can be used to cut costs regarding cloud services and what its pros\n"
  102. "and cons are.\n")
  103. # sadly, AWS Academy Labs don't allow API gateways
  104. # API gateway would allow getting an HTTP endpoint that we could access directly in the browser,
  105. # that would call our function, as in the provided demo:
  106. #
  107. # https://348yxdily0.execute-api.eu-central-1.amazonaws.com/default/cloudcomp-counter-demo
  108. # print("creating API gateway...")
  109. # print("------------------------------------")
  110. #
  111. # #apiArn = ""
  112. # response = apiClient.create_api(
  113. # Name=functionName + '-api',
  114. # ProtocolType='HTTP',
  115. # Target=lambdaFunctionARN
  116. # )
  117. # #apiArn=response['']
  118. #
  119. # #response = lClient.create_event_source_mapping(
  120. # # EventSourceArn=apiArn,
  121. # #)