Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Questo tutorial mostra come eseguire il deployment di una funzione Pub/Sub caricando
un file zip del codice sorgente della funzione in un bucket Cloud Storage utilizzando
Terraform per il provisioning delle risorse. Terraform è uno strumento open source che consente di eseguire il provisioning delle risorse con file di configurazione dichiarativi. Google Cloud
Questo tutorial utilizza una funzione Node.js come esempio, ma funziona anche
con le funzioni Python, Go e Java. Le istruzioni sono le stesse indipendentemente dal runtime che utilizzi. Consulta le
pagine di riferimento
di HashiCorp per informazioni dettagliate sull'utilizzo di Terraform con l'API Cloud Functions v2.
Obiettivi
Scopri come utilizzare Terraform per eseguire il deployment di una funzione Pub/Sub.
Costi
In questo documento vengono utilizzati i seguenti componenti fatturabili di Google Cloud:
Per generare una stima dei costi in base all'utilizzo previsto,
utilizza il calcolatore prezzi.
I nuovi utenti di Google Cloud potrebbero avere diritto a una prova senza costi.
Prima di iniziare
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.
In questo tutorial, esegui i comandi in Cloud Shell. Cloud Shell è un ambiente shell con Google Cloud CLI già installato, inclusa l'interfaccia a riga di comando Google Cloud, e con valori già impostati per il progetto corrente.
L'inizializzazione di Cloud Shell può richiedere diversi minuti:
Passa alla directory che contiene il codice campione delle funzioni Cloud Run:
cdterraform-docs-samples/functions/pubsub
L'esempio Node.js utilizzato in questo tutorial è una semplice funzione Pub/Sub "Hello World". Ecco il 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"
}
}
Inizializza Terraform
Nella directory terraform-docs-samples/functions/pubsub contenente il file
main.tf, esegui questo comando per aggiungere i plug-in necessari e creare la directory
.terraform:
terraforminit
Convalida la configurazione Terraform
Visualizza l'anteprima della configurazione Terraform. Questo passaggio è facoltativo, ma ti consente di
verificare che la sintassi di main.tf sia corretta. Questo comando mostra un'anteprima delle risorse che verranno create:
terraformplan
Applica la configurazione Terraform
Esegui il deployment della funzione applicando la configurazione. Quando richiesto, inserisci yes:
terraformapply
Attivazione della funzione
Per testare la funzione Pub/Sub:
Pubblica un messaggio nell'argomento (in questo esempio, il nome dell'argomento è
functions2-topic):
Leggi i log della funzione per visualizzare il risultato, dove
FUNCTION_NAME è il nome della tua funzione (in questo
esempio, il nome della funzione è function):
gcloud functions logs read FUNCTION_NAME
Dovresti visualizzare l'output di logging che include il nuovo messaggio "Amico".
Esegui la pulizia
Al termine del tutorial, puoi eliminare tutto ciò che hai creato per non incorrere in ulteriori costi.
Terraform ti consente di rimuovere tutte le risorse definite nel file di configurazione eseguendo il comando terraform destroy:
terraformdestroy
Inserisci yes per consentire a Terraform di eliminare le risorse.
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Difficile da capire","hardToUnderstand","thumb-down"],["Informazioni o codice di esempio errati","incorrectInformationOrSampleCode","thumb-down"],["Mancano le informazioni o gli esempi di cui ho bisogno","missingTheInformationSamplesINeed","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Altra","otherDown","thumb-down"]],["Ultimo aggiornamento 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."]]