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:
- Google Cloud SDK
- Service Account Key File
- 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
- 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
}
}
}
- Cloud Storage Bucket
resource "google_storage_bucket" "static-site" {
name = "image-store.com"
location = "EU"
force_destroy = true
}
- VPC Network
resource "google_compute_network" "vpc_network" {
name = "terraform-network"
auto_create_subnetworks = "true"
}
Best Practices
- Use service accounts with minimal necessary permissions
- Utilize GCP-specific modules from the Terraform Registry
- Use Terraform workspaces for managing multiple environments
- Implement proper state management and locking
Advanced Topics
- Working with Google Kubernetes Engine (GKE)
- Managing Cloud SQL instances
- Setting up Load Balancers
- Implementing Cloud Functions
Always refer to the official Terraform Google provider documentation for the most up-to-date information.