gpt4 book ai didi

terraform - "for_each"值取决于无法确定的资源属性(Terraform)

转载 作者:行者123 更新时间:2023-12-03 23:26:36 26 4
gpt4 key购买 nike

我有一个 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 并使用 计数 相反,如果合适的话。 for_each 有一些主要的限制。我遇到了类似的事情(对我来说似乎是一个主要错误,但他们说这是一个功能)
    考虑我正在部署三个虚拟机,并希望将它们绑定(bind)到负载均衡器:

    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 ,我得到“for_each”值取决于无法确定的资源属性...或元组错误。
    失败:
    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
    }
    作品 *
    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]
    }

    关于terraform - "for_each"值取决于无法确定的资源属性(Terraform),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63768921/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com