social-network
social-network/data-generator.tf
1
# Lambda function
2
3
data "archive_file" "lambda_zip" {
4
  type        = "zip"
5
  output_path = "/tmp/${random_id.id.hex}-lambda.zip"
6
  source_file = "data-generator.mjs"
7
}
8
9
resource "aws_lambda_function" "lambda" {
10
  function_name = "social-network-data-generator-${random_id.id.hex}"
11
12
  filename         = data.archive_file.lambda_zip.output_path
13
  source_code_hash = data.archive_file.lambda_zip.output_base64sha256
14
15
  handler = "data-generator.handler"
16
  runtime = "nodejs18.x"
17
  role    = aws_iam_role.lambda_exec.arn
18
  timeout = 60
19
  environment {
20
    variables = {
21
      APIURL    = aws_appsync_graphql_api.appsync.uris["GRAPHQL"]
22
      APIREGION = data.aws_region.current.name
23
      USERIDS   = jsonencode(slice(aws_cognito_user.user.*.sub, 1, length(aws_cognito_user.user.*)))
24
    }
25
  }
26
}
27
28
data "aws_iam_policy_document" "lambda_exec_role_policy" {
29
  statement {
30
    actions = [
31
      "logs:CreateLogStream",
32
      "logs:PutLogEvents"
33
    ]
34
    resources = [
35
      "arn:aws:logs:*:*:*"
36
    ]
37
  }
38
  statement {
39
    actions = [
40
      "appsync:GraphQL",
41
    ]
42
    resources = [
43
      "${aws_appsync_graphql_api.appsync.arn}/*",
44
    ]
45
  }
46
}
47
48
resource "aws_cloudwatch_log_group" "loggroup_lambda" {
49
  name              = "/aws/lambda/${aws_lambda_function.lambda.function_name}"
50
  retention_in_days = 14
51
}
52
53
resource "aws_iam_role_policy" "lambda_exec_role" {
54
  role   = aws_iam_role.lambda_exec.id
55
  policy = data.aws_iam_policy_document.lambda_exec_role_policy.json
56
}
57
58
resource "aws_iam_role" "lambda_exec" {
59
  assume_role_policy = <<EOF
60
{
61
  "Version": "2012-10-17",
62
  "Statement": [
63
	{
64
	  "Action": "sts:AssumeRole",
65
	  "Principal": {
66
		"Service": "lambda.amazonaws.com"
67
	  },
68
	  "Effect": "Allow"
69
	}
70
  ]
71
}
72
EOF
73
}
74
75
# scheduler
76
77
resource "aws_cloudwatch_event_rule" "scheduler" {
78
  schedule_expression = "rate(1 minute)"
79
}
80
81
resource "aws_cloudwatch_event_target" "lambda" {
82
  rule = aws_cloudwatch_event_rule.scheduler.name
83
  arn  = aws_lambda_function.lambda.arn
84
}
85
86
resource "aws_lambda_permission" "scheduler" {
87
  action        = "lambda:InvokeFunction"
88
  function_name = aws_lambda_function.lambda.arn
89
  principal     = "events.amazonaws.com"
90
91
  source_arn = aws_cloudwatch_event_rule.scheduler.arn
92
}
93
94