Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Ce tutoriel explique comment déployer une fonction Pub/Sub en important un fichier ZIP de code source de fonction dans un bucket Cloud Storage, à l'aide de Terraform pour provisionner les ressources. Terraform est un outil Open Source qui vous permet de provisionner des ressources Google Cloud à l'aide de fichiers de configuration déclaratifs.
Ce tutoriel utilise une fonction Node.js comme exemple, mais il fonctionne également avec les fonctions Python, Go et Java. Les instructions sont identiques, quel que soit l'environnement d'exécution que vous utilisez. Pour en savoir plus sur l'utilisation de Terraform avec l'API Cloud Functions v2, consultez les pages de référence de Hashicorp.
Objectifs
Apprenez à utiliser Terraform pour déployer une fonction Pub/Sub.
Coûts
Dans ce document, vous utilisez les composants facturables de Google Cloudsuivants :
Obtenez une estimation des coûts en fonction de votre utilisation prévue à l'aide du simulateur de coût.
Les nouveaux utilisateurs de Google Cloud peuvent bénéficier d'un essai gratuit.
Avant de commencer
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.
Dans ce tutoriel, vous exécutez des commandes dans Cloud Shell. Cloud Shell est un environnement de shell dans lequel Google Cloud CLI est déjà installée avec des valeurs prédéfinies pour votre projet actuel.
L'initialisation de Cloud Shell peut prendre quelques minutes.
Accédez au répertoire contenant l'exemple de code Cloud Run Functions :
cdterraform-docs-samples/functions/pubsub
L'exemple Node.js utilisé dans ce tutoriel est une fonction Pub/Sub de base "Hello". Voici le fichier 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"
}
}
Initialiser Terraform
Dans le répertoire terraform-docs-samples/functions/pubsub contenant le fichier main.tf, exécutez cette commande pour ajouter les plug-ins nécessaires et créer le répertoire .terraform :
terraforminit
Valider la configuration Terraform
Prévisualisez la configuration Terraform. Bien que facultative, cette étape vous permet de vérifier que la syntaxe de main.tf est correcte. Cette commande affiche un aperçu des ressources qui seront créées:
terraformplan
Appliquer la configuration Terraform
Déployez la fonction en appliquant la configuration. Lorsque vous y êtes invité, saisissez yes.
terraformapply
Déclencher la fonction
Pour tester la fonction Pub/Sub, procédez comme suit :
Publiez un message sur le sujet (dans cet exemple, le nom du sujet est functions2-topic) :
Lisez les journaux de la fonction pour afficher le résultat, où FUNCTION_NAME correspond au nom de la fonction (dans cet exemple, le nom de la fonction est function) :
gcloud functions logs read FUNCTION_NAME
Les résultats de journalisation incluant votre nouveau message "Friend" doivent s'afficher.
Effectuer un nettoyage
Une fois le tutoriel terminé, vous pouvez supprimer tous les éléments que vous avez créés afin d'éviter tous frais supplémentaires.
Terraform vous permet de supprimer toutes les ressources définies dans le fichier de configuration en exécutant la commande terraform destroy:
terraformdestroy
Saisissez yes pour autoriser Terraform à supprimer vos ressources.
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/09/05 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 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."]]