403 when using Terraform to attach Lambda Function to Target Group w/ ALB
I'm able to create Instances, Target Groups, and ALBs just fine with Terraform, but am getting stuck when trying to use Lambda Functions. It looks like the Lambda function gets created OK along with an ALB and a Target Group, but fails on the step when attaching the Lambda function to the target group.
resource "aws_lambda_function" "LAMBDA_FUNCTION" {
filename = "../my_function.zip"
function_name = "my_function"
role = aws_iam_role.LAMBDA_ROLE.arn
handler = "my_function.lambda_handler"
runtime = "python3.8"
memory_size = 128
description = "My Lambda Function"
}
resource "aws_lb_target_group" "LB_TG" {
name = "${local.env}-tg"
target_type = "lambda"
lambda_multi_value_headers_enabled = false
}
resource "aws_lb_target_group_attachment" "TG_ATTACHMENT" {
target_group_arn = aws_lb_target_group.LB_TG.arn
target_id = aws_lambda_function.LAMBDA_FUNCTION.arn
}
Error message when running terraform apply:
Error: Error registering targets with target group: AccessDenied: elasticloadbalancing principal does not have permission to invoke arn:aws:lambda:us-west-1:694058713236:function:my_function from target group arn:aws:elasticloadbalancing:us-west-1:694058713236:targetgroup/test-tg/9da892faefbe02b7
status code: 403, request id: d13c36ed-2513-4d4c-97d0-2e449be859a1
From what I can gather, I'm missing a step where I specifically give permission to either the Target Group or the Lambda function to associate with one another.
Solution 1:
There are two additional resources needed for this to work:
- aws_lambda_alias
- aws_lambda_permission
Much thanks to this blog post