blog
Create a VM using Terrafo ...
30 August 22

Create a VM using Terraform on GCP

Posted byINE
facebooktwitterlinkedin
news-featured

In our lab walkthrough series, we go through selected lab exercises on our INE Platform. Subscribe or sign up for a 7-day, risk-free trial with INE and access this lab and a robust library covering the latest in Cyber Security, Networking, Cloud, and Data Science!

Purpose: Terraform is an infrastructure as code tool that lets you define both cloud and on-prem resources in human-readable configuration files that you can version, reuse, and share. In this article, you will learn how to create a Virtual Machine Using Terraform on Google Cloud Platform.

Technical difficulty:

|   Novice   |   Beginner   |   Competent   |   Proficient   |   Expert

Lab Scenario

We have set up the below scenario in our INE labs for our students to practice. The screenshots have been taken from our online lab environment.

Lab Link: Create a VM using Terraform on GCP

Objective

In this lab, you will use Terraform to create an Ubuntu 20.04 virtual machine of type e2-micro.

Solution

Note: You need to have Google Cloud SDK and Terraform installed on your local machine.

Step 1: Choose the Start lab button and then choose Open lab. On the next page, agree to the terms and conditions and select Continue.

You will be presented with access credentials, as shown in the following example. Open the GCP Portal Login link in a new private window or Incognito window.

cvtg2.png

Step 2: Configure the Google Cloud Account with your local machine.  

Use your local terminal or PowerShell to run the following command.

Command:

gcloud init

After running this command, a new browser window will open. Log in using the same credentials you were given after you started this lab.

Step 3: Download Service Account Key and save it in a file named "terraform-gpc.json"

To download the service account key first, we need to login into the Google cloud platform and then select the project as shown below:

cvtg3.png

Now click on the hamburger menu, select IAM and Admin option, and inside that, select the service account option as shown below:

cvtg4.png

Now click on the service account as shown below:

cvtg5.png

Select the "Keys" option and click on "Create new key". Now to generate the JSON file, select JSON and click on create. The JSON file will be downloaded to your local machine.

Save that file with the name "terraform-gcp.json" in your terraform project folder.

Step 4: Find access token

To find the access token. First, you need to login to Google Cloud Shell with the same credentials by clicking on the following link- https://shell.cloud.google.com/?pli=1&show=ide%2Cterminal and then run:

Command:

gcloud beta auth application-default print-access-token

Now copy and store the access token somewhere for future reference.

Step 5: Create a new variables.tf file

Create a file with the name "variables.tf" in your terraform folder and paste the below-mentioned code into it.

Code:

variable "region" {
    type = string
    default = "us-central1"
}
variable "project" {
    type = string
    default = <project_id> 
}
variable "access_token" {
    type = string
    default = <access_token>
}
variable "email" {
    type = string
    default = <client_email>
}
variable "privatekeypath" {
    type = string
    default = "~/.ssh/id_rsa"
}
variable "publickeypath" {
    type = string
    default = "~/.ssh/id_rsa.pub"
}

Go to the terraform-gcp.json file, copy "project_id", and paste its value into the default attribute of the "project" block.

Copy the access token value we stored earlier and navigate to the "access_token" block to assign that value to the default attribute. Search for "client_email" in the terraform-gcp.json file and assign the value to the default attribute in the "email" block.

Step 6: Create a main.tf file

In this step, you will define a virtual machine with the following specifications:

  • Os : ubuntu

  • Resource group :  inelabs-43882753

  • Name :  DemoVm

  • Machine type = "e2-micro"

  • Admin username of the machine : root

  • Admin password of the machine : password@54321@123@@

Create a directory. In this directory, create a file and save it as main.tf. This is the main configuration file where you will define the resources for your virtual machine.

In your main.tf file, copy and paste the following code.

Code:

