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

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 shows the resource block. It leaves out the provider configuration, project and zone settings, and authentication, and it uses a Debian 9 image that Google has since retired. The sections below give a complete working configuration, the commands to deploy it and remove it, and fixes for the errors people hit most often.


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 = "default"
    access_config {
    }
  }
}Code language: PHP (php)


What the example above does and what it is missing

The resource block declares one VM named terraform-instance with the e2-micro machine type. Its boot disk is built from a public Debian image, and its network interface is attached to the project's default VPC. The empty access_config {} block matters: it tells Google to give the VM an ephemeral external IP address. If you remove it, the VM gets only an internal IP.

Terraform cannot run that block on its own. To work, it also needs:

  • A terraform block that declares the hashicorp/google provider.
  • A provider "google" block that sets the project, region and zone. Without a zone, the instance cannot be placed.
  • Credentials Terraform can use to call the Google Cloud APIs.
  • An image that still exists. The debian-cloud/debian-9 image family has been deprecated and removed from the public image list.

Prerequisites

  • A Google Cloud project with billing enabled.
  • Terraform 1.5 or later installed (terraform version).
  • The Google Cloud CLI installed (gcloud version).
  • An account with permission to create Compute Engine instances in the project, for example the Compute Instance Admin role.

Sign in, select the project, enable the Compute Engine API and create Application Default Credentials (ADC). The Terraform provider picks up ADC automatically, so you do not need a key file.

gcloud auth login
gcloud config set project YOUR_PROJECT_ID
gcloud services enable compute.googleapis.com
gcloud auth application-default loginCode language: CSS (css)

Note: Don't download service account JSON keys to a laptop just to run Terraform. Use ADC locally. In CI, use Workload Identity Federation or an attached service account.

Complete working configuration

Create an empty directory and add the following files. Together they wrap the original resource in everything it needs to run.

# versions.tf
terraform {
  required_version = ">= 1.5"

  required_providers {
    google = {
      source  = "hashicorp/google"
      version = ">= 6.0"
    }
  }
}

provider "google" {
  project = var.project_id
  region  = var.region
  zone    = var.zone
}Code language: PHP (php)
# variables.tf
variable "project_id" {
  description = "Google Cloud project ID"
  type        = string
}

variable "region" {
  type    = string
  default = "us-central1"
}

variable "zone" {
  type    = string
  default = "us-central1-a"
}Code language: PHP (php)
# main.tf
resource "google_compute_instance" "vm_instance" {
  name         = "terraform-instance"
  machine_type = "e2-micro"
  zone         = var.zone

  labels = {
    env        = "lab"
    managed_by = "terraform"
  }

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

  network_interface {
    network = "default"
    access_config {}   # ephemeral public IP
  }

  shielded_instance_config {
    enable_secure_boot = true
  }
}Code language: PHP (php)
# outputs.tf
output "instance_name" {
  value = google_compute_instance.vm_instance.name
}

output "external_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)

debian-cloud/debian-12 uses the project/family shorthand, which always resolves to the latest image in that family. If you need builds you can repeat exactly, pin a specific image name instead. To list the current families, run gcloud compute images list --filter="family~debian".

Note: Before using this in a real project, check the Terraform Registry for the latest major version of the Google provider. Then pin to it with a pessimistic constraint such as ~> X.0, so that a future major release cannot change behaviour without warning.

Deploy, connect and clean up

  1. Run terraform init to download the Google provider and create .terraform.lock.hcl.
  2. Run terraform fmt and terraform validate to catch syntax mistakes early.
  3. Run terraform plan and review it. It should end with Plan: 1 to add, 0 to change, 0 to destroy.
  4. Run terraform apply and type yes. Creating the VM usually takes under a minute, and the outputs print at the end.
  5. Connect with gcloud compute ssh terraform-instance --zone us-central1-a. The default network includes a firewall rule that allows SSH on port 22.
  6. When you have finished, run terraform destroy so you are not billed for the VM or its disk.
