This tutorial uses Terraform to create a Google Compute Engine VM on Google Cloud, either in a new auto-mode VPC network or in the project's default network. Below the original examples you'll find a corrected, ready-to-run version with a current Debian image, variables, a firewall rule and outputs. It also covers authentication, the full init-plan-apply-destroy workflow and fixes for the errors you're most likely to hit.
provider "google" {
project = "{{YOUR GCP PROJECT}}"
region = "us-central1"
zone = "us-central1-c"
}
resource "google_compute_instance" "vm_instance" {
name = "terraform-instance"
machine_type = "e2-micro"
boot_disk {
initialize_params {
image = "debian-cloud/debian-9"
}
}
network_interface {
# A default network is created for all GCP projects
network = google_compute_network.vpc_network.self_link
access_config {
}
}
}
resource "google_compute_network" "vpc_network" {
name = "terraform-network"
auto_create_subnetworks = "true"
}Code language: PHP (php)
resource "google_compute_instance" "default" {
name = "test"
machine_type = "e2-medium"
zone = "us-central1-a"
tags = ["foo", "bar", "ramu"]
boot_disk {
initialize_params {
image = "debian-cloud/debian-9"
}
}
network_interface {
network = "default"
access_config {
// Ephemeral public IP
}
}
metadata = {
foo = "bar"
}
}Code language: JavaScript (javascript)
What the two examples above do
The first example creates two resources. google_compute_network.vpc_network is a new VPC called terraform-network in auto mode, which means Google creates one subnet in every region. google_compute_instance.vm_instance is an e2-micro VM attached to that network. The VM refers to the network through google_compute_network.vpc_network.self_link. Terraform reads that reference as a dependency, so it creates the network first and deletes it last.
The second example creates one e2-medium VM in the project's existing default network. It also shows network tags (tags), which firewall rules use to target instances, and custom instance metadata, which software on the VM can read from the metadata server. In both examples, the empty access_config {} block gives the VM an ephemeral public IP. Remove that block if the VM should have only a private IP.
Note: Neither example will work exactly as written today. The debian-cloud/debian-9 image family is end-of-life and has been removed from the public images. The second example also assumes a default network exists, and many organisations delete it or block it with policy. The corrected version below fixes both problems.
Prerequisites and authentication
- A Google Cloud project with billing enabled, and its project ID (not the display name).
- Terraform CLI installed (
terraform -version). - Google Cloud CLI installed (
gcloud --version). - An account with permission to create Compute Engine resources, for example the Compute Admin role on the project.
# Log in and set the project for gcloud commands
gcloud auth login
gcloud config set project YOUR_PROJECT_ID
# Create Application Default Credentials, which the Terraform Google provider uses
gcloud auth application-default login
# Enable the Compute Engine API (the first enable can take a minute)
gcloud services enable compute.googleapis.comCode language: PHP (php)
In CI pipelines, use a service account through Workload Identity Federation or the runner's attached identity rather than user credentials. Avoid downloading long-lived service account JSON keys where you can.
Corrected and complete configuration
Put these files in an empty directory. This version builds on the first example. It adds a terraform block that pins the provider source, swaps the hard-coded project placeholder for a variable, uses a supported Debian image and adds a firewall rule so you can actually SSH to the VM.
# versions.tf
terraform {
required_providers {
google = {
source = "hashicorp/google"
version = ">= 5.0" # pin to the major version you have tested
}
}
}
provider "google" {
project = var.project_id
region = var.region
zone = var.zone
}Code language: PHP (php)
# variables.tf
variable "project_id" {
description = "GCP project ID"
type = string
}
variable "region" {
type = string
default = "us-central1"
}
variable "zone" {
type = string
default = "us-central1-c"
}
variable "ssh_source_ranges" {
description = "CIDRs allowed to SSH. 35.235.240.0/20 is the IAP TCP forwarding range."
type = list(string)
default = ["35.235.240.0/20"]
}Code language: PHP (php)
# main.tf
resource "google_compute_network" "vpc_network" {
name = "terraform-network"
auto_create_subnetworks = true
}
resource "google_compute_firewall" "allow_ssh" {
name = "terraform-allow-ssh"
network = google_compute_network.vpc_network.name
allow {
protocol = "tcp"
ports = ["22"]
}
source_ranges = var.ssh_source_ranges
target_tags = ["ssh"]
}
resource "google_compute_instance" "vm_instance" {
name = "terraform-instance"
machine_type = "e2-micro"
tags = ["ssh"]
boot_disk {
initialize_params {
image = "debian-cloud/debian-12"
}
}
network_interface {
network = google_compute_network.vpc_network.self_link
access_config {} # ephemeral public IP
}
metadata = {
environment = "lab"
}
}Code language: PHP (php)
# outputs.tf
output "instance_name" {
value = google_compute_instance.vm_instance.name
}
output "public_ip" {
value = google_compute_instance.vm_instance.network_interface[0].access_config[0].nat_ip
}
output "internal_ip" {
value = google_compute_instance.vm_instance.network_interface[0].network_ip
}Code language: PHP (php)
# terraform.tfvars
project_id = "your-project-id"Code language: PHP (php)
A new custom VPC has only implied rules: all egress is allowed and all ingress is denied. Without the firewall rule, the VM boots normally but no SSH connection can reach it. The rule applies only to instances with the ssh network tag, and the VM has that tag.
Run the workflow
terraform initdownloads the Google provider and creates.terraform/and.terraform.lock.hcl. Commit the lock file to version control.terraform fmtandterraform validatefix formatting and catch syntax or type errors before any API call is made.terraform planshows what will be created. ExpectPlan: 3 to add, 0 to change, 0 to destroy.terraform applyrepeats the plan and asks foryes. On success it printsApply complete! Resources: 3 added, 0 changed, 0 destroyed.followed by the outputs.- Connect to the VM with
gcloud compute ssh terraform-instance --zone us-central1-c --tunnel-through-iap. terraform destroyremoves the VM, the firewall rule and the network, in reverse dependency order, when you are finished.
terraform init
terraform fmt
terraform validate
terraform plan -out=tfplan
terraform apply tfplan
terraform output public_ip
# verify from gcloud
gcloud compute instances list --filter="name=terraform-instance"
# clean up
terraform destroyCode language: PHP (php)
Note: When you run terraform apply tfplan, Terraform applies the saved plan without asking again. Use this pattern in pipelines so that exactly what was reviewed is what gets applied.
Making the second example work
The second example has no provider block, so it inherits the project from the provider configuration in the same directory. If you copy it into the configuration above, change the image to debian-cloud/debian-12. Then check that the default network exists with gcloud compute networks list. Also note that its zone = "us-central1-a" argument overrides the provider's default zone for that one instance.
The default network comes with a default-allow-ssh rule that opens port 22 to 0.0.0.0/0. That is convenient for a lab and risky for anything else. Network tags such as foo, bar and ramu have no effect until a firewall rule targets them. Tags must be lowercase letters, digits and hyphens.
Common errors and fixes
| Error | Cause | Fix |
|---|---|---|
Compute Engine API has not been used in project ... or it is disabled | API not enabled | gcloud services enable compute.googleapis.com, wait a minute, then retry |
could not find default credentials | No Application Default Credentials | gcloud auth application-default login or set GOOGLE_APPLICATION_CREDENTIALS |
The resource 'projects/debian-cloud/global/images/family/debian-9' was not found | Debian 9 image removed | Use a current family such as debian-cloud/debian-12 |
The resource 'projects/.../global/networks/default' was not found | Default network deleted or never created | Create your own network as in the corrected configuration |
Error 403 ... Required 'compute.instances.create' permission | Missing IAM role or wrong project ID | Grant a Compute role, then check that project_id is the ID, not the name |
ZONE_RESOURCE_POOL_EXHAUSTED | No capacity for that machine type in the zone | Change zone or machine_type and apply again |
| SSH times out | No ingress rule or wrong source range | Check the firewall rule, its target_tags and your source CIDR |
Best practices
- Store state in a remote backend such as a GCS bucket with object versioning, not on a laptop. The state file contains resource details and sometimes secrets.
- Don't put project IDs, credentials or SSH keys in
.tffiles. Use variables,tfvarsfiles kept out of Git and a secrets manager. - Prefer IAP or a bastion host over public IPs. Remove
access_config {}on VMs that don't need internet ingress and use Cloud NAT for outbound traffic. - For production, use custom-mode VPCs (
auto_create_subnetworks = false) with explicitly definedgoogle_compute_subnetworkresources and planned CIDR ranges. - Attach a dedicated, minimally scoped service account to VMs instead of the Compute Engine default service account.
- Run
terraform fmt,validateand a security scanner such as tfsec in pre-commit hooks or CI.
Frequently asked questions
Is the e2-micro VM in this tutorial free?
Google Cloud's free tier has historically included one e2-micro instance per month in some US regions, including us-central1. Usage limits apply, along with charges for things like egress. Check the current free tier terms for your account before relying on it.
Why can't I SSH into a VM created in a new Terraform VPC?
A new custom VPC denies all ingress by default. Add a google_compute_firewall rule that allows TCP 22 from your IP or from the IAP range 35.235.240.0/20, and give the VM a matching network tag.
What is the difference between auto mode and custom mode VPC networks?
With auto_create_subnetworks = true, Google creates one subnet in every region from a fixed IP range. Custom mode (false) creates no subnets, so you define each subnet and its CIDR yourself. That's why it's the usual choice for production.
How do I find a valid image name for boot_disk?
Run gcloud compute images list --filter="family~debian" or browse the public image projects. Referencing a family such as debian-cloud/debian-12 gives you the latest image in that family.
How do I give the VM only a private IP?
Remove the access_config {} block from network_interface. To give the VM outbound internet access, add a Cloud Router and Cloud NAT, and use IAP for SSH.
Related tutorials
- More Terraform tutorials
- More Google Cloud tutorials
- Terraform Tutorials: TFSec for Security Scanning
- Terraform Loops and Iteration: Complete Guide to count, for_each, for Expressions, and Dynamic Blocks
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals