Sfoglia il codice sorgente

Starting to understand some things

Fred Damstra (Macbook 2015) 2 anni fa
parent
commit
c083e4abdc

+ 13 - 1
login.sh

@@ -20,5 +20,17 @@ RAW=$( curl --silent --show-error --location --request POST 'https://cognito-idp
 ACCESS_TOKEN=$( echo "$RAW" | jq '.AuthenticationResult.AccessToken' -r )
 
 echo ACCESS_TOKEN=\""${ACCESS_TOKEN}"\"
-echo curl --request GET \'"${ENDPOINT}"/example\' --header \"Authorization: Bearer \${ACCESS_TOKEN}\"
+echo ""
+echo ENDPOINT=\""${ENDPOINT}"\"
+echo ""
 
+echo "Calls:"
+echo "  "curl --request GET \'"${ENDPOINT}"/example\' --header \"Authorization: Bearer \${ACCESS_TOKEN}\"
+echo "  "curl --request GET \'"${ENDPOINT}"/echo\' --header \"Authorization: Bearer \${ACCESS_TOKEN}\" \| jq
+echo "  "
+echo view the comments for more.
+# When json encoded:
+# curl -d '{"fredwasalsohere": "true"}' -H "Content-Type: application/json" --request POST "${ENDPOINT}"'/echo?fredwashere=true' --header "Authorization: Bearer ${ACCESS_TOKEN}" | jq '.event.body | fromjson'
+#
+# When not:
+# curl -d "fredwasalsohere=2" --request POST ${ENDPOINT}"'/echo?fredwashere=true' --header "Authorization: Bearer ${ACCESS_TOKEN}" | jq -r .event.body | base64 -d

+ 74 - 0
terraform/lambda_echo.tf

@@ -0,0 +1,74 @@
+# /echo
+# Returns the event, and the context
+data "archive_file" "lambda_echo" {
+  type        = "zip"
+  source_file = "${path.module}/lambda_scripts/echo.py"
+  output_path = "${path.module}/lambda_scripts/echo.zip"
+}
+
+resource "aws_lambda_function" "lambda_echo" {
+  # If the file is not in the current working directory you will need to include a
+  # path.module in the filename.
+  filename      = data.archive_file.lambda_echo.output_path
+  function_name = "game_server_echo"
+  role          = aws_iam_role.lambda_role.arn
+  handler       = "echo.lambda_handler"
+
+  # The filebase64sha256() function is available in Terraform 0.11.12 and later
+  # For Terraform 0.11.11 and earlier, use the base64sha256() function and the file() function:
+  # source_code_hash = "${base64sha256(file("lambda_function_payload.zip"))}"
+  source_code_hash = data.archive_file.lambda_echo.output_base64sha256
+
+  runtime = "python3.9"
+
+  environment {
+    variables = {
+      foo = "bar"
+    }
+  }
+
+  vpc_config {
+    subnet_ids         = module.vpc.public_subnets # using public for now, to allow for Internets
+    security_group_ids = [aws_security_group.allow_all.id]
+  }
+
+  tags = local.tags
+}
+
+resource "aws_lambda_permission" "api_lambda_echo" {
+  statement_id  = "AllowExecutionFromAPI"
+  action        = "lambda:InvokeFunction"
+  function_name = aws_lambda_function.lambda_echo.function_name
+  principal     = "apigateway.amazonaws.com"
+
+  # The /*/*/* part allows invocation from any stage, method and resource path
+  # within API Gateway REST API.
+  #source_arn = "${aws_apigatewayv2_stage.test.execution_arn}/*/*/*"
+  source_arn = "${aws_apigatewayv2_api.gateway.execution_arn}/*/*/*"
+  #qualifier     = aws_lambda_alias.test_alias.name
+}
+
+# The API Gateway Route
+resource "aws_apigatewayv2_integration" "lambda_echo" {
+  api_id             = aws_apigatewayv2_api.gateway.id
+  integration_type   = "AWS_PROXY"
+  connection_type    = "INTERNET"
+  integration_method = "POST"
+  integration_uri    = "arn:aws:apigateway:${data.aws_region.current.name}:lambda:path/2015-03-31/functions/arn:aws:lambda:${data.aws_region.current.name}:${data.aws_caller_identity.current.id}:function:${aws_lambda_function.lambda_echo.function_name}/invocations"
+}
+
+resource "aws_apigatewayv2_route" "lambda_echo_GET" {
+  api_id             = aws_apigatewayv2_api.gateway.id
+  route_key          = "GET /echo"
+  target             = "integrations/${aws_apigatewayv2_integration.lambda_echo.id}"
+  authorization_type = "JWT"
+  authorizer_id      = aws_apigatewayv2_authorizer.auth.id
+}
+
+resource "aws_apigatewayv2_route" "lambda_echo_POST" {
+  api_id             = aws_apigatewayv2_api.gateway.id
+  route_key          = "POST /echo"
+  target             = "integrations/${aws_apigatewayv2_integration.lambda_echo.id}"
+  authorization_type = "JWT"
+  authorizer_id      = aws_apigatewayv2_authorizer.auth.id
+}

+ 2 - 0
terraform/lambda_example.tf

@@ -1,3 +1,5 @@
+# /example
+# always returns {"a": "b"}
 data "archive_file" "lambda_example" {
   type        = "zip"
   source_file = "${path.module}/lambda_scripts/example.py"

+ 19 - 0
terraform/lambda_scripts/echo.py

@@ -0,0 +1,19 @@
+#! /usr/bin/env python3
+
+import json
+
+
+def lambda_handler(event, context):
+    return {
+        "statusCode": 200,
+        "isBase64Encoded": False,
+        "body": json.dumps({"event": event, "context": context}, default=str),
+    }
+
+
+def main():
+    print("No CLI support.")
+
+
+if __name__ == "__main__":
+    main()

+ 38 - 0
terraform/lambda_scripts/storeit.py

@@ -0,0 +1,38 @@
+#! /usr/bin/env python3
+#
+# Sample code to store something in redis
+import base64
+import json
+import os
+
+
+def server_error(errorstring):
+    return {"statusCode": 200, "isBase64Encoded": False, "body": errorstring}
+
+
+def lambda_handler(event, context):
+    redis_endpoint = os.environ["REDIS_ENDPOINT"]
+
+    try:
+        params = event.get("body", {})
+        if event.get("isBase64Encoded", False):
+            params = base64.b64decode(body).decode()
+        params = json.loads(body)
+    except Exception as e:
+        return server_error(str(e))
+
+    # `params` should now be a valid structure.
+
+    return {
+        "statusCode": 200,
+        "isBase64Encoded": False,
+        "body": json.dumps({"asked_to_store": body}, default=str),
+    }
+
+
+def main():
+    print("No CLI support.")
+
+
+if __name__ == "__main__":
+    main()

+ 66 - 0
terraform/lambda_storeit.tf

@@ -0,0 +1,66 @@
+# /storeit
+# Returns the event, and the context
+data "archive_file" "lambda_storeit" {
+  type        = "zip"
+  source_file = "${path.module}/lambda_scripts/storeit.py"
+  output_path = "${path.module}/lambda_scripts/storeit.zip"
+}
+
+resource "aws_lambda_function" "lambda_storeit" {
+  # If the file is not in the current working directory you will need to include a
+  # path.module in the filename.
+  filename      = data.archive_file.lambda_storeit.output_path
+  function_name = "game_server_storeit"
+  role          = aws_iam_role.lambda_role.arn
+  handler       = "storeit.lambda_handler"
+
+  # The filebase64sha256() function is available in Terraform 0.11.12 and later
+  # For Terraform 0.11.11 and earlier, use the base64sha256() function and the file() function:
+  # source_code_hash = "${base64sha256(file("lambda_function_payload.zip"))}"
+  source_code_hash = data.archive_file.lambda_storeit.output_base64sha256
+
+  runtime = "python3.9"
+
+  environment {
+    variables = {
+      REDIS_ENDPOINT = aws_elasticache_cluster.redis.cache_nodes[0]["address"]
+    }
+  }
+
+  vpc_config {
+    subnet_ids         = module.vpc.public_subnets # using public for now, to allow for Internets
+    security_group_ids = [aws_security_group.allow_all.id]
+  }
+
+  tags = local.tags
+}
+
+resource "aws_lambda_permission" "api_lambda_storeit" {
+  statement_id  = "AllowExecutionFromAPI"
+  action        = "lambda:InvokeFunction"
+  function_name = aws_lambda_function.lambda_storeit.function_name
+  principal     = "apigateway.amazonaws.com"
+
+  # The /*/*/* part allows invocation from any stage, method and resource path
+  # within API Gateway REST API.
+  #source_arn = "${aws_apigatewayv2_stage.test.execution_arn}/*/*/*"
+  source_arn = "${aws_apigatewayv2_api.gateway.execution_arn}/*/*/*"
+  #qualifier     = aws_lambda_alias.test_alias.name
+}
+
+# The API Gateway Route
+resource "aws_apigatewayv2_integration" "lambda_storeit" {
+  api_id             = aws_apigatewayv2_api.gateway.id
+  integration_type   = "AWS_PROXY"
+  connection_type    = "INTERNET"
+  integration_method = "POST"
+  integration_uri    = "arn:aws:apigateway:${data.aws_region.current.name}:lambda:path/2015-03-31/functions/arn:aws:lambda:${data.aws_region.current.name}:${data.aws_caller_identity.current.id}:function:${aws_lambda_function.lambda_storeit.function_name}/invocations"
+}
+
+resource "aws_apigatewayv2_route" "lambda_storeit_POST" {
+  api_id             = aws_apigatewayv2_api.gateway.id
+  route_key          = "POST /storeit"
+  target             = "integrations/${aws_apigatewayv2_integration.lambda_storeit.id}"
+  authorization_type = "JWT"
+  authorizer_id      = aws_apigatewayv2_authorizer.auth.id
+}

+ 25 - 0
terraform/output.tf

@@ -25,6 +25,31 @@ resource "local_file" "output" {
   content  = jsonencode(local.tmp_output)
 }
 
+# New "master" output
 output "resources" {
   value = local.tmp_output
 }
+
+# Legacy, per item output
+output "cognito_user_pool" {
+  value = aws_cognito_user_pool.pool.id
+}
+
+output "cognito_client_id" {
+  value = aws_cognito_user_pool_client.client.id
+}
+
+output "api_endpoint" {
+  value = aws_apigatewayv2_api.gateway.api_endpoint
+}
+
+output "test_api_endpoint" {
+  value = aws_apigatewayv2_stage.test.invoke_url
+}
+
+output "test_instances_dns" {
+  value = {
+    "DNS" : aws_instance.test[*].public_dns,
+    "IP" : aws_instance.test[*].public_ip
+  }
+}