$ terraform apply
...
google_compute_instance.vm_instance: Creating...
google_compute_instance.vm_instance: Creation complete after 15s [id=projects/YOUR_PROJECT_ID/zones/us-central1-a/instances/terraform-instance]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

Outputs:

external_ip = "34.x.x.x"
instance_name = "terraform-instance"
internal_ip = "10.128.0.2"Code language: JavaScript (javascript)

Corrected version of the original snippet

If you only want to fix the snippet above, here is the minimal corrected resource. You still need the provider block from the previous section.

resource "google_compute_instance" "vm_instance" {
  name         = "terraform-instance"
  machine_type = "e2-micro"
  zone         = "us-central1-a"

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

  network_interface {
    network = "default"
    access_config {}
  }
}Code language: JavaScript (javascript)
  • debian-cloud/debian-9 became debian-cloud/debian-12, because the Debian 9 image family is retired and no longer resolves.
  • Added a zone. Alternatively, set it in the provider block, as shown in the full configuration.
  • A provider block with a project is required, or you can set the GOOGLE_PROJECT environment variable instead.

Common errors and fixes

Error message (abbreviated)CauseFix
could not find default credentialsADC is not configuredRun gcloud auth application-default login
project: required field is not setNo project in the provider block or the environmentSet project in the provider block or export GOOGLE_PROJECT
Compute Engine API has not been used in project ... or it is disabledThe API is not enabledRun gcloud services enable compute.googleapis.com and wait a minute
The resource 'projects/debian-cloud/global/images/family/debian-9' was not foundThe image family is retiredUse debian-cloud/debian-12 or another current family
The resource 'projects/.../networks/default' was not foundThe project has no default VPC, which is common when an organization policy skips its creationCreate a VPC with google_compute_network or reference an existing one
ZONE_RESOURCE_POOL_EXHAUSTED or a quota errorThe zone is out of capacity or a project quota has been reachedTry another zone or request a quota increase
Required 'compute.instances.create' permissionYour identity lacks IAM permissionsGrant a role such as Compute Instance Admin on the project

Best practices and security notes

  • Do not commit state. Add *.tfstate*, .terraform/ and *.tfvars files that contain secrets to .gitignore. Do commit .terraform.lock.hcl.
  • Use remote state for team work. Configure a backend "gcs" block pointing at a versioned Cloud Storage bucket, so state is shared and protected by locking.
  • Limit public exposure. Drop access_config {} when a VM doesn't need a public IP. Use IAP TCP forwarding (gcloud compute ssh --tunnel-through-iap) or Cloud NAT for outbound traffic.
  • Attach a dedicated service account to the VM with only the roles it needs, rather than relying on the Compute Engine default service account.
  • Turn on deletion protection (deletion_protection = true) for long-lived VMs.
  • Scan and lint before applying. Tools such as tfsec flag issues like public IPs and missing Shielded VM settings. See Terraform Tutorials: TFSec for Security Scanning and How to Configure pre-commit for Terraform.

To create several identical VMs from one block, add count or for_each to the resource. Terraform Loops and Iteration covers both patterns.

Frequently asked questions

Why does Terraform say the debian-9 image was not found?

Google has retired the Debian 9 image family, so debian-cloud/debian-9 no longer resolves to an image. Change it to a current family such as debian-cloud/debian-12.

Do I need a service account key file to run Terraform against Google Cloud?

No. Locally, run gcloud auth application-default login and the Google provider uses those credentials automatically. In CI, Workload Identity Federation is preferred over long-lived JSON keys.

What does the empty access_config block do?

It gives the VM an ephemeral external IP address. If you remove it, the instance has only an internal IP and needs IAP, a bastion host or Cloud NAT for access and outbound traffic.

Is an e2-micro VM free?

Google Cloud's Always Free tier includes one e2-micro instance per month in certain US regions, subject to the current free tier terms. VMs outside those regions, or above the free limits, are billed normally, so run terraform destroy when you have finished testing.

How do I get the VM's public IP from Terraform?

Add an output that references google_compute_instance.vm_instance.network_interface[0].access_config[0].nat_ip, then run terraform output external_ip after apply.

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 & 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….

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