Преглед на файлове

Working through to lambda function.

Gogs преди 5 години
родител
ревизия
cf0ca5c397

+ 1 - 0
Architecture.md

@@ -13,6 +13,7 @@ Naming Convention: None
 Features:
   * CloudWatch Events Rules
     * Can be API calls or responses to AWS Config
+    * From external accounts, puts the event on the main account's event bus.
   * "Custom" entry (Message sent to SNS topic), such as a request to scan for an issue.
 
 ### SNS Distribution

+ 6 - 0
sample/TODO.md

@@ -1,3 +1,9 @@
+# Overall
+* Add second account
+
+# KMS
+* Figure out exactly what actions cloudwatch needs. `kms:*` is too permissive.
+
 # SNS
 * Allow use of custom key
 

+ 6 - 0
sample/eventbus.tf

@@ -0,0 +1,6 @@
+# Allow other accounts to publish to the master account event bus
+resource "aws_cloudwatch_event_permission" "CrossAccount123456789012" {
+  principal    = "123456789012"
+  statement_id = "SampleAccount"
+}
+

+ 23 - 0
sample/fcm-analysis-EbsEncryptionByDefault/EbsEncryptionByDefault.py

@@ -0,0 +1,23 @@
+#! /usr/bin/env python3
+import logging
+import json
+import os
+
+logger = logging.getLogger('FCM')
+
+def lambda_handler(event, context):
+    global logger
+    try:
+        logger.setLevel(os.environ['LOGLEVEL'])
+    except:
+        logger.setLevel('DEBUG')
+        logger.warn('Logging level not set or set to invalid value.')
+    logger.debug(f'Inbound event: {json.dumps(event, default=str)}')
+    return { 'msg': 'Hello!' }
+
+if __name__ == "__main__":
+    handler = logging.StreamHandler()
+    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
+    handler.setFormatter(formatter)
+    logger.addHandler(handler)
+    lambda_handler(event = { 'test': 'true' }, context={})

+ 22 - 1
sample/kms.tf

@@ -19,7 +19,7 @@ resource "aws_kms_key" "FCM-Key" {
             "Resource": "*"
         },
 				{
-					"Sid": "Allow Amazon SNS to use this key",
+					"Sid": "Allow Amazon Services to use this key",
 					"Effect": "Allow",
 					"Principal": {
 						"Service": "sns.amazonaws.com"
@@ -29,6 +29,27 @@ resource "aws_kms_key" "FCM-Key" {
 						"kms:GenerateDataKey*"
 					],
 					"Resource": "*"
+				},
+				{
+					"Sid": "Allow CloudWatch Events to use this key",
+					"Effect": "Allow",
+					"Principal": {
+						"Service": "events.amazonaws.com"
+					},
+          "Action": "kms:*",
+					"Resource": "*"
+				},
+				{
+					"Sid": "Grant access to lambda functions",
+					"Effect": "Allow",
+					"Principal": {
+            "AWS": "${aws_iam_role.fcm-analysis-EbsEncryptionByDefault.arn}"
+					},
+					"Action": [
+            "kms:GenerateDataKey*",
+            "kms:Decrypt"
+          ],
+					"Resource": "*"
 				}
 			]
     }

+ 97 - 0
sample/lambda.fcm-analysis-EbsEncryptionByDefault.tf

