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.

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