Terraform

Creating a virtual machine with Terraform in GCP

Hello. In this tutorial, we will create a virtual machine in gcp through terraform scripting.

1. Introduction

Terraform is an open-source tool developed by HashiCorp for building, changing, and versioning the infrastructure safely and efficiently. It is used to manage the infrastructure of the popular cloud service providers and custom in-house solutions. It helps manage both low-level (Compute, Storage, Networking, etc.) and high-level components (such as SaaS, DNS, etc.) Terraform deployment automation is divided into different sections i.e. –

  • IaaC – IaaC is popularly known as the Infrastructure as a Code, describing the infrastructure using a high-level configuration syntax. This allows a blueprint of the infrastructure which can be deployed, versioned, and shared for re-use
  • Execution Plans – Terraform has a planning step where it generates an execution plan. The execution plan tells the administrator what Terraform will do once applied and helps to avoid any surprises when it creates the infrastructure
  • Resource Graph – Terraform builds a graph of all the resources and parallelizes the creation and modification of non-dependent resources. This offers insights into learning the dependencies in their infrastructure
  • Change Automation – Terraform allows applying of complex changesets to the infrastructure with minimal human intervention

1.1 Steps

To create the infrastructure via the Terraform scripts following commands need to be executed in a sequence. However, details and actions may differ between workflows.

  • terraform init – Initializing the new or existing terraform configuration
  • terraform plan – Generate the execution plan from the resources specified in the file
  • terraform apply – Create the infrastructure from the resources specified in the file
  • terraform destroy – Destroy the created infrastructure

2. Creating a virtual machine with Terraform in GCP

To work in the terraform scripts I will be using the visual code as a preferred choice of my ide. As a pre-requisite for this tutorial, I already have the gcloud sdk setup on my laptop and signed in to an account. Hence the user credential information will be skipped from the provider block.

2.1 Creating the provider file

In the provider.tf file we will add the google provider information and will specify the project, region, and zone information.

provider.tf

provider "google" {
  // replace GCP_PROJECT_ID with your project
  project = "GCP_PROJECT_ID"
  region = "us-central1"
  zone = "us-central1-a"
}

2.2 Creating the main file

In the main.tf file we will create two firewall groups (i.e. ssh and webserver) and compute instance information of e2-micro type. An external ip of the instance will also be displayed as an output once the terraform apply step is completed. For this article, we are keeping the configuration very simple for creating an instance via terraform but in case if you’re interested in reading the detailed configuration you can navigate to this page.

main.tf

// resource 1: creating a ssh security group
resource "google_compute_firewall" "ssh" {
  name = "allow-ssh"
  network = "default"
  allow {
    protocol = "tcp"
    ports = ["22"]
  }
  // allow traffic from everywhere to instances with an ssh tag
  source_ranges = ["0.0.0.0/0"]
  target_tags   = ["ssh"]
}

// resource 2: creating a webserver security group
resource "google_compute_firewall" "http-server" {
  name = "allow-http-traffic"
  network = "default"
  allow {
    protocol = "tcp"
    ports = ["80"]
  }
  // allow traffic from everywhere to instances with an http-server tag
  source_ranges = ["0.0.0.0/0"]
  target_tags   = ["http-server"]
}

// resource 3: creating a webserver instance
resource "google_compute_instance" "default" {
  name = "webserver"
  machine_type = "e2-micro"
  zone = "us-central1-a"
  boot_disk {
    initialize_params {
      image = "debian-cloud/debian-11"
    }
  }
  network_interface {
    network = "default"
    access_config {
      // including this secion to give vm an external ip for accessing the webserver
    }
  }
  // install webserver metadata script
  metadata_startup_script = "sudo apt-get update && sudo apt-get install apache2 -y && echo '<!doctype html><html><body><h1>Hello world.!</h1></body></html>' | sudo tee /var/www/html/index.html"
  metadata = {
    "foo" = "bar"
  }
  // apply the firewall rule to allow external ips to access this instance
  tags = ["ssh", "http-server"]
  depends_on = [
    google_compute_firewall.ssh,
    google_compute_firewall.http-server
  ]
}

// return the public ip of created instance
output "ip" {
  value = "${google_compute_instance.default.network_interface.0.access_config.0.nat_ip}"
}

3. Demo

Once the scripts are created successfully run the below terraform commands from the project root directory to create the infrastructure in the google cloud environment under the virtual machine service.

Commands

-- Step 1. to initialize the terraform in the repo
terraform init

-- Step 2. to plan the infrastructure based on the resources specified in the terraform file
terraform plan

-- Step 3. to apply the infrastructure to the google cloud environment
terraform apply

Once step 3 is executed the resource will be created in the environment as shown below. Some information from the picture is hidden due to security reasons.

Fig. 1: Virtual machine in gcp

Once the resource is created in the cloud and verified I recommend deleting the resource to save yourself from unwanted pricing. For deleting the resource we will use the delete command.

Command

-- Step 4: delete the created resource from the environment.
terraform delete

That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

4. Summary

In this tutorial, we learned the introduction to terraform basics and created a terraform script for creating a virtual machine in the google cloud. You can download the terraform scripts used in this tutorial from the Downloads section.

5. Download the terraform scripts

This was a tutorial on creating a virtual machine in google via terraform scripts.

Download
You can download the full source code of this example here: Creating a virtual machine with Terraform in GCP

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button