Terraform:如何在单个资源块中提供多个 lambda 函数 zip 文件
Posted
技术标签:
【中文标题】Terraform:如何在单个资源块中提供多个 lambda 函数 zip 文件【英文标题】:Terraform : how to provide multiple lambda fucntion zip files in a single resource block 【发布时间】:2021-12-09 14:09:03 【问题描述】:为 1 个 lambda 函数工作的 sn-p。 Terraform 版本 0.14.9。
resource "aws_lambda_function" "main"
function_name = var.lambda_name
role = aws_iam_role.lambda.arn
handler = "index.handler"
runtime = "nodejs12.x"
filename = "testlambda1.zip"
variable "lambda_name"
default = "testlambda1"
我是 terraform 的新手。我总共有 4 个 zip 格式的 lambda 函数。如何在 1 个资源块中提供所有这些。
resource "aws_lambda_function" "main"
function_name = var.lambda_name
role = aws_iam_role.lambda.arn
handler = "index.handler"
runtime = "nodejs12.x"
filename = var.filename
variable "lambda_name"
type = list(string)
default = [
"testlambda1",
"testlambda2",
"testlambda3",
"testlambda4"
]
variable "filename"
type = list(string)
default = [
"testlambda1.zip",
"testlambda2.zip",
"testlambda3.zip",
"testlambda4.zip"
]
我尝试了这个,但最终出现了错误。
Error: Incorrect attribute value type
on main-lambda.tf line 6, in resource "aws_lambda_function" "main":
6: function_name = var.lambda_name
Inappropriate value for attribute "function_name": string required.
Error: Incorrect attribute value type
on main-lambda.tf line 10, in resource "aws_lambda_function" "main":
10: filename = var.filename
Inappropriate value for attribute "filename": string required.
【问题讨论】:
我不知道这是否是您基础设施的“要求”,但对我来说看起来不太好。你检查过官方的 lambda 模块吗? registry.terraform.io/modules/terraform-aws-modules/lambda/aws/… -- 或许能帮到你。 【参考方案1】:如果您希望单个资源块创建多个资源,您需要使用 Terraform for_each 或 count 元参数。
例如:
resource "aws_lambda_function" "main"
count = length(var.lambda_name)
function_name = var.lambda_name[count.index]
role = aws_iam_role.lambda.arn
handler = "index.handler"
runtime = "nodejs12.x"
filename = var.filename[count.index]
variable "lambda_name"
type = list(string)
default = [
"testlambda1",
"testlambda2",
"testlambda3",
"testlambda4"
]
variable "filename"
type = list(string)
default = [
"testlambda1.zip",
"testlambda2.zip",
"testlambda3.zip",
"testlambda4.zip"
]
或将您的变量转换为地图,并使用for_each
:
resource "aws_lambda_function" "main"
for_each = var.lambdas
function_name = each.key
role = aws_iam_role.lambda.arn
handler = "index.handler"
runtime = "nodejs12.x"
filename = each.value
variable "lambdas"
type = map(string)
default =
"testlambda1" = "testlambda1.zip",
"testlambda2" = "testlambda2.zip",
"testlambda3" = "testlambda3.zip",
"testlambda4" = "testlambda4.zip"
【讨论】:
以上是关于Terraform:如何在单个资源块中提供多个 lambda 函数 zip 文件的主要内容,如果未能解决你的问题,请参考以下文章
Terraform:如何安装多个版本的提供程序插件? [复制]