MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Terraform Tutorial with Google Cloud – Create Single VM & Network

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

  1. terraform init downloads the Google provider and creates .terraform/ and .terraform.lock.hcl. Commit the lock file to version control.
  2. terraform fmt and terraform validate fix formatting and catch syntax or type errors before any API call is made.
  3. terraform plan shows what will be created. Expect Plan: 3 to add, 0 to change, 0 to destroy.
  4. terraform apply repeats the plan and asks for yes. On success it prints Apply complete! Resources: 3 added, 0 changed, 0 destroyed. followed by the outputs.
  5. Connect to the VM with gcloud compute ssh terraform-instance --zone us-central1-c --tunnel-through-iap.
  6. terraform destroy removes 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

ErrorCauseFix
Compute Engine API has not been used in project ... or it is disabledAPI not enabledgcloud services enable compute.googleapis.com, wait a minute, then retry
could not find default credentialsNo Application Default Credentialsgcloud auth application-default login or set GOOGLE_APPLICATION_CREDENTIALS
The resource 'projects/debian-cloud/global/images/family/debian-9' was not foundDebian 9 image removedUse a current family such as debian-cloud/debian-12
The resource 'projects/.../global/networks/default' was not foundDefault network deleted or never createdCreate your own network as in the corrected configuration
Error 403 ... Required 'compute.instances.create' permissionMissing IAM role or wrong project IDGrant a Compute role, then check that project_id is the ID, not the name
ZONE_RESOURCE_POOL_EXHAUSTEDNo capacity for that machine type in the zoneChange zone or machine_type and apply again
SSH times outNo ingress rule or wrong source rangeCheck 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 .tf files. Use variables, tfvars files 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 defined google_compute_subnetwork resources and planned CIDR ranges.
  • Attach a dedicated, minimally scoped service account to VMs instead of the Compute Engine default service account.
  • Run terraform fmt, validate and 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

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals

Related Posts

Terraform Tutorial with Google Cloud – Create Single VM

This tutorial shows how to create a single Google Compute Engine VM with Terraform, using the google_compute_instance resource above as the starting point. The snippet above only…

Read More

Terraform Variable Example: Azure & AWS

This page shows how to declare and use Terraform input variables of type number, string, bool, list and map with AWS and Azure resources. Below the original…

Read More

Terraform dynamaic block details explaination with example

A Terraform dynamic block generates repeated nested blocks inside a resource, data source, provider or provisioner, such as ingress rules in a security group or rule blocks…

Read More

Terraform Error Handing with Try Catch

Terraform has no try { } catch { } block. Error handling in HCL uses the try() function, which returns the first of its arguments that evaluates…

Read More

Terraform: Example Code for Create Multiple Azure Linux Vms

This page shows how to create several Azure Linux virtual machines from one Terraform configuration by using the count meta-argument. The VMs sit behind a load balancer…

Read More

Terraform Tools for Developer Productivity Master Guide

Tools, Workflow, Security, Testing, CI/CD, Automation, AI Assistance, Governance, and Production Best Practices Verified baseline: 5 September 2026Audience: Terraform developers, DevOps/SRE, platform/cloud engineers, module authors, DevSecOps teams, and engineering…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x