使用Terraform创建API Gateway Documentation Part时JSON格式错误求助
解决Terraform创建API Gateway Documentation Part时的JSON格式错误问题
问题原因
你遇到的BadRequestException: Documentation part properties must be a valid JSON错误,核心是传递给properties参数的内容不符合API Gateway要求的有效JSON字符串格式——要么多了冗余的外层引号,要么传递的是文件路径而非文件内容。
针对你三种尝试的修正方案
1. 直接为变量赋值(修正方式1)
原写法多了外层双引号,导致传递的是包裹JSON的字符串而非纯JSON结构。正确写法去掉外层引号,用heredoc直接定义:
variable "cors_properties" { default = <<EOF {"summary" : "CORS support"} EOF }
或者用转义双引号的字符串形式:
variable "cors_properties" { default = "{\"summary\": \"CORS support\"}" }
2. 从JSON文件读取(修正方式2)
不能直接传入文件路径,需要用Terraform的file()函数读取文件内容,确保文件本身是标准JSON:
resource "aws_api_gateway_documentation_part" "cors_docs" { rest_api_id = aws_api_gateway_rest_api.example.id location { type = "METHOD" method = "OPTIONS" path = "/example" } properties = file("${path.module}/xyz.json") }
对应的xyz.json内容保持你原来的标准JSON即可:
{ "summary": "CORS support" }
3. 字符串变量传入(修正方式3)
确保变量值是无外层引号的合法JSON字符串,示例:
variable "cors_properties" { type = string default = "{\"summary\": \"CORS support\"}" } resource "aws_api_gateway_documentation_part" "cors_docs" { rest_api_id = aws_api_gateway_rest_api.example.id location { type = "METHOD" method = "OPTIONS" path = "/example" } properties = var.cors_properties }
关键注意点
API Gateway的Documentation Part要求properties是可直接解析为JSON对象的字符串,不能包含外层冗余引号,也不能传递文件路径、未转义的无效字符串等非JSON内容。
内容的提问来源于stack exchange,提问作者Shafeeq
相关产品推荐
相关产品推荐

