Home > Software engineering >  How to use 'depends_on' with 'for_each' in terraform?
How to use 'depends_on' with 'for_each' in terraform?

Time:12-20

I've got a terraform plan that creates a number of resources in a for_each loop, and I need another resource to depend_on those first ones. How can I do it without having to explicitly list them?

Here's the first resource (AWS API Gateway resource):

locals {
  apps = toset(["app1", "app2", "app3"])
}

resource "aws_api_gateway_integration" "lambda" {
  for_each                = local.apps 
  rest_api_id             = aws_api_gateway_rest_api.primary.id
  resource_id             = aws_api_gateway_resource.lambda[each.key].id
  http_method             = aws_api_gateway_method.lambda_post[each.key].http_method
  integration_http_method = "POST"
  type                    = "AWS_PROXY"
  uri                     = aws_lambda_function.lambda[each.key].invoke_arn
}

Now I need to wait for all the 3 apps integrations before creating an API Gateway deployment:

resource "aws_api_gateway_deployment" "primary" {
  rest_api_id = aws_api_gateway_rest_api.primary.id

  depends_on = [
    aws_api_gateway_integration.lambda["app1"],
    aws_api_gateway_integration.lambda["app2"],
    aws_api_gateway_integration.lambda["app3"],
  ]

However the list of apps keeps growing and I don't want to maintain it manually over here. Everywhere else I can simply use for or for_each together with local.apps but I can't figure out how to dynamically build the list for depends_on? Any ideas?

CodePudding user response:

You have to do it manually. enter image description here

  • At the end you can put depends_on on a module - depends_on = [ module.logic_app ]

    • Related