本教學課程將示範如何使用 Terraform 佈建資源,將函式來源程式碼 ZIP 檔案上傳至 Cloud Storage 值區,進而部署 Pub/Sub 函式。Terraform 是一項開放原始碼工具,可讓您透過宣告式設定檔佈建 Google Cloud 資源
本教學課程以 Node.js 函式為例,但也適用於 Python、Go 和 Java 函式。無論您使用哪個執行階段,操作說明都相同。如要進一步瞭解如何搭配使用 Terraform 和 Cloud Functions v2 API,請參閱 Hashicorp 的參考頁面。
目標
- 瞭解如何使用 Terraform 部署 Pub/Sub 函式。
費用
在本文件中,您會使用 Google Cloud的下列計費元件:
For details, see Cloud Run functions pricing.
您可以使用 Pricing Calculator 根據預測用量產生預估費用。
事前準備
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Cloud Functions, Cloud Build, Artifact Registry, and Cloud Storage APIs.
-
Install the Google Cloud CLI.
-
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
-
To initialize the gcloud CLI, run the following command:
gcloud init
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Cloud Functions, Cloud Build, Artifact Registry, and Cloud Storage APIs.
-
Install the Google Cloud CLI.
-
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
-
To initialize the gcloud CLI, run the following command:
gcloud init
- 將
roles/run.invoker
和roles/cloudbuild.builds.builder
指派給預設運算服務帳戶。 -
準備開發環境。
如果您已安裝 gcloud CLI,請執行下列指令進行更新:
gcloud components update
正在設定環境
在本教學課程中,您將使用 Cloud Shell 執行指令。Cloud Shell 是已安裝 Google Cloud CLI (包括 Google Cloud CLI) 的殼層環境,並已針對您目前的專案設定好適用值。Cloud Shell 可能需要幾分鐘的時間才能初始化:
準備應用程式
在 Cloud Shell 中執行下列步驟:
將應用程式存放區範例複製到 Cloud Shell 執行個體:
git clone https://github.com/terraform-google-modules/terraform-docs-samples.git
變更為包含 Cloud Run 函式範例程式碼的目錄:
cd terraform-docs-samples/functions/pubsub
本教學課程中使用的 Node.js 範例是基本「Hello World」Pub/Sub 函式。以下是
main.tf
檔案:
初始化 Terraform
在包含 main.tf
檔案的 terraform-docs-samples/functions/pubsub
目錄中,執行下列指令以新增必要的外掛程式,並建構 .terraform
目錄:
terraform init
驗證 Terraform 設定
預覽 Terraform 設定。這個步驟並非必要,但可讓您驗證 main.tf
的語法是否正確。這個指令會顯示即將建立的資源預覽畫面:
terraform plan
套用 Terraform 設定
套用設定來部署函式。出現提示時,請輸入 yes
:
terraform apply
觸發函式
如要測試 Pub/Sub 函式,請按照下列步驟操作:
將訊息發布至主題 (在本例中,主題名稱為
functions2-topic
):gcloud pubsub topics publish TOPIC_NAME --message="Friend"
請查看函式記錄檔,瞭解結果。其中
FUNCTION_NAME
是函式名稱 (在本例中,函式名稱為function
):gcloud functions logs read FUNCTION_NAME
您應該會看到記錄輸出內容,其中包含新的「Friend」訊息。
清除所用資源
完成教學課程後,您可以刪除所有建立的項目,避免產生任何額外費用。
您可以透過執行 terraform destroy
指令,透過 Terraform 移除設定檔中定義的所有資源:
terraform destroy
輸入 yes
可讓 Terraform 刪除資源。