我想将几十个AWS Lambda函数添加到我的Terraform项目中。每个人都有相同的基本形状:
data "archive_file" "foo" {
type = "zip"
output_path = "./build/foo.zip"
source {
content = "build/foo.js"
filename = "index.js"
}
}
resource "aws_lambda_function" "foo" {
description = "Description of Foo"
filename = "./build/foo.zip"
function_name = "foo"
handler = "index.handler"
memory_size = "128"
publish = true
role = "${aws_iam_role.Lambda.arn}"
runtime = "nodejs10.x"
source_code_hash = "${sha256(filebase64("./build/foo.zip"))}"
timeout = "3"
vpc_config {
security_group_ids = []
subnet_ids = []
}
}
除了function_name
,output_path
,filename
和source_code_hash
以外,它们都是相同的。
如何减少重复?
我创建了一个modules/lambda-function/{main,variables}.tf
,然后使用来调用它
module "lambda-function" {
source = "./modules/lambda-function"
name = "foo"
}
module "lambda-function" {
source = "./modules/lambda-function"
name = "bar"
}
但是当我运行terraform plan
时,我得到了
一个列表已经在aws-lambda.tf:1,1-16定义了名为“ lambda”的模块调用。模块调用在模块内必须具有唯一的名称。
我创建了一个Lambda定义对象列表,并尝试对其进行迭代:
# lambda-functions/variables.tf
variable "lambdas" {
type = list(object({
name = string
description = string
}))
description = "The AWS lambda functions as {name,description} objects."
}
# lambda-functions/main.tf
data "archive_file" "this" {
count = "${length(var.lambdas)}"
type = "zip"
output_path = "./build/${var.lambdas[count.index].name}.zip"
source {
content = "build/${var.name}.js"
filename = "index.js"
}
}
但是"./build/${var.lambdas[count.index].name}.zip"
不是有效的Terraform语法。