Search code examples
terraformaws-api-gateway

Value of a module reference in Terraform


I'm trying to get my api gateway deployment to redeploy when I'm making changes to it's endpoints. Each of those endpoints is defined within a module and so by following this documentation, I end up with something like the following:

resource "aws_api_gateway_deployment" "rest_api" {
  rest_api_id = aws_api_gateway_rest_api.rest_api.id
  
  triggers = {
    redeployment = sha1(jsonencode([
      module.api_endpoint[*],
      aws_api_gateway_integration.webapp,
      aws_api_gateway_integration_response.webapp_404,
      aws_api_gateway_integration.root_redirect
    ]))
  }

  lifecycle { create_before_destroy = true }
}

module api_endpoint {
  source = "./modules/api_endpoint"

  for_each = local.paths

  api_id = aws_api_gateway_rest_api.rest_api.id
  root_resource_id = aws_api_gateway_rest_api.rest_api.root_resource_id
  path = each.key
  methods = each.value

  authoriser_id = aws_api_gateway_authorizer.rest_api.id
  lambda_arn = aws_lambda_function.rest_api.invoke_arn
}

However when I add additional api_endpoints, it's not updating. Am I missing something about the value of module.api_endpoint[*]? I had assumed it would work like the resources below. Do I need to make it output something that would change accordingly?


Solution

  • As mentioned in the comments, the splat expression does not work when using for_each. Alternatively, the values built-in function could be used to fetch all the values for a certain output that the module provides. The other option would be to reference a single output for one of the keys. The code would look something like:

    resource "aws_api_gateway_deployment" "rest_api" {
      rest_api_id = aws_api_gateway_rest_api.rest_api.id
      
      triggers = {
        redeployment = sha1(jsonencode([
          values(module.api_endpoint)[*].<name_of_the_output>,
          aws_api_gateway_integration.webapp,
          aws_api_gateway_integration_response.webapp_404,
          aws_api_gateway_integration.root_redirect
        ]))
      }
    
      lifecycle { create_before_destroy = true }
    }
    

    where the <name_of_the_output> is a placeholder which should be replaced with a real output name defined in the module.