@@ -0,0 +1,97 @@
+resource "aws_iam_role" "fcm-analysis-EbsEncryptionByDefault" {
+  name = "fcm-analysis-EbsEncryptionByDefault"
+
+  assume_role_policy = <<ASSUMEROLEDOC
+{
+  "Version": "2012-10-17",
+  "Statement": [
+    {
+      "Action": "sts:AssumeRole",
+      "Principal": {
+        "Service": "lambda.amazonaws.com"
+      },
+      "Effect": "Allow",
+      "Sid": ""
+    }
+  ]
+}
+ASSUMEROLEDOC
+}
+
+resource "aws_iam_policy" "fcm-analysis-EbsEncryptionByDefault" {
+  name        = "fcm-analysis-EbsEncryptionByDefault"
+  path        = "/fcm/"
+  description = "FCM policy for EbsEncryptionByDefault Enforcement Analysis"
+
+  policy = <<POLICYDOC
+{
+    "Version": "2012-10-17",
+    "Statement": [
+        {
+            "Effect": "Allow",
+            "Action": "logs:CreateLogGroup",
+            "Resource": "
+        },
+        {
+            "Effect": "Allow",
+            "Action": [
+                "logs:CreateLogStream",
+                "logs:PutLogEvents"
+            ],
+            "Resource": [
+                "arn:aws:logs:us-east-2:082012130604:log-group:/aws/lambda/*"
+            ]
+        },
+        {
+            "Sid": "RequiredLambdaAccess",
+            "Effect": "Allow",
+            "Action": [
+                "kms:Decrypt",
+                "kms:GenerateDataKey*",
+                "sqs:ReceiveMessage",
+                "sqs:DeleteMessage",
+                "sqs:GetQueueAttributes"
+            ],
+            "Resource": "*"
+         }
+    ]
+}
+POLICYDOC
+}
+
+resource "aws_iam_role_policy_attachment" "fcm-analysis-EbsEncryptionByDefault" {
+  role       = "${aws_iam_role.fcm-analysis-EbsEncryptionByDefault.name}"
+  policy_arn = "${aws_iam_policy.fcm-analysis-EbsEncryptionByDefault.arn}"
+}
+
+resource "aws_lambda_function" "fcm-analysis-EbsEncryptionByDefault" {
+  filename      = "fcm-analysis-EbsEncryptionByDefault.zip"
+  function_name = "fcm-analysis-EbsEncryptionByDefault"
+  role          = "${aws_iam_role.fcm-analysis-EbsEncryptionByDefault.arn}"
+  handler       = "EbsEncryptionByDefault.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.fcm-analysis-EbsEncryptionByDefault.output_base64sha256}"
+
+  runtime = "python3.7"
+
+  environment {
+    variables = {
+      LOGLEVEL = "DEBUG"
+    }
+  }
+}
+
+resource "aws_lambda_event_source_mapping" "example" {
+  event_source_arn = "${aws_sqs_queue.fcm-analysis-EbsEncryptionByDefault.arn}"
+  function_name    = "${aws_lambda_function.fcm-analysis-EbsEncryptionByDefault.arn}"
+  batch_size = 1 # How many messages to process at a time
+}
+
+data "archive_file" "fcm-analysis-EbsEncryptionByDefault" {
+    type        = "zip"
+    source_dir  = "fcm-analysis-EbsEncryptionByDefault"
+    output_path = "fcm-analysis-EbsEncryptionByDefault.zip"
+}

+ 7 - 3
sample/sns.tf → sample/sns.master-account.tf

@@ -11,8 +11,10 @@ resource "aws_sns_topic" "fcm-input-DisableEbsEncryptionByDefault" {
 
 data "aws_iam_policy_document" "fcm-input-DisableEbsEncryptionByDefault" {
   statement {
+    sid = "Allow CloudWatch Events to Publish to SNS"
+    actions = ["sns:Publish"]
+
     effect  = "Allow"
-    actions = ["SNS:Publish"]
 
     principals {
       type        = "Service"
@@ -43,8 +45,9 @@ resource "aws_sns_topic" "fcm-input-EnableEbsEncryptionByDefault" {
 
 data "aws_iam_policy_document" "fcm-input-EnableEbsEncryptionByDefault" {
   statement {
+    sid = "Allow CloudWatch Events to Publish to SNS"
     effect  = "Allow"
-    actions = ["SNS:Publish"]
+    actions = ["sns:Publish"]
 
     principals {
       type        = "Service"
@@ -75,8 +78,9 @@ resource "aws_sns_topic" "fcm-custom-EbsEncryptionByDefault" {
 
 data "aws_iam_policy_document" "fcm-custom-EbsEncryptionByDefault" {
   statement {
+    sid = "Allow CloudWatch Events to Publish to SNS"
     effect  = "Allow"
-    actions = ["SNS:Publish"]
+    actions = ["sns:Publish"]
 
     principals {
       type        = "Service"

+ 1 - 1
sample/sqs.tf

@@ -1,6 +1,6 @@
 resource "aws_sqs_queue" "fcm-analysis-EbsEncryptionByDefault-deadletter" {
   name                      = "fcm-analysis-EbsEncryptionByDefault-deadletter"
-  visibility_timeout_seconds = 900 # How long before the item can be retried if something went wrong, should match processing time
+  visibility_timeout_seconds = 5400 # How long before the item can be retried if something went wrong, should match processing time. Should be at least 6 times the lambda timeout
   delay_seconds             = 0 # Delay before message is delivered. This can be increased if resources take longer to be active.
   max_message_size          = 262144 # How big messages can get. 256KB is the max for SNS and SQS
   message_retention_seconds = 1209600 # Better handle it with 14 days!