title: The "for_each" value depends on resource attributes that cannot be determined (Terraform)
body: <p>I have a terraform configuration which needs to:</p>
  <ol>
  <li>Create a lambda</li>
  <li>Invoke the lambda</li>
  <li>Iterate on the lambda's json result which returns an array and create a CloudWatch event rule per entry in the array</li>
  </ol>
  <p>The relevant code looks like:</p>
  <pre><code>Create lambda code...
  
  data &quot;aws_lambda_invocation&quot; &quot;run_lambda&quot; {
    function_name = &quot;${aws_lambda_function.deployed_lambda.function_name}&quot;
  
    input = &lt;&lt;JSON
    {}
    JSON
    depends_on = [aws_lambda_function.deployed_lambda]
  }
  
  resource &quot;aws_cloudwatch_event_rule&quot; &quot;aws_my_cloudwatch_rule&quot; {
    for_each = {for record in jsondecode(data.aws_lambda_invocation.run_lambda.result).entities : record.entityName =&gt; record} 
      name = &quot;${each.value.entityName}-event&quot;
      description = &quot;Cloudwatch rule for ${each.value.entityName}&quot;
      schedule_expression = &quot;cron(${each.value.cronExpression})&quot;
  }
  </code></pre>
  <p>The problem is that when I run it, I get:</p>
  <pre><code>Error: Invalid for_each argument
  
    on lambda.tf line 131, in resource &quot;aws_cloudwatch_event_rule&quot; &quot;aws_my_cloudwatch_rule&quot;:
   131:   for_each = {for record in jsondecode(data.aws_lambda_invocation.aws_lambda_invocation.result).entities : record.entityName =&gt; record}
  
  The &quot;for_each&quot; 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.
  </code></pre>
  <p>I've read a bunch of posts on the problem but couldn't find a workaround.<br />
  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.<br />
  What is the best approach to solving such a task?<br />
  Since it is run as part of a CI/CD pipeline I prefer a solution that doesn't include the &quot;-target&quot; flag.</p>