Skip to content

Create the Compute Engine VM with Terraform on Google Cloud

Objectives:

  • Understand the resource dependencies
  • Understand the .name and .self_link concept
  • Know to create a virtual machine with Terraform on GCP

Prerequisite

  • Google Cloud Account

Tasks

  1. Create a VM instance with default network
  2. Create a VM instance with linked VPC network

Context

Boot disk :In the context of virtual machines (VMs), the term “boot disk” refers to the primary disk that contains the operating system and boot loader necessary for the VM to start up and run. The boot disk is where the VM’s operating system is installed, and it plays a critical role in the initial boot process of the virtual machine.

Network Interface: In the context of a virtual machine (VM), a network interface refers to a virtual representation of a network adapter or network interface card (NIC) within the VM’s operating system. It allows the VM to connect to and communicate over a network.

Code

Task 1

resource "google_compute_instance" "vm_instance" {
  name         = "terraform-instance"
  machine_type = "e2-micro"

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

  network_interface {
    # A default network is created for all GCP projects
    network = "default"
    access_config {
    }
  }
}

Task 2

# step 1. create a VPC network
resource "google_compute_network" "vpc_network" {
  name                    = "terraform-network"
  auto_create_subnetworks = "true"
}

#step 2 create a VM instance
resource "google_compute_instance" "vm_instance" {
  name         = "terraform-instance"
  machine_type = "e2-micro"

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

network_interface {
       # use the "terraform-network"
    network = google_compute_network.vpc_network.name
    access_config {
    }
  }
}