Managing Cloud Functions with Terraform

Learn how to deploy and manage serverless functions on Google Cloud Functions using Terraform

In this guide, we’ll explore how to manage Google Cloud Functions using Terraform.

Video Tutorial

Learn more about managing Google Cloud Functions with Terraform in this comprehensive video tutorial:

Prerequisites

  • Google Cloud SDK installed and configured
  • Terraform installed (version 1.0.0 or later)
  • A GCP project with billing enabled

Project Structure

.
├── main.tf                   # Main Terraform configuration file
├── variables.tf              # Variable definitions
├── outputs.tf               # Output definitions
├── terraform.tfvars         # Variable values
└── modules/
    └── functions/
        ├── main.tf          # Cloud Functions specific configurations
        ├── variables.tf      # Module variables
        ├── functions.tf     # Function configurations
        └── outputs.tf       # Module outputs

Provider Configuration

terraform {
  required_providers {
    google = {
      source  = "hashicorp/google"
      version = "~> 4.0"
    }
  }
}

provider "google" {
  project = var.project_id
  region  = var.region
}

Variables

variable "project_id" {
  description = "The ID of the GCP project"
  type        = string
}

variable "region" {
  description = "The region to deploy resources to"
  type        = string
  default     = "us-central1"
}

variable "function_name" {
  description = "Name of the Cloud Function"
  type        = string
}

variable "runtime" {
  description = "Runtime for the function"
  type        = string
  default     = "python39"
}

Storage Bucket for Function Code

resource "google_storage_bucket" "function_bucket" {
  name     = "${var.project_id}-function-source"
  location = var.region
}

data "archive_file" "function_source" {
  type        = "zip"
  source_dir  = "${path.module}/function"
  output_path = "${path.module}/function.zip"
}

resource "google_storage_bucket_object" "function_source" {
  name   = "function-source-${data.archive_file.function_source.output_md5}.zip"
  bucket = google_storage_bucket.function_bucket.name
  source = data.archive_file.function_source.output_path
}

Cloud Function

resource "google_cloudfunctions_function" "function" {
  name        = var.function_name
  description = "A serverless function managed by Terraform"
  runtime     = var.runtime

  available_memory_mb   = 256
  source_archive_bucket = google_storage_bucket.function_bucket.name
  source_archive_object = google_storage_bucket_object.function_source.name
  trigger_http         = true
  entry_point         = "main"

  environment_variables = {
    ENVIRONMENT = "production"
  }

  timeout     = 60
  max_instances = 10

  ingress_settings = "ALLOW_ALL"
}

# IAM entry for all users to invoke the function
resource "google_cloudfunctions_function_iam_member" "invoker" {
  project        = google_cloudfunctions_function.function.project
  region         = google_cloudfunctions_function.function.region
  cloud_function = google_cloudfunctions_function.function.name

  role   = "roles/cloudfunctions.invoker"
  member = "allUsers"  # Be cautious with public access
}

Outputs

output "function_url" {
  value       = google_cloudfunctions_function.function.https_trigger_url
  description = "The URL of the Cloud Function"
}

output "function_name" {
  value       = google_cloudfunctions_function.function.name
  description = "The name of the Cloud Function"
}

output "function_status" {
  value       = google_cloudfunctions_function.function.status
  description = "Status of the Cloud Function"
}

Best Practices

  1. Security:

    • Use appropriate IAM roles
    • Secure environment variables
    • Implement authentication
    • Use secret manager
  2. Performance:

    • Optimize cold starts
    • Configure memory appropriately
    • Use connection pooling
    • Implement caching
  3. Cost Optimization:

    • Monitor execution time
    • Set appropriate timeouts
    • Use memory efficiently
    • Implement retries
  4. Development:

    • Use version control
    • Implement testing
    • Follow coding standards
    • Document properly

Common Operations

Deploying Function

terraform init
terraform plan
terraform apply

Testing Function

curl $(terraform output -raw function_url)

Updating Function

# Update source code or configuration
terraform apply

Best Practices and Tips

  1. Function Management:

    • Keep functions focused
    • Implement proper error handling
    • Use appropriate triggers
    • Monitor execution
  2. Security:

    • Regular security updates
    • Audit access logs
    • Review permissions
    • Implement HTTPS
  3. Operations:

    • Monitor performance
    • Set up logging
    • Configure alerts
    • Regular maintenance

Conclusion

You’ve learned how to set up and manage Google Cloud Functions using Terraform. This setup provides:

  • Automated function deployment
  • Secure serverless infrastructure
  • Best practices implementation
  • Easy function management