Automating Google Cloud Functions with Terraform: A Step-by-Step Guide
Managing Google Cloud Functions manually is error-prone when scaling. Terraform codifies your infrastructure as declarative configuration, making deployments reproducible and version-controlled. This tutorial walks you through provisioning, updating, and destroying Cloud Functions using Terraform.
Before you start, ensure you have the Google Cloud SDK and Terraform installed. Authenticate with gcloud auth application-default login and enable the Cloud Functions API in your GCP project.
1. Define the Provider and Backend
Create a main.tf file. Set up the google provider with your project ID and region. Optionally configure a Cloud Storage backend to store state remotely.
provider "google" {
project = "your-project-id"
region = "us-central1"
}
terraform {
backend "gcs" {
bucket = "your-tf-state-bucket"
prefix = "cloud-functions"
}
}
2. Write the Cloud Function Resource
Use the google_cloudfunctions_function resource. Define the runtime, entry point, source code location (Cloud Storage bucket or local zip), and environment variables. For zip deployments, first upload your code to a bucket or use archive_file data source.
data "archive_file" "source" {
type = "zip"
source_dir = "${path.module}/function/"
output_path = "${path.module}/function.zip"
}
resource "google_storage_bucket_object" "code" {
name = "function-${data.archive_file.source.output_md5}.zip"
bucket = "your-code-bucket"
source = data.archive_file.source.output_path
}
resource "google_cloudfunctions_function" "my_func" {
name = "my-function"
runtime = "nodejs20"
entry_point = "helloWorld"
source_archive_bucket = google_storage_bucket_object.code.bucket
source_archive_object = google_storage_bucket_object.code.name
trigger_http = true
}
3. Deploy and Manage the Function
- Run
terraform initto initialize providers and backend. - Execute
terraform planto preview changes. - Deploy with
terraform apply -auto-approve. - To update, modify your source code or configuration, then plan and apply again.
4. Destroy Resources
When you no longer need the function, run terraform destroy to remove all associated resources – no leftover services or manual cleanup required.
By treating Cloud Functions as code, you gain repeatability, collaboration, and safety across environments. Start small – a single HTTP function – and expand to event-driven triggers and multiple runtimes as you master Terraform.