GenAIHub
← Back to Technical Section

Terraform for GenAI Infrastructure

Infrastructure as Code (IaC) for reproducible AI/ML environments

What is Terraform?

Terraform is an Infrastructure as Code (IaC) tool by HashiCorp that allows you to define, provision, and manage cloud infrastructure using declarative configuration files. For GenAI projects, Terraform enables reproducible deployment of compute resources, databases, networking, and AI services across cloud providers.

Key Innovation: Terraform's declarative syntax and state management allows teams to version-control infrastructure, enabling reproducible ML environments that can be deployed consistently across development, staging, and production.

4,000+

Providers

Multi-Cloud

AWS, GCP, Azure

HCL

Declarative Language

State

Drift Detection

Core Concepts

Provider

Plugin for cloud platforms (AWS, GCP, Azure)

Resource

Infrastructure component to create

Module

Reusable configuration package

State

Current infrastructure snapshot

Write .tf files terraform init Download providers terraform plan Preview changes terraform apply Create resources

Basic Configuration

Provider Configuration

# main.tf - Provider configuration
terraform {
  required_version = ">= 1.0"
  
  required_providers {
    google = {
      source  = "hashicorp/google"
      version = "~> 5.0"
    }
  }
  
  # Remote state storage (recommended for teams)
  backend "gcs" {
    bucket = "my-terraform-state"
    prefix = "genai-project"
  }
}

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

Variables Definition

# variables.tf
variable "project_id" {
  description = "GCP Project ID"
  type        = string
}

variable "region" {
  description = "GCP Region"
  type        = string
  default     = "us-central1"
}

variable "environment" {
  description = "Environment (dev, staging, prod)"
  type        = string
  validation {
    condition     = contains(["dev", "staging", "prod"], var.environment)
    error_message = "Environment must be dev, staging, or prod."
  }
}

GenAI Infrastructure Examples

Cloud Run for GenAI API

# cloud_run.tf
resource "google_cloud_run_v2_service" "genai_api" {
  name     = "genai-api-${var.environment}"
  location = var.region

  template {
    containers {
      image = "gcr.io/${var.project_id}/genai-api:latest"
      
      resources {
        limits = {
          cpu    = "2"
          memory = "4Gi"
        }
      }
      
      env {
        name  = "OPENAI_API_KEY"
        value_source {
          secret_key_ref {
            secret  = google_secret_manager_secret.openai_key.secret_id
            version = "latest"
          }
        }
      }
    }
    
    scaling {
      min_instance_count = var.environment == "prod" ? 1 : 0
      max_instance_count = 10
    }
  }
}

# IAM binding for public access
resource "google_cloud_run_v2_service_iam_member" "public" {
  count    = var.environment == "prod" ? 1 : 0
  location = google_cloud_run_v2_service.genai_api.location
  name     = google_cloud_run_v2_service.genai_api.name
  role     = "roles/run.invoker"
  member   = "allUsers"
}

Vector Database (Pinecone-style)

# vertex_ai.tf - Vector Search for RAG
resource "google_vertex_ai_index" "embeddings" {
  region       = var.region
  display_name = "genai-embeddings-${var.environment}"
  
  metadata {
    contents_delta_uri = "gs://${var.bucket_name}/embeddings/"
    config {
      dimensions                  = 768
      approximate_neighbors_count = 100
      distance_measure_type       = "COSINE_DISTANCE"
      
      algorithm_config {
        tree_ah_config {
          leaf_node_embedding_count    = 1000
          leaf_nodes_to_search_percent = 10
        }
      }
    }
  }
  
  index_update_method = "STREAM_UPDATE"
}

Secrets Management

# secrets.tf
resource "google_secret_manager_secret" "openai_key" {
  secret_id = "openai-api-key-${var.environment}"
  
  replication {
    auto {}
  }
}

resource "google_secret_manager_secret" "anthropic_key" {
  secret_id = "anthropic-api-key-${var.environment}"
  
  replication {
    auto {}
  }
}

# Grant Cloud Run access to secrets
resource "google_secret_manager_secret_iam_member" "api_access" {
  for_each  = toset(["openai_key", "anthropic_key"])
  secret_id = google_secret_manager_secret[each.key].secret_id
  role      = "roles/secretmanager.secretAccessor"
  member    = "serviceAccount:${google_service_account.cloud_run.email}"
}

Essential Commands

terraform init

Initialize working directory, download providers

terraform plan

Preview changes before applying

terraform apply

Create or update infrastructure

terraform destroy

Remove all managed resources

terraform fmt

Format configuration files

terraform validate

Check configuration syntax

Project Structure

infrastructure/
├── environments/
│   ├── dev/
│   │   ├── main.tf
│   │   ├── variables.tf
│   │   └── terraform.tfvars
│   ├── staging/
│   │   └── ...
│   └── prod/
│       └── ...
├── modules/
│   ├── cloud-run/
│   │   ├── main.tf
│   │   ├── variables.tf
│   │   └── outputs.tf
│   ├── vector-db/
│   │   └── ...
│   └── networking/
│       └── ...
├── .terraform.lock.hcl    # Provider lock file
└── README.md

Best Practices

Warning: Never commit terraform.tfstate to Git. It may contain sensitive data. Use remote backends like GCS, S3, or Terraform Cloud.

  • Remote State: Store state in cloud storage with locking (GCS, S3, Azure Blob)
  • Modules: Create reusable modules for common patterns (Cloud Run, databases)
  • Environment Separation: Use workspaces or separate directories per environment
  • Variables: Never hardcode values; use variables with validation
  • Outputs: Export important values (URLs, IPs) for other systems
  • Version Pinning: Pin provider versions to avoid breaking changes
  • Plan Review: Always review terraform plan before apply
  • CI/CD Integration: Run Terraform in GitHub Actions with approval gates

Terraform vs Alternatives

Feature Terraform Pulumi CloudFormation
Language HCL (declarative) Python, TypeScript, Go YAML/JSON
Multi-Cloud ✅ Excellent ✅ Excellent ❌ AWS only
State Management External file/backend Pulumi Cloud or file Managed by AWS
Learning Curve Medium (new language) Low (familiar langs) Medium
Community Largest ecosystem Growing AWS-centric

Learn More

Related Topics

Test Your Knowledge

Score 8/10 or higher to pass