0
0
TerraformHow-ToBeginner · 3 min read

How to Use Google Cloud Provider in Terraform: Simple Guide

To use the google provider in Terraform, declare it in your configuration with the required project and region settings. Then authenticate using a service account key or application default credentials to manage Google Cloud resources.
📐

Syntax

The provider block configures Terraform to use Google Cloud services. You specify the project ID and region where resources will be created. Authentication is handled automatically if credentials are set in the environment or via a service account key file.

terraform
provider "google" {
  project = "your-gcp-project-id"
  region  = "us-central1"
}
💻

Example

This example shows how to configure the Google Cloud provider and create a simple Compute Engine VM instance. It demonstrates setting the project, region, and zone, and using a basic resource.

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

provider "google" {
  project = "my-sample-project"
  region  = "us-central1"
  zone    = "us-central1-a"
}

resource "google_compute_instance" "vm_instance" {
  name         = "test-vm"
  machine_type = "e2-medium"
  zone         = "us-central1-a"

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

  network_interface {
    network = "default"
    access_config {}
  }
}
Output
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
⚠️

Common Pitfalls

Common mistakes include not setting the project or region in the provider block, which causes Terraform to fail to find the right Google Cloud project. Another issue is missing authentication credentials, which leads to permission errors. Always ensure your service account key is correctly referenced or that your environment has application default credentials set.

Also, avoid hardcoding sensitive data directly in Terraform files; use environment variables or secret management.

terraform
provider "google" {
  # Missing project and region causes errors
}

# Correct way:
provider "google" {
  project = "my-project-id"
  region  = "us-central1"
}
📊

Quick Reference

  • project: Your Google Cloud project ID.
  • region: The region for resources (e.g., us-central1).
  • zone: Specific zone within the region (optional, but needed for some resources).
  • authentication: Use service account JSON key or application default credentials.
  • required_providers: Declare provider source and version in Terraform 0.13+.

Key Takeaways

Always declare the google provider with project and region in Terraform.
Authenticate using a service account key or application default credentials.
Use the required_providers block to specify provider source and version.
Avoid missing project or region to prevent configuration errors.
Keep sensitive credentials out of Terraform files; use environment variables.