Skip to content

Terraform with Google Cloud Platform (GCP)

Introduction to GCP Provider

The Google Cloud Platform provider is used to interact with GCP resources and services. It requires proper authentication and configuration before use.

Provider Configuration

provider "google" {
  project = "my-project-id"
  region  = "us-central1"
  zone    = "us-central1-c"
}

Authentication

Common authentication methods:

  1. Google Cloud SDK
  2. Service Account Key File
  3. Google Application Default Credentials

Example using a service account key file:

provider "google" {
  credentials = file("path/to/service-account-key.json")
  project     = "my-project-id"
  region      = "us-central1"
}

Common GCP Resources

  1. Compute Engine Instance
resource "google_compute_instance" "default" {
  name         = "test"
  machine_type = "e2-medium"
  zone         = "us-central1-a"

  boot_disk {
    initialize_params {
      image = "debian-cloud/debian-10"
    }
  }

  network_interface {
    network = "default"
    access_config {
      // Ephemeral IP
    }
  }
}
  1. Cloud Storage Bucket
resource "google_storage_bucket" "static-site" {
  name          = "image-store.com"
  location      = "EU"
  force_destroy = true
}
  1. VPC Network
resource "google_compute_network" "vpc_network" {
  name                    = "terraform-network"
  auto_create_subnetworks = "true"
}

Best Practices

  1. Use service accounts with minimal necessary permissions
  2. Utilize GCP-specific modules from the Terraform Registry
  3. Use Terraform workspaces for managing multiple environments
  4. Implement proper state management and locking

Advanced Topics

  1. Working with Google Kubernetes Engine (GKE)
  2. Managing Cloud SQL instances
  3. Setting up Load Balancers
  4. Implementing Cloud Functions

Always refer to the official Terraform Google provider documentation for the most up-to-date information.