前一篇,我們成功建立了 Lambda 函數,接下來要再建立一組 API 閘道 (Gateway),並且把兩邊串接一起。
首先建立 gateway.tf
檔案,我們開始設定需要的資源。
建立 API 閘道需要多個資源組合:
aws_api_gateway_rest_api
建立 API 閘道物件aws_api_gateway_resource
建立 API 閘道資源,設定路徑為 hello
aws_api_gateway_method
建立 API 閘道資源的方法,設定方法為 GET
aws_api_gateway_integration
整合 API 閘道跟 Lambda 函數
integration_http_method
設定成 POST
type
設定成 AWS_PROXY
uri
填入 Lambda 函數的 invoke arn設定好 API 閘道需要再經過一個「部署」的步驟啟動 API
aws_api_gateway_deployment
部署 API 閘道,要設定 depends_on
確保 aws_api_gateway_integration
完成之後才能部署 APIaws_lambda_permission
允許 API 閘道使用 Lambda 函數完整內容如下:
resource "aws_api_gateway_rest_api" "hello" {
name = "hello"
description = "Serverless hello world"
}
resource "aws_api_gateway_resource" "hello" {
path_part = "hello"
parent_id = aws_api_gateway_rest_api.hello.root_resource_id
rest_api_id = aws_api_gateway_rest_api.hello.id
}
resource "aws_api_gateway_method" "hello" {
rest_api_id = aws_api_gateway_rest_api.hello.id
resource_id = aws_api_gateway_resource.hello.id
http_method = "GET"
authorization = "NONE"
}
resource "aws_api_gateway_integration" "hello" {
rest_api_id = aws_api_gateway_rest_api.hello.id
resource_id = aws_api_gateway_resource.hello.id
http_method = aws_api_gateway_method.hello.http_method
integration_http_method = "POST"
type = "AWS_PROXY"
uri = aws_lambda_function.hello.invoke_arn
}
resource "aws_api_gateway_deployment" "hello_v1" {
depends_on = [
aws_api_gateway_integration.hello
]
rest_api_id = aws_api_gateway_rest_api.hello.id
stage_name = "v1"
}
resource "aws_lambda_permission" "hello" {
statement_id = "AllowAPIGatewayInvoke"
action = "lambda:InvokeFunction"
function_name = aws_lambda_function.hello.arn
principal = "apigateway.amazonaws.com"
}
建立 output.tf
output "url" {
value = "${aws_api_gateway_deployment.hello_v1.invoke_url}${aws_api_gateway_resource.hello.path}"
}
$ terraform apply
Apply complete! Resources: 6 added, 0 changed, 0 destroyed.
Outputs:
url = https://k09e1wi32e.execute-api.ap-northeast-1.amazonaws.com/v1/hello
我們成功建立了無伺服器的 API 了。
使用 curl 指令測試 API
curl 'https://k09e1wi32e.execute-api.ap-northeast-1.amazonaws.com/v1/hello'
{"message":"Hello World!","at":"2020-09-26T10:09:01Z"}%
curl 'https://k09e1wi32e.execute-api.ap-northeast-1.amazonaws.com/v1/hello?name=John'
{"message":"Hello, John!\n","at":"2020-09-26T10:09:45Z"}%
一樣只要 terraform destroy
就可以把所有基礎架構刪除。
$ terraform destroy
...
Destroy complete! Resources: 8 destroyed.
以上所有測試的完整檔案,可以在 Github 上面看到