Search code examples
amazon-web-servicesterraformterraform-provider-aws

How to create api gateway resource with path parameter in terraform?


I want to create an api gateway rest resource in terraform of the following pattern:

/v1/foo/{foo}

However when I try to run the following terraform I get this error.

│ Error: creating API Gateway Resource: BadRequestException: Resource's path part only allow a-zA-Z0-9._-: or a valid greedy path variable and curly braces at the beginning and the end.

data "aws_lambda_function" "function" {
  function_name = module.configuration_lambda.function_name
}
        
data "aws_api_gateway_rest_api" "api" {
  name = var.api_name
}
        
data "aws_api_gateway_resource" "parent" {
   path        = "/v1"
   rest_api_id = data.aws_api_gateway_rest_api.api.id
}
        
resource "aws_lambda_permission" "lambda_invocation" {
   action        = "lambda:InvokeFunction"
   function_name = data.aws_lambda_function.function.function_name
   principal     = "apigateway.amazonaws.com"
        
   source_arn = "${data.aws_api_gateway_rest_api.api.execution_arn}/*"
}
       
resource "aws_api_gateway_resource" "current" {
  parent_id   = data.aws_api_gateway_resource.parent.id
  path_part   = "/foo/{foo}"
  rest_api_id = data.aws_api_gateway_rest_api.api.id
}
        
resource "aws_api_gateway_integration" "lambda" {
  http_method = "GET"
  resource_id = aws_api_gateway_resource.current.id
  rest_api_id = data.aws_api_gateway_rest_api.api.id
  integration_http_method = "POST"
  type        = "AWS_PROXY"
        
  uri = data.aws_lambda_function.function.invoke_arn
}
        
resource "aws_api_gateway_method" "method" {
  authorization = "NONE"
  http_method   = "GET"
  resource_id   = aws_api_gateway_resource.current.id
  rest_api_id   = data.aws_api_gateway_rest_api.api.id
}

Any ideas what I might be doing wrong ?


Solution

  • I think you need this:

    resource "aws_api_gateway_resource" "current" {
      parent_id   = data.aws_api_gateway_resource.parent.id
      path_part   = "foo"
      rest_api_id = data.aws_api_gateway_rest_api.api.id
    }
    
    resource "aws_api_gateway_resource" "current_foo" {
      parent_id   = aws_api_gateway_resource.current.id
      path_part   = "{foo}"
      rest_api_id = data.aws_api_gateway_rest_api.api.id
    }