Reputation: 61
I'm brand new to Terraform and AWS, and after looking for a long time online I still can't make sense of how this is doable. I would really appreciate the help.
data "archive_file" "archive" {
type = "zip"
source_file = "${reference to any lambda which requires it}"
output_path = "${specified output_path somehow dictated by the lambda?}"
}
resource "aws_lambda_function" "hello_world" {
function_name = "HelloWorld"
s3_bucket = aws_s3_bucket.lambda_bucket.id
s3_key = aws_s3_object.lambda_hello_world.key
runtime = "nodejs12.x"
handler = "hello.handler"
source_code_hash = data.archive_file.lambda_hello_world.output_base64sha256
(this will somehow let archive_file know what the source_file and output_path are)
role = aws_iam_role.lambda_exec.arn
}
Would it be possible for me to achieve something like this? It would mean I'd only have to write the block for archive_file
one time but have it change its variables per lambda.
Upvotes: 0
Views: 184
Reputation: 238407
You can do it through for_each
. For that,your files would have to be in a map, e.g.:
variable "files" {
default = {
"function1" = {
source_file = "..."
output_path = "..."
},
"function2" = {
source_file = "..."
output_path = "..."
}
}
}
data "archive_file" "archive" {
for_each = var.files
type = "zip"
source_file = each.value.source_file
output_path = each.value.output_path
}
then you have only one function code:
resource "aws_lambda_function" "hello_world" {
for_each = var.files
function_name = "HelloWorld" # name also must be unique
s3_bucket = aws_s3_bucket.lambda_bucket.id
s3_key = aws_s3_object.lambda_hello_world.key
runtime = "nodejs12.x"
handler = "hello.handler"
source_code_hash = data.archive_file.lambda_hello_world[each.key].output_base64sha256
role = aws_iam_role.lambda_exec.arn
}
Upvotes: 2