Setup Google Compute Enggine (GCE) with Terraform


Pre-requisites

  1. Terraform
  2. Google Cloud Platform account
  3. GCP API Authentication credentials

Script to create Google Compute Enggine with Terrafor.

// Variable
variable "region" {
  default = "us-east1-d"
}

variable "project" {
  default = "vital-ensign-188214"
}

// Provider
provider "google" {
  credentials = "${file("myfirstproject-teraform-ce.json")}"
  project     = "${var.project}"
  region      = "${var.region}"
}

// Google Compute Instance
resource "google_compute_instance" "test" {
  count        = 1                        // 
  name         = "test${count.index + 1}" // yields "test1", "test2", etc. It's also the machine's name and hostname
  machine_type = "f1-micro"               // smallest (CPU & RAM) available instance
  zone         = "${var.region}"          //

  boot_disk {
    initialize_params {
      image = "ubuntu-1710"
    }
  }

  network_interface {
    network = "default"

    access_config {
      // Ephemeral IP - leaving this block empty will generate a new external IP and assign it to the machine
    }
  }
}

This simple script is devided into 3 part: Variable, Provider, Resource

Variable

  1. Region: Region where Google Compute Enginne will be deploy (Available GCP Region)
  2. Project: GCP Project

Provider

1.Credential: Contain authenticated requared to create resource (Google Cloud Platform -> API Manager -> Credentials -> Create Credentials -> Service account key) 1. Region & Project: We already define this in variable

Resource

  1. Google Compute Instance: Manages a VM instance resource within GCE. An instance is a virtual machine (VM) hosted on Google's infrastructure.
  2. boot_disk: The boot disk for the instance.
  3. network_interface: Networks to attach to the instance

Terraform Commands

  • terraform get: The terraform get command is used to download and update modules mentioned in the root module.
  • terraform plan: create an execution plan
  • terraform apply: apply the changes required to reach the desired state of the configuration, or the pre-determined set of actions generated by a terraform plan execution plan.
  • terraform destroy: destroy the Terraform-managed infrastructure.