Create a VM using Terrafo ...
    30 August 22

    Create a VM using Terraform on GCP

    Posted byINE

    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


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


    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.


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

    Use your local terminal or PowerShell to run the following 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:


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


    Now click on the service account as shown below:


    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- and then run:


    gcloud beta auth application-default print-access-token

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

    Step 5: Create a new file

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


    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/"

    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 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 This is the main configuration file where you will define the resources for your virtual machine.

    In your file, copy and paste the following 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 = [""] # 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 = [""] # 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 file.

    Step 7: Deploy your infrastructure on Terraform

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


    terraform init

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


    To have Terraform create the resources, run:


    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 file.


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


    gcloud beta auth application-default print-access-token

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


    At the prompt, enter yes.

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


    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.


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


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


    terraform apply -destroy

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


    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:


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


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


    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!

    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