Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Neste tutorial, você vai aprender a implantar uma função do Pub/Sub fazendo upload
de um arquivo ZIP do código-fonte da função em um bucket do Cloud Storage usando o
Terraform para provisionar os recursos. O Terraform é uma ferramenta de código aberto que permite provisionar recursos Google Cloud com arquivos de configuração declarativos
Neste tutorial, usamos uma função Node.js como exemplo, mas ela também funciona
com funções Python, Go e Java. As instruções são as mesmas, independentemente do
ambiente de execução usado. Consulte as páginas de referência do Hashicorp para mais detalhes sobre como usar o Terraform com a API Cloud Functions v2.
Objetivos
Saiba como usar o Terraform para implantar uma função Pub/Sub.
Custos
Neste documento, você vai usar os seguintes componentes faturáveis do Google Cloud:
Para gerar uma estimativa de custo baseada na projeção de uso deste tutorial, use a calculadora de preços.
Novos usuários do Google Cloud podem estar qualificados para um teste gratuito.
Antes de começar
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.
Neste tutorial, você executa comandos no Cloud Shell. O Cloud Shell é um ambiente com a Google Cloud CLI pré-instalada, incluindo a Google Cloud CLI e os valores já definidos para o projeto atual.
O Cloud Shell pode demorar vários minutos para ser inicializado.
Mude para o diretório que contém o código
de amostra das funções do Cloud Run:
cdterraform-docs-samples/functions/pubsub
A amostra Node.js usada neste tutorial é uma função básica do
Pub/Sub "Hello World". Este é o arquivo 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"
}
}
Inicialize o Terraform
No diretório terraform-docs-samples/functions/pubsub que contém o
arquivo main.tf, execute este comando para adicionar os plug-ins necessários e criar o
diretório .terraform:
terraforminit
Validar a configuração do Terraform
Visualizar a configuração do Terraform. Essa etapa é opcional, mas permite
verificar se a sintaxe de main.tf está correta. Este comando mostra uma prévia dos recursos que serão criados:
terraformplan
Aplique a configuração do Terraform:
Implante a função aplicando a configuração. Quando solicitado, digite yes.
terraformapply
Como acionar a função
Para testar a função do Pub/Sub:
Publique uma mensagem no tópico. Neste exemplo, o nome do tópico é
functions2-topic:
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 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."]]