Terraform Tutorial

This tutorial demonstrates how to deploy an HTTP function by uploading afunction source code zip file to a Cloud Storage bucket, usingTerraform to provision the resources. Terraform is an opensource tool that lets you provision Google Cloud resources with declarativeconfiguration files.

This tutorial uses a Node.js HTTP function as an example, but it also workswith Python, Go, and Java HTTP functions. The instructions are the sameregardless of which of these runtimes you are using.

When you deploy with Terraform, you mustupload your function's zipped source file to a Cloud Storage bucket (source_archive_bucket),and also specify the Cloud Storage object name (source_archive_object) inthe Terraform configuration. For more information, see theTerraform specification guide.

Cloud Run functions copies the source file you upload in thesource_archive_bucket toa bucket in your project with a bucket name that follows the formatgcf-v2-sources-PROJECT_NUMBER-REGION(Cloud Run functions), orgcf-sources-PROJECT_NUMBER-REGION Cloud Run functions (1st gen). This configuration varies depending on the CMEK dependency.

Objectives

  • Learn how to use Terraform to deploy an HTTP function.

Costs

In this document, you use the following billable components of Google Cloud:

For details, seeCloud Run functions pricing.

To generate a cost estimate based on your projected usage, use thepricing calculator.

New Google Cloud users might be eligible for afree trial.

Before you begin

  1. 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.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.create permission.Learn how to grant roles.
    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.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Cloud Functions, Cloud Run, Cloud Build, Artifact Registry, and Cloud Storage APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enable permission.Learn how to grant roles.

    Enable the APIs

  5. Install the Google Cloud CLI.

  6. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  7. Toinitialize the gcloud CLI, run the following command:

    gcloudinit
  8. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.create permission.Learn how to grant roles.
    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.

    Go to project selector

  9. Verify that billing is enabled for your Google Cloud project.

  10. Enable the Cloud Functions, Cloud Run, Cloud Build, Artifact Registry, and Cloud Storage APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enable permission.Learn how to grant roles.

    Enable the APIs

  11. Install the Google Cloud CLI.

  12. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  13. Toinitialize the gcloud CLI, run the following command:

    gcloudinit
  14. If you already have the gcloud CLI installed, update it by running the following command:

    gcloud components update
  15. Prepare your development environment.

    Go to the Node.js setup guide

Required roles

Setting up your environment

In this tutorial, you run commands in Cloud Shell. Cloud Shell is ashell environment with the Google Cloud CLI already installed, including theGoogle Cloud CLI, and with values already set for your currentproject.Cloud Shell can take several minutes to initialize:

Open Cloud Shell

Preparing the application

In Cloud Shell, perform the following steps:

  1. Clone the sample app repository to your Cloud Shell instance:

    gitclonehttps://github.com/terraform-google-modules/terraform-docs-samples.git
  2. Change to the directory that contains the Cloud Run functions samplecode examples:

    cdterraform-docs-samples/functions/basic

    The Node.JS sample used in this tutorial is a basic "Hello World" HTTPfunction. Here is themain.tf file:

    terraform {  required_providers {    google = {      source  = "hashicorp/google"      version = ">= 4.34.0"    }  }}resource "random_id" "default" {  byte_length = 8}resource "google_storage_bucket" "default" {  name                        = "${random_id.default.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  = "functions/hello-world/"}resource "google_storage_bucket_object" "object" {  name   = "function-source.zip"  bucket = google_storage_bucket.default.name  source = data.archive_file.default.output_path # Add path to the zipped function source code}resource "google_cloudfunctions2_function" "default" {  name        = "function-v2"  location    = "us-central1"  description = "a new function"  build_config {    runtime     = "nodejs22"    entry_point = "helloHttp" # Set the entry point    source {      storage_source {        bucket = google_storage_bucket.default.name        object = google_storage_bucket_object.object.name      }    }  }  service_config {    max_instance_count = 1    available_memory   = "256M"    timeout_seconds    = 60  }}resource "google_cloud_run_service_iam_member" "member" {  location = google_cloudfunctions2_function.default.location  service  = google_cloudfunctions2_function.default.name  role     = "roles/run.invoker"  member   = "allUsers"}output "function_uri" {  value = google_cloudfunctions2_function.default.service_config[0].uri}

Initialize Terraform

In theterraform-docs-samples/functions/basic directory containing themain.tffile, run this command to add the necessary plugins and build the.terraformdirectory:

terraforminit

Apply the Terraform configuration

In the sameterraform-docs-samples/functions/basic directory containing themain.tffile, deploy the function by applying the configuration. When prompted, enteryes:

terraformapply

Test the function

  1. When the function finishes deploying, take note of the URI property or find it using the following command:

    gcloudfunctionsdescribefunction-v2--gen2--region=us-central1--format="value(serviceConfig.uri)"
  2. Make a request to this URL to see your function's "Hello World" message.Note that the function is deployed requiringauthentication.Therefore you must provide credentials in your request:

    curl-H"Authorization: Bearer$(gcloudauthprint-identity-token)"YOUR_FUNCTION_URL
Note: For security reasons, it is best practice to require authenticationfor HTTP function invocation. If required, you can enable unauthenticatedinvocationafter the function has been deployed.

Clean up

After completing the tutorial, you can delete everything that you created sothat you don't incur any further costs.

Terraform lets you remove all the resources defined in the configuration file byrunning theterraform destroy command in theterraform-docs-samples/functions/basicdirectory containing yourmain.tf file:

terraformdestroy

Enteryes to allow Terraform to delete your resources.

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-12-15 UTC.