Effortless Cloud Deployment: Mastering VM Provisioning with Terraform on Google Cloud Platform

Hafizhan Aliady Afif
6 min readMar 20, 2024

--

Introduction

Usually, when creating a VM (Virtual Machine) on Google Cloud Platform (GCP), we tend to use the UI (User Interface) or Console Page provided by GCP. This process is relatively straightforward, but there’s a risk of forgetting the steps or configurations applied to previous VM instances, especially in large companies where documentation might be overlooked amidst heavy workloads.

Fortunately, there’s a solution to this issue: leveraging code to automate the setup of VMs or infrastructure on either a cloud provider or a local environment. This approach is commonly known as Infrastructure as Code (IaC).

This article aims to provide a tutorial on utilizing Terraform to implement IaC and create VMs on the Google Cloud Platform.

To begin, let’s follow the steps below:

Prerequisites

Sign up for a Google Cloud Platform account.

  • Visit https://cloud.google.com/free and follow the instruction
  • NB: for Indonesian folk that don’t have credit cards you can use
    digital banks like Bank Jag0, Bank Jen1us, and another bank that
    supports online digital transactions using debit cards.
    you can add IDR 100.000 to the card to prevent you from overspending
    on the cloud.

Install Terraform on your local machine.

  • For Mac, you can use brew install terraform
  • For Ubuntu / Windows users, you can read This

Set up authentication credentials for Terraform to interact with GCP.

  1. Install Gcloud,
  2. Login from console/terminal using `gcloud auth login`

Create Terraform backend on Google cloud storage

  1. Enable storage API
  2. Just create a bucket in Google Cloud storage.
    https://console.cloud.google.com/storage/browser
Click Create

Setting up Terraform Configuration

Step 1: Create Terraform backend

This is important to ensure that Terraform can track the state of your infrastructure and configuration. By using a remote backend, the state is stored in a remote, shared store, allowing team members to use Terraform commands that require state. Don’t forget to rename this file to backend.tf

terraform {
backend "gcs" {
bucket = "my-bucket-tfstate"
prefix = "terraform/state/vm"
}
}

Step 2: Create a Terraform Configuration File

In your main.tf file, start by specifying the provider details. The provider in this case is Google Cloud Platform. Here, you'll need to specify the project ID and region for your VM instance.

Create a new directory for your Terraform project and navigate into it. 
Then, create a file named `main.tf`.

Step 3: Configure Provider

In the provider block, specify “Google” as the provider, and then set the required parameters, namely the “project” and “region”. The “project” parameter is the ID of your GCP project, and the “region” is the region where your resources will be allocated. You can rename this file as providers.tf

# Define the GCP provider and specify the project ID and region.
provider "google" {
project = "hvzn-development"
region = "us-central1"
}

Step 4: Define VM Instance Resource

this is [main.tf](<http://main.tf>) the main file of Terraform resource declaration

resource "google_compute_instance" "default" {
name = "hvzn-instance"
machine_type = "e2-micro"
zone = "us-central1-a"

tags = ["foo", "bar"]

boot_disk {
initialize_params {
image = "projects/ubuntu-os-cloud/global/images/ubuntu-2204-jammy-v20240315a"
size = 10
type = "pd-balanced"
}
}

network_interface {
network = "default"
access_config {}
}

metadata_startup_script = "echo hi > /test.txt"

}

Parameters Explaination

This is the explaination for each row of the terraform main.tf

Resource Block:

resource "google_compute_instance" "default" {
  • This declares a resource of the type google_compute_instance. In Terraform, resources are the basic building blocks of infrastructure. This block is named default and will be referenced by this name throughout the configuration.

Name:

name = "hvzn-instance"
  • Sets the name of the compute instance to “hvzn-instance”. This will be the name by which you can refer to this instance in GCP.

Machine Type:


machine_type = "e2-micro"
  • Specifies the machine type for the instance. In this case, it’s set to “e2-micro”, which is a small machine type suitable for low-intensity workloads.

Zone:


zone = "us-central1-a"
  • Specify the zone where the instance will be created. In this case, it’s set to “us-central1-a”.

Tags:


tags = ["foo", "bar"]
  • Assign tags to the instance. Tags are used for organizing resources and applying firewall rules, among other things. In this case, the instance will have tags “foo” and “bar”.

Boot Disk:


boot_disk {
initialize_params {
image = "projects/ubuntu-os-cloud/global/images/ubuntu-2204-jammy-v20240315a"
size = 10
type = "pd-balanced"
}
}
  • Specifies the boot disk configuration for the instance. It defines the image, size, and type of the boot disk. Here, it’s using a Ubuntu 22.04 (Jammy) image from the Google Cloud Platform’s public images, with a size of 10 GB and type “pd-balanced”.

Network Interface:

network_interface {
network = "default"
access_config {}
}
  • Configures the network interface for the instance. In this case, it uses the default network and sets an access configuration.

Metadata Startup Script:

metadata_startup_script = "echo hi > /test.txt"
  • Specifies a startup script that will be executed when the instance starts. In this case, it simply echoes “hi” to a file named “test.txt” in the root directory.

This main.tf file is the minimum one, to get complete parameters you can see here on the Complete Documentation: Here
Make sure the file is structured like this

Let’s Deploy!

Step 5: Initialize Terraform

Run terraform init command to initialize the working directory containing Terraform configuration files.

Step 6: Plan the Deployment

Execute terraform plan to create an execution plan. Review the proposed changes to ensure they match your expectations.

This is an example that a VM will be created with this action, you can see the details of the VM.

Step 7: Apply the Configuration

Run terraform apply to apply the Terraform configuration and create the VM instance in GCP. Confirm the action when prompted.

Step 8: Verify Deployment

Visit the Google cloud platform console/web to verify the creation result.

nb: if you want to stop/destroy the VM just Run terraform destroy and the instance/resoruce that you write on the [main.tf](<http://main.tf>) file will be deleted. Be Cautions!

Conclusion

  • Recap of the steps involved in deploying VM instances in GCP using Terraform.
  • Highlight the benefits of using Terraform for infrastructure provisioning.
  • Encourage further exploration and experimentation with Terraform and GCP services.

Additional Resources

By following this guide, you’ll be able to efficiently deploy VM instances in the Google Cloud Platform using Terraform, streamlining your infrastructure provisioning process in a reproducible and scalable manner.

In the next article, we will cover how to set up CI/CD for terraform deployment to manage a cloud infrastructure.

--

--