我有一个 terraform 配置,需要:
- 创建一个 lambda
- 调用 lambda
- 迭代 lambda 的 json 结果,返回一个数组并为数组中的每个条目创建一个 CloudWatch 事件规则
相关代码如下:
Create lambda code...
data "aws_lambda_invocation" "run_lambda" {
function_name = "${aws_lambda_function.deployed_lambda.function_name}"
input = <<JSON
{}
JSON
depends_on = [aws_lambda_function.deployed_lambda]
}
resource "aws_cloudwatch_event_rule" "aws_my_cloudwatch_rule" {
for_each = {for record in jsondecode(data.aws_lambda_invocation.run_lambda.result).entities : record.entityName => record}
name = "${each.value.entityName}-event"
description = "Cloudwatch rule for ${each.value.entityName}"
schedule_expression = "cron(${each.value.cronExpression})"
}
问题是当我运行它时,我得到:
Error: Invalid for_each argument
on lambda.tf line 131, in resource "aws_cloudwatch_event_rule" "aws_my_cloudwatch_rule":
131: for_each = {for record in jsondecode(data.aws_lambda_invocation.aws_lambda_invocation.result).entities : record.entityName => record}
The "for_each" value depends on resource attributes that cannot be determined
until apply, so Terraform cannot predict how many instances will be created.
To work around this, use the -target argument to first apply only the
resources that the for_each depends on.
我已经阅读了很多有关该问题的帖子,但找不到解决方法。
问题在于,Terraform 需要在创建 lambda 之前的规划阶段知道 lambda 返回的数组的大小。
解决此类任务的最佳方法是什么?
由于它作为 CI/CD 管道的一部分运行,我更喜欢不包含“-target”标志的解决方案。
一种可能性是重新考虑for_each并使用count相反,如果合适的话。for_each有一些主要的限制。我遇到了类似的事情(对我来说似乎是一个主要错误,但他们说这是一个功能)
假设我正在部署三个虚拟机,并希望将它们绑定到负载均衡器:
resource "aws_instance" "xxx-IIS-004" {
ami = var.ami["Windows Server 2019"]
instance_type = var.depoy_lowcost ? var.default_instance_type : "m5.2xlarge"
count = "3"
...
当我尝试使用时for_each, I get “for_each”值取决于无法确定的资源属性...或元组错误。
Fails:
resource "aws_elb_attachment" "attachments_004" {
depends_on = [ aws_instance.xxx-IIS-004 ]
elb = data.aws_elb.loadBalancer.id
for_each = aws_instance.xxx-IIS-004[*]
instance = each.value.id
}
Works*
locals {
att_004 = join("_", aws_instance.xxx-IIS-004[*].id )
}
resource "aws_elb_attachment" "attachments_004" {
depends_on = [ aws_instance.xxx-IIS-004 ]
elb = data.aws_elb.loadBalancer.id
count = length( aws_instance.xxx-IIS-004 )
instance = split("_", local.att_004)[count.index]
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)