Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
En este instructivo, se demuestra cómo implementar una función de Pub/Sub mediante la carga de un archivo ZIP de código fuente de función a un bucket de Cloud Storage mediante Terraform para aprovisionar los recursos. Terraform es una herramienta de código abierto que te permite aprovisionar Google Cloud recursos con archivos de configuración declarativos.
En este instructivo, se usa una función de Node.js como ejemplo, pero también se aplica a las funciones de Python, Go y Java. Las instrucciones son las mismas sin importar el entorno de ejecución que uses. Consulta las
páginas de referencia
de Hashicorp para obtener detalles sobre el uso de Terraform con la API de Cloud Functions v2.
Objetivos
Aprende a usar Terraform para implementar una función de Pub/Sub.
Costos
En este documento, usarás los siguientes componentes facturables de Google Cloud:
Para generar una estimación de costos en función del uso previsto, usa la calculadora de precios.
Es posible que los usuarios de Google Cloud nuevos cumplan con los requisitos para acceder a una prueba gratuita.
Antes de comenzar
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.
En este instructivo, ejecutarás comandos en Cloud Shell. Cloud Shell es un entorno de shell con Google Cloud CLI ya instalada, incluida Google Cloud CLI, y valores ya establecidos para el proyecto actual.
La inicialización de Cloud Shell puede tomar varios minutos:
Ve al directorio que contiene el código de muestra de funciones de Cloud Run:
cdterraform-docs-samples/functions/pubsub
La muestra de Node.js que se usa en este instructivo es una función “Hello World” básica de Pub/Sub. Este es el archivo 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"
}
}
Inicializa Terraform
En el directorio terraform-docs-samples/functions/pubsub que contiene el archivo main.tf, ejecuta este comando para agregar los complementos necesarios y compilar el directorio .terraform:
terraforminit
Valida la configuración de Terraform
Obtén una vista previa de la configuración de Terraform. Este paso es opcional, pero te permite
verificar que la sintaxis de main.tf sea correcta. Este comando muestra una vista previa de los recursos que se crearán:
terraformplan
Aplica la configuración de Terraform
Aplica la configuración para implementar la función. Cuando se te solicite, ingresa yes:
terraformapply
Activa la función
Para probar la función de Pub/Sub, sigue estos pasos:
Publica un mensaje en el tema (en este ejemplo, el nombre del tema es functions2-topic):
Lee los registros de la función para ver el resultado, en el que FUNCTION_NAME es el nombre de tu función (en este ejemplo, el nombre de la función es function):
gcloud functions logs read FUNCTION_NAME
Deberías ver un resultado de registro que incluya tu nuevo mensaje “Amigable”.
Realiza una limpieza
Después de completar el instructivo, puedes borrar todo lo que creaste para no incurrir en más costos.
Terraform te permite quitar todos los recursos definidos en el archivo de configuración mediante la ejecución del comando terraform destroy:
terraformdestroy
Ingresa yes para permitir que Terraform borre tus recursos.
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Información o código de muestra incorrectos","incorrectInformationOrSampleCode","thumb-down"],["Faltan la información o los ejemplos que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 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."]]