How do I resolve the error: "Argument names must not be quoted" in Terraform?

How do I resolve the error: "Argument names must not be quoted" in Terraform?

我在本地运行 Terraform 0.12.24

我正在尝试部署 API 网关与 Lambda 的集成

我正在尝试使用 Terraform 启用 AWS API GW CORS。

我有以下 OPTIONS 方法响应资源:

resource "aws_api_gateway_method_response" "options_200" {
    rest_api_id   = aws_api_gateway_rest_api.scout-approve-api-gateway.id
    resource_id   = aws_api_gateway_resource.proxy.id
    http_method   = aws_api_gateway_method.options_method.http_method
    status_code   = "200"

    response_models {
      "application/json" = "Empty"
    }

    response_parameters {
        "method.response.header.Access-Control-Allow-Headers" = true,
        "method.response.header.Access-Control-Allow-Methods" = true,
        "method.response.header.Access-Control-Allow-Origin" = true
    }
    depends_on = [aws_api_gateway_method.options_method]
}

我得到:

Error: Invalid argument name

  on main.tf line 48, in resource "aws_api_gateway_method_response" "options_200":
  48:       "application/json" = "Empty"

Argument names must not be quoted.

什么给了?

这其实是解析器误会了错误所在。它实际上是在抱怨它试图将 response_modelsresponse_parameters 作为块而不是属性来读取。在 0.12 documentation.

中对此有进一步的讨论

The main difference between a map attribute and a nested block is that a map attribute will usually have user-defined keys, like we see in the tags example above, while a nested block always has a fixed set of supported arguments defined by the resource type schema, which Terraform will validate.

在 0.11 中,您可以互换使用块语法(只是大括号,例如 response_parameters { ... })用于属性,但在 0.12 中,它对类型更加严格,因此这不再可能。 The code in the Medium post you linked to as a working example is 0.11 code and isn't valid in 0.12. If you look closely at the GitHub code you also linked 你可以看到它使用属性语法而不是块语法,所以是有效的。

通过添加 = 切换到使用属性语法将使这项工作按预期进行:

resource "aws_api_gateway_method_response" "options_200" {
  rest_api_id = aws_api_gateway_rest_api.scout-approve-api-gateway.id
  resource_id = aws_api_gateway_resource.proxy.id
  http_method = aws_api_gateway_method.options_method.http_method
  status_code = "200"

  response_models = {
    "application/json" = "Empty"
  }

  response_parameters = {
    "method.response.header.Access-Control-Allow-Headers" = true,
    "method.response.header.Access-Control-Allow-Methods" = true,
    "method.response.header.Access-Control-Allow-Origin"  = true
  }

  depends_on = [aws_api_gateway_method.options_method]
}