Tetap teratur dengan koleksi
Simpan dan kategorikan konten berdasarkan preferensi Anda.
Tutorial ini menunjukkan cara menerapkan fungsi Pub/Sub dengan mengupload file zip kode sumber fungsi ke bucket Cloud Storage, menggunakan Terraform untuk menyediakan resource. Terraform adalah alat open source yang dapat Anda gunakan untuk menyediakan Google Cloud resource dengan file konfigurasi deklaratif
Tutorial ini menggunakan fungsi Node.js sebagai contoh, tetapi juga dapat digunakan dengan fungsi Python, Go, dan Java. Petunjuknya sama, terlepas dari
runtime mana yang Anda gunakan. Lihat halaman referensi Hashicorp untuk mengetahui detail tentang cara menggunakan Terraform dengan Cloud Functions v2 API.
Tujuan
Pelajari cara menggunakan Terraform untuk men-deploy fungsi Pub/Sub.
Biaya
Dalam dokumen ini, Anda akan menggunakan komponen Google Cloudyang dapat ditagih berikut:
Untuk membuat perkiraan biaya berdasarkan proyeksi penggunaan Anda,
gunakan kalkulator harga.
Pengguna Google Cloud baru mungkin memenuhi syarat untuk mendapatkan uji coba gratis.
Sebelum memulai
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.
Dalam tutorial ini, Anda akan menjalankan perintah di Cloud Shell. Cloud Shell adalah
lingkungan shell dengan Google Cloud CLI yang sudah terinstal, termasuk
Google Cloud CLI, dan dengan nilai yang sudah ditetapkan untuk project Anda
saat ini.
Cloud Shell dapat memerlukan waktu beberapa menit untuk proses inisialisasi:
Ubah ke direktori yang berisi kode contoh fungsi Cloud Run:
cdterraform-docs-samples/functions/pubsub
Contoh Node.js yang digunakan dalam tutorial ini adalah fungsi Pub/Sub "Halo Dunia" dasar. Berikut adalah file main.tf:
terraform {
required_providers {
google = {
source = "hashicorp/google"
version = ">= 4.34.0"
}
}
}
resource "random_id" "bucket_prefix" {
byte_length = 8
}
resource "google_service_account" "default" {
account_id = "test-gcf-sa"
display_name = "Test Service Account"
}
resource "google_pubsub_topic" "default" {
name = "functions2-topic"
}
resource "google_storage_bucket" "default" {
name = "${random_id.bucket_prefix.hex}-gcf-source" # Every bucket name must be globally unique
location = "US"
uniform_bucket_level_access = true
}
data "archive_file" "default" {
type = "zip"
output_path = "/tmp/function-source.zip"
source_dir = "function-source/"
}
resource "google_storage_bucket_object" "default" {
name = "function-source.zip"
bucket = google_storage_bucket.default.name
source = data.archive_file.default.output_path # Path to the zipped function source code
}
resource "google_cloudfunctions2_function" "default" {
name = "function"
location = "us-central1"
description = "a new function"
build_config {
runtime = "nodejs22"
entry_point = "helloPubSub" # Set the entry point
environment_variables = {
BUILD_CONFIG_TEST = "build_test"
}
source {
storage_source {
bucket = google_storage_bucket.default.name
object = google_storage_bucket_object.default.name
}
}
}
service_config {
max_instance_count = 3
min_instance_count = 1
available_memory = "256M"
timeout_seconds = 60
environment_variables = {
SERVICE_CONFIG_TEST = "config_test"
}
ingress_settings = "ALLOW_INTERNAL_ONLY"
all_traffic_on_latest_revision = true
service_account_email = google_service_account.default.email
}
event_trigger {
trigger_region = "us-central1"
event_type = "google.cloud.pubsub.topic.v1.messagePublished"
pubsub_topic = google_pubsub_topic.default.id
retry_policy = "RETRY_POLICY_RETRY"
}
}
Lakukan inisialisasi Terraform
Dalam direktori terraform-docs-samples/functions/pubsub yang berisi file
main.tf, jalankan perintah ini untuk menambahkan plugin yang diperlukan dan membuat direktori
.terraform:
terraforminit
Memvalidasi konfigurasi Terraform
Lihat pratinjau konfigurasi Terraform. Langkah ini bersifat opsional, tetapi memungkinkan Anda
memverifikasi bahwa sintaksis main.tf sudah benar. Perintah ini menampilkan
pratinjau resource yang akan dibuat:
terraformplan
Menerapkan konfigurasi Terraform
Deploy fungsi dengan menerapkan konfigurasi. Saat diminta, masukkan yes.
terraformapply
Memicu fungsi
Untuk menguji fungsi Pub/Sub:
Memublikasikan pesan ke topik (dalam contoh ini, nama topiknya adalah functions2-topic):
[[["Mudah dipahami","easyToUnderstand","thumb-up"],["Memecahkan masalah saya","solvedMyProblem","thumb-up"],["Lainnya","otherUp","thumb-up"]],[["Sulit dipahami","hardToUnderstand","thumb-down"],["Informasi atau kode contoh salah","incorrectInformationOrSampleCode","thumb-down"],["Informasi/contoh yang saya butuhkan tidak ada","missingTheInformationSamplesINeed","thumb-down"],["Masalah terjemahan","translationIssue","thumb-down"],["Lainnya","otherDown","thumb-down"]],["Terakhir diperbarui pada 2025-09-05 UTC."],[[["\u003cp\u003eThis tutorial guides you through deploying a Pub/Sub function using Terraform, which involves uploading a function's source code zip file to a Cloud Storage bucket.\u003c/p\u003e\n"],["\u003cp\u003eThe process works for Node.js, Python, Go, and Java functions, with the instructions remaining consistent across these different runtimes.\u003c/p\u003e\n"],["\u003cp\u003eYou will need to set up your environment using Cloud Shell, prepare your function application by cloning the sample and creating a zip file of its source code, create a main.tf file to configure terraform, and apply the configuration.\u003c/p\u003e\n"],["\u003cp\u003eThe deployed Pub/Sub function can be tested by publishing a message to the specified topic, and then reading the function logs to verify the function's response to the message.\u003c/p\u003e\n"],["\u003cp\u003eYou can remove all the resources created during the tutorial using the \u003ccode\u003eterraform destroy\u003c/code\u003e command to avoid incurring further costs.\u003c/p\u003e\n"]]],[],null,["# Terraform Pub/Sub Tutorial\n\n*** ** * ** ***\n\nThis tutorial demonstrates how to deploy a Pub/Sub function by uploading\na function source code zip file to a Cloud Storage bucket, using\n[Terraform](/docs/terraform) to provision the resources. Terraform is an open\nsource tool that lets you provision Google Cloud resources with declarative\nconfiguration files\n\nThis tutorial uses a Node.js function as an example, but it also works\nwith Python, Go, and Java functions. The instructions are the same regardless of\nwhich of these runtimes you are using. See Hashicorp's\n[reference pages](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/cloudfunctions2_function)\nfor details on using Terraform with the Cloud Functions v2 API.\n\nObjectives\n----------\n\n- Learn how to use Terraform to deploy a Pub/Sub function.\n\nCosts\n-----\n\n\nIn this document, you use the following billable components of Google Cloud:\n\n\n- [Cloud Run functions](/functions/pricing)\n- [Cloud Build](/build/pricing)\n- [Cloud Storage](/storage/pricing)\n- [Artifact Registry](/artifact-registry/pricing)\n\n\u003cbr /\u003e\n\nFor details, see [Cloud Run functions pricing](/functions/pricing).\n\n\nTo generate a cost estimate based on your projected usage,\nuse the [pricing calculator](/products/calculator). \nNew Google Cloud users might be eligible for a [free trial](/free). \n\n\u003cbr /\u003e\n\nBefore you begin\n----------------\n\n- Sign in to your Google Cloud account. If you're new to Google Cloud, [create an account](https://console.cloud.google.com/freetrial) to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.\n- In the Google Cloud console, on the project selector page,\n select or create a Google Cloud project.\n\n | **Note**: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.\n\n [Go to project selector](https://console.cloud.google.com/projectselector2/home/dashboard)\n-\n [Verify that billing is enabled for your Google Cloud project](/billing/docs/how-to/verify-billing-enabled#confirm_billing_is_enabled_on_a_project).\n\n-\n\n\n Enable the Cloud Functions, Cloud Build, Artifact Registry, and Cloud Storage APIs.\n\n\n [Enable the APIs](https://console.cloud.google.com/flows/enableapi?apiid=cloudbuild.googleapis.com,artifactregistry.googleapis.com,cloudfunctions.googleapis.com,storage.googleapis.com&redirect=https://cloud.google.com/functions/docs/tutorials/terraform-pubsub)\n-\n [Install](/sdk/docs/install) the Google Cloud CLI.\n\n- If you're using an external identity provider (IdP), you must first\n [sign in to the gcloud CLI with your federated identity](/iam/docs/workforce-log-in-gcloud).\n\n-\n To [initialize](/sdk/docs/initializing) the gcloud CLI, run the following command:\n\n ```bash\n gcloud init\n ```\n\n- In the Google Cloud console, on the project selector page,\n select or create a Google Cloud project.\n\n | **Note**: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.\n\n [Go to project selector](https://console.cloud.google.com/projectselector2/home/dashboard)\n-\n [Verify that billing is enabled for your Google Cloud project](/billing/docs/how-to/verify-billing-enabled#confirm_billing_is_enabled_on_a_project).\n\n-\n\n\n Enable the Cloud Functions, Cloud Build, Artifact Registry, and Cloud Storage APIs.\n\n\n [Enable the APIs](https://console.cloud.google.com/flows/enableapi?apiid=cloudbuild.googleapis.com,artifactregistry.googleapis.com,cloudfunctions.googleapis.com,storage.googleapis.com&redirect=https://cloud.google.com/functions/docs/tutorials/terraform-pubsub)\n-\n [Install](/sdk/docs/install) the Google Cloud CLI.\n\n- If you're using an external identity provider (IdP), you must first\n [sign in to the gcloud CLI with your federated identity](/iam/docs/workforce-log-in-gcloud).\n\n-\n To [initialize](/sdk/docs/initializing) the gcloud CLI, run the following command:\n\n ```bash\n gcloud init\n ```\n\n1. If you already have the gcloud CLI installed, update it by running the following command: \n\n```sh\ngcloud components update\n```\n2. Grant [`roles/run.invoker`](/iam/docs/understanding-roles#run.invoker) and the [`roles/cloudbuild.builds.builder`](/iam/docs/understanding-roles#cloudbuild.builds.builder) to the default compute service account.\n3. Prepare your development environment. \n\n\n[Go to the Node.js setup guide](/nodejs/docs/setup) \n\nSetting up your environment\n---------------------------\n\nIn this tutorial, you run commands in Cloud Shell. Cloud Shell is a\nshell environment with the Google Cloud CLI already installed, including the\nGoogle Cloud CLI, and with values already set for your current\nproject.\nCloud Shell can take several minutes to initialize:\n\n[Open Cloud Shell](https://console.cloud.google.com/?cloudshell=true)\n\nPreparing the application\n-------------------------\n\nIn Cloud Shell, perform the following steps:\n\n1. Clone the sample app repository to your Cloud Shell instance:\n\n ```bash\n git clone https://github.com/terraform-google-modules/terraform-docs-samples.git\n ```\n2. Change to the directory that contains the Cloud Run functions sample\n code:\n\n ```bash\n cd terraform-docs-samples/functions/pubsub\n ```\n\n The Node.js sample used in this tutorial is a basic \"Hello World\"\n Pub/Sub function. Here is the `main.tf` file: \n\n terraform {\n required_providers {\n google = {\n source = \"hashicorp/google\"\n version = \"\u003e= 4.34.0\"\n }\n }\n }\n\n resource \"random_id\" \"bucket_prefix\" {\n byte_length = 8\n }\n\n\n resource \"google_service_account\" \"default\" {\n account_id = \"test-gcf-sa\"\n display_name = \"Test Service Account\"\n }\n\n resource \"google_pubsub_topic\" \"default\" {\n name = \"functions2-topic\"\n }\n\n resource \"google_storage_bucket\" \"default\" {\n name = \"${random_id.bucket_prefix.hex}-gcf-source\" # Every bucket name must be globally unique\n location = \"US\"\n uniform_bucket_level_access = true\n }\n\n data \"archive_file\" \"default\" {\n type = \"zip\"\n output_path = \"/tmp/function-source.zip\"\n source_dir = \"function-source/\"\n }\n\n resource \"google_storage_bucket_object\" \"default\" {\n name = \"function-source.zip\"\n bucket = google_storage_bucket.default.name\n source = data.archive_file.default.output_path # Path to the zipped function source code\n }\n\n resource \"google_cloudfunctions2_function\" \"default\" {\n name = \"function\"\n location = \"us-central1\"\n description = \"a new function\"\n\n build_config {\n runtime = \"nodejs22\"\n entry_point = \"helloPubSub\" # Set the entry point\n environment_variables = {\n BUILD_CONFIG_TEST = \"build_test\"\n }\n source {\n storage_source {\n bucket = google_storage_bucket.default.name\n object = google_storage_bucket_object.default.name\n }\n }\n }\n\n service_config {\n max_instance_count = 3\n min_instance_count = 1\n available_memory = \"256M\"\n timeout_seconds = 60\n environment_variables = {\n SERVICE_CONFIG_TEST = \"config_test\"\n }\n ingress_settings = \"ALLOW_INTERNAL_ONLY\"\n all_traffic_on_latest_revision = true\n service_account_email = google_service_account.default.email\n }\n\n event_trigger {\n trigger_region = \"us-central1\"\n event_type = \"google.cloud.pubsub.topic.v1.messagePublished\"\n pubsub_topic = google_pubsub_topic.default.id\n retry_policy = \"RETRY_POLICY_RETRY\"\n }\n }\n\nInitialize Terraform\n--------------------\n\nIn the `terraform-docs-samples/functions/pubsub` directory containing the\n`main.tf` file, run this command to add the necessary plugins and build the\n`.terraform` directory: \n\n terraform init\n\nValidate the Terraform configuration\n------------------------------------\n\nPreview the Terraform configuration. This step is optional, but it lets you\nverify that the syntax of `main.tf` is correct. This command shows a\npreview of the resources that will be created: \n\n terraform plan\n\nApply the Terraform configuration\n---------------------------------\n\nDeploy the function by applying the configuration. When prompted, enter `yes`: \n\n terraform apply\n\nTriggering the function\n-----------------------\n\nTo test the Pub/Sub function:\n\n1. Publish a message to the topic (in this example, the topic name is\n `functions2-topic`):\n\n ```sh\n gcloud pubsub topics publish TOPIC_NAME --message=\"Friend\"\n ```\n2. Read the function logs to see the result, where\n \u003cvar translate=\"no\"\u003eFUNCTION_NAME\u003c/var\u003e is the name of your function (in this\n example, the function name is `function`):\n\n ```sh\n gcloud functions logs read FUNCTION_NAME\n ```\n\n You should see logging output that includes your new \"Friend\" message.\n | **Note:** Logs might take a few moments to appear. If you don't see them immediately, check again in a minute or two.\n\nClean up\n--------\n\nAfter completing the tutorial, you can delete everything that you created so\nthat you don't incur any further costs.\n\nTerraform lets you remove all the resources defined in the configuration file by\nrunning the `terraform destroy` command: \n\n terraform destroy\n\nEnter `yes` to allow Terraform to delete your resources."]]