Intermediate

Reusable Terraform Modules

Build composable Terraform modules for GPU clusters, ML storage, and complete AI platforms that your team can reuse across projects and environments.

Module Structure

modules/
  gpu-cluster/
    main.tf          # Core resources
    variables.tf     # Input variables
    outputs.tf       # Output values
    versions.tf      # Provider constraints
  ml-storage/
    main.tf
    variables.tf
    outputs.tf
  ai-platform/       # Composite module
    main.tf           # Combines gpu-cluster + ml-storage
    variables.tf
    outputs.tf

GPU Cluster Module

# modules/gpu-cluster/variables.tf
variable "cluster_name"    { type = string }
variable "gpu_node_count"  { type = number, default = 2 }
variable "gpu_type"        { type = string, default = "nvidia-tesla-a100" }
variable "gpu_per_node"    { type = number, default = 4 }
variable "environment"     { type = string }

# modules/gpu-cluster/main.tf
resource "google_container_cluster" "cluster" {
  name     = var.cluster_name
  location = var.region
  # ... cluster configuration
}

resource "google_container_node_pool" "gpu" {
  name       = "${var.cluster_name}-gpu"
  node_count = var.gpu_node_count
  node_config {
    guest_accelerator {
      type  = var.gpu_type
      count = var.gpu_per_node
    }
  }
}

Using the Module

# environments/production/main.tf
module "training_cluster" {
  source         = "../../modules/gpu-cluster"
  cluster_name   = "prod-training"
  gpu_node_count = 8
  gpu_type       = "nvidia-tesla-a100"
  gpu_per_node   = 8
  environment    = "production"
}

module "ml_storage" {
  source      = "../../modules/ml-storage"
  bucket_name = "prod-ml-datasets"
  environment = "production"
}
Module versioning: Publish modules to a private Terraform registry and reference specific versions. This prevents breaking changes from propagating to production environments when modules are updated.