cdh-terraform/modules/lambda/main.tf

97 lines
3.1 KiB
HCL

resource "null_resource" "pip_install" {
triggers = {
# shell_hash = "${sha256(file("${path.module}/${var.path_to_function}/src/requirements.txt"))}"
always_run = timestamp()
}
provisioner "local-exec" {
command = "bash ${path.module}/${var.path_to_function}/create_pkg.sh"
environment = {
function_name = module.lambda_label.id
runtime = var.runtime
path_cwd = "${path.module}/${var.path_to_function}"
}
}
}
data "archive_file" "layer" {
type = "zip"
source_dir = "${path.module}/${var.path_to_function}/layer"
output_path = "${path.module}/${var.path_to_function}/layer.zip"
depends_on = [null_resource.pip_install]
}
resource "aws_lambda_layer_version" "layer" {
layer_name = "dependencies"
filename = data.archive_file.layer.output_path
source_code_hash = data.archive_file.layer.output_base64sha256
compatible_runtimes = ["python3.9"]
}
data "archive_file" "code" {
type = "zip"
source_dir = "${path.module}/${var.path_to_function}/src"
output_path = "${path.module}/${var.path_to_function}/lambda.zip"
}
resource "aws_lambda_function" "this" {
filename = data.archive_file.code.output_path
function_name = module.lambda_label.id
description = var.description
role = aws_iam_role.this.arn
handler = var.handler
source_code_hash = data.archive_file.code.output_base64sha256
runtime = var.runtime
memory_size = var.memory
timeout = var.timeout
reserved_concurrent_executions = var.reserved_concurrent_executions
tags = module.lambda_label.tags
layers = [aws_lambda_layer_version.layer.arn, "arn:aws:lambda:eu-west-1:336392948345:layer:AWSSDKPandas-Python39:7"]
tracing_config {
mode = "PassThrough"
}
environment {
variables = var.environment_vars
}
}
resource "aws_cloudwatch_event_rule" "this" {
for_each = var.cron
name = "${module.lambda_label.id}_${each.key}"
description = each.value.description
schedule_expression = each.value.schedule
}
resource "aws_cloudwatch_event_target" "this" {
for_each = var.cron
rule = aws_cloudwatch_event_rule.this[each.key].name
target_id = module.lambda_label.id
arn = aws_lambda_function.this.arn
input = each.value.payload
}
resource "aws_lambda_permission" "this" {
for_each = var.cron
statement_id = "AllowExecutionFromCloudWatch${each.key}"
action = "lambda:InvokeFunction"
function_name = aws_lambda_function.this.function_name
principal = "events.amazonaws.com"
source_arn = aws_cloudwatch_event_rule.this[each.key].arn
}
#resource "aws_s3_bucket_notification" "this" {
# for_each = var.s3Trigger
# bucket = each.value.bucket
# lambda_function {
# lambda_function_arn = aws_lambda_function.this.arn
# events = ["s3:ObjectCreated:*"]
# }
#}
resource "aws_sns_topic_subscription" "invoke_with_sns" {
for_each = var.snsTrigger
topic_arn = each.value.topic
protocol = "lambda"
endpoint = aws_lambda_function.this.arn
}