基于swagger文件使用terraform部署API网关

xggvc2p6  于 2023-10-18  发布在  其他
关注(0)|答案(1)|浏览(106)

我想用terraform部署我的API网关,使用swagger文件来描述我的API。swagger.yaml看起来像这样:

swagger: '2.0'
info:
  version: '1.0'
  title: "CodingTips"
schemes:
  - https
paths:
  "/api":
    get:
      description: "Get coding tips"
      produces:
        - application/json
      x-amazon-apigateway-integration: ${apiIntegration}
      responses:
        '200':
          description: "Codingtips were successfully requested"

Terraform给了我一个BadRequestExceptionThe REST API doesn't contain any methods
因此,我认为它正在尝试部署REST API,而不等待创建该API的方法和集成。
这让我想到了必须将DEPENDS_ON添加到aws_api_gateway_deployment的方向。然而,我不知道依赖于什么,因为我没有使用swagger定义方法和集成资源。它们应该自动从 Swagger 的定义中扣除。
我的想法是否正确?如果是,我必须让我的aws_api_gateway_deployment依赖于什么?还是我尝试部署这个API的方式有其他问题。
我的apigateway.tf文件看起来像这样:

resource "aws_api_gateway_rest_api" "codingtips-api-gateway" {
  name        = "ServerlessExample"
  description = "Terraform Serverless Application Example"
  body        = "${data.template_file.codingtips_api_swagger.rendered}"
}

locals{
  "get_codingtips_arn" = "${aws_lambda_function.get-tips-lambda.invoke_arn}"

  "x-amazon-coding-tips-apigateway-integration" = <<EOF
#
uri = "${local.get_codingtips_arn}"
passthroughBehavior: when_no_match
httpMethod: POST
type: aws_proxy
credentials: "${aws_iam_role.api_gateway_role.arn}"
EOF
}

data "template_file" codingtips_api_swagger{
  template = "${file("./swagger.yaml")}"

  vars {
    apiIntegration = "${indent(8, local.x-amazon-coding-tips-apigateway-integration)}"
  }
}

resource "aws_api_gateway_deployment" "codingtips-api-gateway-deployment" {
  rest_api_id = "${aws_api_gateway_rest_api.codingtips-api-gateway.id}"
  stage_name  = "test"
}

如何修复BadRequestException: The REST API doesn't contain any methods

wz3gfoph

wz3gfoph1#

我发现了问题所在。这是locals{}块中的语法错误。uri =应该是uri:。使用冒号而不是等号。然后块看起来像这样:

locals{
  "get_codingtips_arn" = "${aws_lambda_function.get-tips-lambda.invoke_arn}"

  "x-amazon-codingtips-get-apigateway-integration" = <<EOF
# comment for new line
uri: "${aws_lambda_function.get-tips-lambda.invoke_arn}"
passthroughBehavior: when_no_match
httpMethod: POST
type: aws_proxy
EOF
}

通过研究,我发现当你在swagger.yaml中指定x-amazon-apigateway-integration时,读起来更容易:

swagger: '2.0'
info:
  version: '1.0'
  title: "CodingTips"
schemes:
  - https
paths:
  "/api":
    get:
      description: "Get coding tips"
      produces:
        - application/json
      responses:
        '200':
          description: "The codingtips request was successful."
      x-amazon-apigateway-integration:
        uri: ${uri_arn}
        passthroughBehavior: "when_no_match"
        httpMethod: "POST"
        type: "aws_proxy"

terraform中的data{}locals{}块看起来像:

data "template_file" codingtips_api_swagger{
  template = "${file("swagger.yaml")}"

  vars {
    uri_arn = "${local.get_codingtips_arn}"
  }
}

locals {
  "get_codingtips_arn" = "${aws_lambda_function.get-tips-lambda.invoke_arn}"
}

相关问题