You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Terraform创建AWS API Gateway Model时遇无效架构错误求助

排查Terraform创建AWS API Gateway Model时的"Invalid model schema specified"错误

我是Terraform新手,正尝试通过Terraform创建AWS API Gateway。其中aws_api_gateway_model资源的schema引用本地JSON文件,该JSON在AWS控制台配置可正常工作,但执行Terraform时出现错误:Invalid model schema specified,请求帮忙排查问题。

我的代码

Terraform配置

resource "aws_api_gateway_rest_api" "demo_services_apig" {
  name = "demo-services-apigateway-${var.environment}"
  description = "Demo service APIs to handle Snow events and User Authentication"
  api_key_source = "HEADER"
  endpoint_configuration {
    types = ["REGIONAL"]
  }
}

resource "aws_api_gateway_model" "demo_services_apig_model" {
  rest_api_id = aws_api_gateway_rest_api.demo_services_apig.id
  name = "UserOauthAPIResponseModel"
  description = "a JSON schema"
  content_type = "application/json"

  schema = jsonencode({
    type = "${file("api_gateway/json_files/oauth_response.json")}"
  })
}

本地JSON文件内容(oauth_response.json)

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "title": "UserOAuthUserConfig",
    "type": "object",
    "properties": {
        "Role": {
            "type": "string"
        },
        "Policy": {
            "type": "string"
        },
        "HomeDirectory": {
            "type": "string"
        },
        "PublicKeys": {
            "type": "array",
            "items": {
                "type": "string"
            }
        }
    }
}

错误信息

│ Error: creating API Gateway Model (UserOauthAPIResponseModel): BadRequestException: Invalid model specified: Validation Result: warnings : [], errors : [Invalid model schema specified]
│ 
│   with module.api_gateway.aws_api_gateway_model.demo_services_apig_model,
│   on api_gateway/main.tf line 15, in resource "aws_api_gateway_model" "demo_services_apig_model":
│   15: resource "aws_api_gateway_model" "demo_services_apig_model" {

问题原因及解决方案

问题根源

你的代码在处理schema参数时犯了关键错误:

  • 你通过jsonencode({ type = file(...) })将本地JSON文件的内容作为type字段的值,再转成JSON字符串。这会导致最终提交给AWS的Schema结构变成一个嵌套对象,其type字段的值是原始JSON的字符串转义版本,完全不符合API Gateway Model要求的JSON Schema格式。
  • AWS API Gateway Model需要的是完整的JSON Schema对象作为schema的值,而不是这种嵌套结构。

修正后的代码

直接将本地JSON文件的内容赋值给schema即可,因为file()函数会直接读取文件的文本内容(合法的JSON字符串),正好符合schema参数的要求:

resource "aws_api_gateway_model" "demo_services_apig_model" {
  rest_api_id = aws_api_gateway_rest_api.demo_services_apig.id
  name = "UserOauthAPIResponseModel"
  description = "a JSON schema"
  content_type = "application/json"

  schema = file("api_gateway/json_files/oauth_response.json")
}

可选验证方案

如果担心本地JSON文件格式不合法,可以先通过jsondecode解析成对象,再用jsonencode转回字符串,确保格式正确:

schema = jsonencode(jsondecode(file("api_gateway/json_files/oauth_response.json")))

这样修改后,提交给AWS的Schema就和你在控制台配置的完全一致,就能正常创建Model了。

内容的提问来源于stack exchange,提问作者snowcoder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 11:55:30