I have a terraform configuration which needs to:
- Create a lambda
- Invoke the lambda
- Iterate on the lambda's json result which returns an array and create a CloudWatch event rule per entry in the array
The relevant code looks like:
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})"
}
The problem is that when I run it, I get:
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.
I've read a bunch of posts on the problem but couldn't find a workaround.
The problem is that Terraform needs to know the size of the array returned by the lambda in the planning phase before the lambda was created.
What is the best approach to solving such a task?
Since it is run as part of a CI/CD pipeline I prefer a solution that doesn't include the "-target" flag.