本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
使用 AWS SAMCLI與進Terraform行本機除錯和測試
本主題介紹如何在Terraform專案和中使用支援的指 AWS Serverless Application Model 令行介面 (AWS SAMCLI) 指令Terraform Cloud。
若要提供意見反應並提交功能要求,請建立GitHub問題
本地測試 sam local invoke
注意
若要使用在本機 AWS SAMCLI進行測試,您必須安裝並設定 Docker。如需說明,請參閱 安裝泊塢視窗以搭配使用 AWS SAMCLI。
以下是透過傳入事件在本機測試 Lambda 函數的範例:
$
sam local invoke --hook-name terraform
hello_world_function
-eevents/event.json
-
若要瞭解有關使用此指令的更多資訊,請參閱測試簡介 sam local invoke。
本地測試 sam local start-api
若要sam local start-api
搭配使用Terraform,請執行下列命令:
$
sam local start-api --hook-name terraform
以下是範例:
$
sam local start-api --hook-name terraform
Running Prepare Hook to prepare the current application Executing prepare hook of hook "terraform" Initializing Terraform application ... Creating terraform plan and getting JSON output .... Generating metadata file Unresolvable attributes discovered in project, run terraform apply to resolve them. Finished generating metadata file. Storing in... Prepare hook completed and metadata file generated at: ... Mounting HelloWorldFunction at http://127.0.0.1:3000/hello [GET] Mounting None at http://127.0.0.1:3000/hello [POST] You can now browse to the above endpoints to invoke your functions. You do not need to restart/reload SAM CLI while working on your functions, changes will be reflected instantly/automatically. If you used sam build before running local commands, you will need to re-run sam build for the changes to be picked up. You only need to restart SAM CLI if you update your AWS SAM template 2023-06-26 13:21:20 * Running on http://127.0.0.1:3000/ (Press CTRL+C to quit)
若要瞭解有關此指令的更多資訊,請參閱測試簡介 sam local start-api。
使用 Lambda 授權器的 Lambda 函數
對於設定為使用 Lambda 授權器的 Lambda 函數, AWS SAMCLI會在叫用 Lambda 函數端點之前自動叫用您的 Lambda 授權器。
-
若要進一步瞭解中的此功能 AWS SAMCLI,請參閱使用 Lambda 授權器的 Lambda 函數。
-
如需有關使用 Lambda 授權者的詳細資訊Terraform,請參閱Terraform登錄Resource: aws_api_gateway_authorizer
中的。
本地測試 sam local start-lambda
以下是使用 AWS Command Line Interface (AWS CLI) 在本機測試 Lambda 函數的範例:
-
使用建 AWS SAMCLI立本機測試環境:
$
sam local start-lambda --hook-name terraform
hello_world_function
-
使用在本 AWS CLI 地調用您的函數:
$
aws lambda invoke --function-name
hello_world_function
--endpoint-urlhttp://127.0.0.1:3001/ response.json --cli-binary-format raw-in-base64-out --payload file://events/event.json
若要瞭解有關此指令的更多資訊,請參閱測試簡介 sam local start-lambda。
Terraform 限制
以下是搭配使用時 AWS SAMCLI的限制Terraform:
-
連結至多個圖層的 Lambda 函數。
-
Terraform定義資源之間連結的區域變數。
-
引用尚未創建的 Lambda 函數。這包括在RESTAPI資源的 body 屬性中定義的函數。
若要避免這些限制,您可以在新增資源terraform apply
時執行。