provider "google" {
  project = var.project
  region  = var.region
  access_token = var.access_token
}
resource "google_compute_firewall" "firewall" {
  name    = "gritfy-firewall-externalssh"
  network = "default"
  allow {
    protocol = "tcp"
    ports    = ["22"]
  }
  source_ranges = ["0.0.0.0/0"] # Not So Secure. Limit the Source Range
  target_tags   = ["externalssh"]
}
resource "google_compute_firewall" "webserverrule" {
  name    = "gritfy-webserver"
  network = "default"
  allow {
    protocol = "tcp"
    ports    = ["80","443"]
  }
  source_ranges = ["0.0.0.0/0"] # Not So Secure. Limit the Source Range
  target_tags   = ["webserver"]
}
# We create a public IP address for our google compute instance to utilize
resource "google_compute_address" "static" {
  name = "vm-public-address"
  project = var.project
  region = var.region
  depends_on = [ google_compute_firewall.firewall ]
}
resource "google_compute_instance" "dev" {
  name         = "demovm"
  machine_type = "e2-micro"
  zone         = "${var.region}-a"
  tags         = ["externalssh","webserver"]
  boot_disk {
    initialize_params {
      image = "ubuntu-os-cloud/ubuntu-2004-lts"
    }
  }
  network_interface {
    network = "default"
    access_config {
      nat_ip = google_compute_address.static.address
    }
  }
  # Ensure firewall rule is provisioned before server, so SSH doesn't fail.
  depends_on = [ google_compute_firewall.firewall, google_compute_firewall.webserverrule ]
  metadata_startup_script = "echo 'root:password@54321@123@@' | chpasswd;echo 'PasswordAuthentication yes' >> /etc/ssh/sshd_config;echo 'PermitRootLogin yes' >>  /etc/ssh/sshd_config"
}
output "ad_ip_address" {
  value = google_compute_address.static.address
}

Save the main.tf file.

Step 7: Deploy your infrastructure on Terraform

To initialize the working directory that you created that contains the Terraform configuration file.

Command:

terraform init
cvtg6.png

Terraform lets you preview the actions it will perform before you deploy them. To preview the actions, run the following command:

cvtg7.pngcvtg8.png

To have Terraform create the resources, run:

Command:

terraform apply

If you are getting the error as shown in the below image, then you need to generate a new access token and update the access token's value in variables.tf file.

cvtg9.png

To get a new access token run the below mentioned command on the Google Cloud Shell.

Command:

gcloud beta auth application-default print-access-token

If terraform apply command gets successfully executed, then you should see the following output:

cvtg10.png

At the prompt, enter yes.

At last, you will get this output, and VM will get created on the Google Cloud Platform:

cvtg11.png

Now the deployment is completed, you can see the resources that Terraform created in the Google Cloud Platform.

Step 8: Verify the resources creation.

Go to the Google Cloud Platform, Compute Engine, and click on VM Instances.

cvtg12.png

After clicking on VM Instances, you can see the VM that we just deployed using Terraform:

cvtg13.png

Step 9: To finish the lab, you need to destroy all the resources that Terraform created.

Command:

terraform apply -destroy

Before that, you need to generate a new access token. 

Command:

gcloud beta auth application-default print-access-token

Copy the access token, navigate to the "variables.json" file, and update the value of the default attribute. You can now run the terraform apply -destroy command to delete the resources we just created.

You should see the following after running the terraform apply -destroy command:

cvtg14.png

Go to the Google Cloud Platform and confirm that there are no longer any Instances in the VM Instances:

cvtg15.png


You can see the resource that we just deleted no longer exists.

Conclusion

In this lab, you used Terraform to create and delete a virtual machine on the Google Cloud Platform.

To perform this task on your own, subscribe or sign up for a 7-day, risk-free trial with INE to access this lab and a robust library covering the latest in Cyber Security, Networking, Cloud, and Data Science!

Need training for your entire team?

Schedule a Demo

Hey! Don’t miss anything - subscribe to our newsletter!

© 2022 INE. All Rights Reserved. All logos, trademarks and registered trademarks are the property of their respective owners.
instagram Logofacebook Logotwitter Logolinkedin Logoyoutube Logo