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.

153 lines
5.1 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. # 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. # see ARN for AWS Academy LabRole function here:
  20. # https://us-east-1.console.aws.amazon.com/iamv2/home?region=us-east-1#/roles/details/LabRole?section=permissions
  21. # roleArn = 'arn:aws:iam::309000625112:role/service-role/cloudcomp-counter-demo-role-6rs7pah3'
  22. # roleArn = 'arn:aws:iam::919927306708:role/cloudcomp-s3-access'
  23. # roleArn = 'arn:aws:iam::488766701848:role/LabRole'
  24. ################################################################################################
  25. #
  26. # boto3 code
  27. #
  28. ################################################################################################
  29. def cleanup_s3_bucket(s3_bucket):
  30. # Deleting objects
  31. for s3_object in s3_bucket.objects.all():
  32. s3_object.delete()
  33. # Deleting objects versions if S3 versioning enabled
  34. for s3_object_ver in s3_bucket.object_versions.all():
  35. s3_object_ver.delete()
  36. client = boto3.setup_default_session(region_name=region)
  37. iamClient = boto3.client('iam')
  38. s3Client = boto3.client('s3')
  39. s3Resource = boto3.resource('s3')
  40. lClient = boto3.client('lambda')
  41. apiClient = boto3.client("apigatewayv2")
  42. print("Getting AWS Academy LabRole ARN...")
  43. print("------------------------------------")
  44. response = iamClient.list_roles()
  45. for role in response["Roles"]:
  46. if role["RoleName"] == "LabRole":
  47. roleArn = role["Arn"]
  48. print(roleArn)
  49. print("Deleting old function...")
  50. print("------------------------------------")
  51. try:
  52. response = lClient.delete_function(
  53. FunctionName=functionName,
  54. )
  55. except lClient.exceptions.ResourceNotFoundException:
  56. print('Function not available. No need to delete it.')
  57. print("Deleting old bucket...")
  58. print("------------------------------------")
  59. try:
  60. currentBucket = s3Resource.Bucket(globallyUniqueS3GroupBucketName)
  61. cleanup_s3_bucket(currentBucket)
  62. currentBucket.delete()
  63. except ClientError as e:
  64. print(e)
  65. print("creating S3 bucket (must be globally unique)...")
  66. print("------------------------------------")
  67. try:
  68. response = s3Client.create_bucket(Bucket=globallyUniqueS3GroupBucketName)
  69. response = s3Client.put_object(Bucket=globallyUniqueS3GroupBucketName, Key='us-east-1', Body=str(0))
  70. except ClientError as e:
  71. print(e)
  72. print("creating new function...")
  73. print("------------------------------------")
  74. zf = zipfile.ZipFile('lambda-deployment-archive.zip', 'w', zipfile.ZIP_DEFLATED)
  75. zf.write('lambda_function.py')
  76. zf.close()
  77. lambdaFunctionARN = ""
  78. with open('lambda-deployment-archive.zip', mode='rb') as file:
  79. zipfileContent = file.read()
  80. response = lClient.create_function(
  81. FunctionName=functionName,
  82. Runtime='python3.9',
  83. Role=roleArn,
  84. Code={
  85. 'ZipFile': zipfileContent
  86. },
  87. Handler='lambda_function.lambda_handler',
  88. Publish=True,
  89. Environment={
  90. 'Variables': {
  91. 'bucketName': globallyUniqueS3GroupBucketName
  92. }
  93. }
  94. )
  95. lambdaFunctionARN = response['FunctionArn']
  96. print("Lambda Function and S3 Bucket to store the counter are available. Sadly, AWS Academy labs do not allow\n"
  97. "creating an API gateway to be able to access the Lambda function directly via HTTP from the browser, as\n"
  98. "shown in https://348yxdily0.execute-api.eu-central-1.amazonaws.com/default/cloudcomp-counter-demo.\n"
  99. "\n"
  100. "However you can now run invoke-function.py to view an increment the counter. You can also use \n"
  101. "the test button in the Lambda AWS console. In this case you need to send the content\n"
  102. "\n"
  103. "{\n"
  104. " \"input\": \"1\"\n"
  105. "}\n"
  106. "\n"
  107. "to increment the counter by 1.\n"
  108. "Try to understand how Lambda can be used to cut costs regarding cloud services and what its pros\n"
  109. "and cons are.\n")
  110. # sadly, AWS Academy Labs don't allow API gateways
  111. # API gateway would allow getting an HTTP endpoint that we could access directly in the browser,
  112. # that would call our function, as in the provided demo:
  113. #
  114. # https://348yxdily0.execute-api.eu-central-1.amazonaws.com/default/cloudcomp-counter-demo
  115. # print("creating API gateway...")
  116. # print("------------------------------------")
  117. #
  118. # #apiArn = ""
  119. # response = apiClient.create_api(
  120. # Name=functionName + '-api',
  121. # ProtocolType='HTTP',
  122. # Target=lambdaFunctionARN
  123. # )
  124. # #apiArn=response['']
  125. #
  126. # #response = lClient.create_event_source_mapping(
  127. # # EventSourceArn=apiArn,
  128. # #)