How Do You Use Terraform to Create a Server in GCP?

Problem scenario
You want to use infrastructure as a code with Terraform and GCP. How do you use a .tf file to create a virtual machine in Google Cloud Platform?

Solution
Prerequisite

This assumes you have installed Terraform. If you need assistance with this, see this posting.

Procedures

1. Obtain the account.json file for your GCP account. Log into GCP, and then go here: https://console.cloud.google.com/apis/credentials/serviceaccountkey
For the "Service Account" drop down menu, choose "Computer Engine default service account." Then for "Key Type" click on the option for "JSON". Click "Create".

2. On the Linux server with Terraform, save the file as account.json in the file you will create a .tf file.

3. Mentally identify the project ID of an existing project. If you want to find the ID of your project, from the GCP web UI, go to "My First Project" or something similar at the top middle part of the screen. Click on it. The pop up should show the project IDs according to their names.

4. Create in this directory a file called test.tf with these lines (but replace projectID-asfoundinstep3above with your project ID):

provider "google" {
  credentials = "${file("account.json")}"
  project     = "projectID-asfoundinstep3above"
  region      = "us-east1"
  zone        = "us-east1-b"
}

resource "google_compute_instance" "coolname" {
  name          = "verycoolserver"
  machine_type  = "n1-standard-1"
  zone          =  "us-east1-b"
  tags          = ["ssh","http"]
  boot_disk {
    initialize_params {
      image     =  "centos-7-v20180129"
    }
  }

network_interface {
    subnetwork = "default"
    access_config {
    }
  }
}

5. Run these commands:

terraform init
terraform apply

6. Respond with "yes" to the prompt. Your server should be created.

Leave a comment

Your email address will not be published. Required fields are marked *