GCP | How to set up and use Terraform for GCP

This tutorial explains how to set-up and configure terraform to provision resources in Google Cloud Platform (GCP).

Terraform is a tool for building, changing, and versioning infrastructure safely and efficiently. You can learn more about terraform at https://developer.hashicorp.com/terraform/docs.

Configuring terraform for GCP

Step 1: Create service account. In order to use Terraform for automating Google Cloud Infra tasks, we need to have service account for GCP authentication, refer steps mentioned in Create Service accounts in GCP to create the service account.

Step 2: Install terraform. Refer steps mentioned in Terraform installation on windows to install terraform on your computer.

Step 3: Create a folder with name terraform.

Step 4: Open cmd and navigate to created terraform folder.

Step 5: Run the below command to initializes a working directory containing Terraform configuration files.

   

  terraform init
   

Step 6: Create new file with name provider.tf in terraform folder.

Step 7: Write below code in provider.tf.

   

  provider "google" {
    #path for GCP service account credentials
    credentials = "Path to service account credentials"
    # GCP project ID
    project     = "My-Project-ID"
    # Any region of your choice
    region      = "My Region"
    # Any zone of your choice      
    zone        = "My Zone
  }
   

Step 8: Create new file with name createvm.tf in terraform folder.

Step 9: Write below code in createvm.tf.

   

  resource "google_compute_instance" "vm_instance" {
    name         = "gcptutorials-tf"
    machine_type = "f1-micro"
  
    boot_disk {
      initialize_params {
        image = "debian-cloud/debian-9"
      }
    }    
    network_interface {       
      network = "default"
      access_config {
      }
    }
  }
   

Step 10: Run the below command to format terraform files.

   

  terraform fmt
   

Step 11: Run the terraform init command.

   

  terraform init
   

Step 12: Run the terraform plan command to check execution plan.

   

  terraform plan
   

Step 13: Run the terraform apply command to provision the resources on GCP.

   

  terraform apply
   

After performing all the steps you should see a VM with name "gcptutorials-tf" in GCP.


Category: GCP