Simple GCE setup with Terraform

Simple GCE setup with Terraform

Here you will find a Terraform configuration file that will create a single virtual machine in the Google Cloud Engine (GCE) platform using Terraform.

I wanted to run a straightforward experiment in a virtual machine in Google Cloud and I couldn't find a Terraform snippet to get me up & running. The truth is that I had never created a GCE environment myself, so I was not familiar whatsoever with the concepts or how everything was glued together. After some head banging against my keyboard and experimenting with different approaches for the Terraform config file, this is what finally got me in the game:


variable "region" {
  default = "europe-west1-d" // We're going to need it in several places in this config
}
 
provider "google" {
  credentials = "${file("account.json")}"
  project     = "my-project"
  region      = "${var.region}"
}
 
resource "google_compute_instance" "test" {
  count        = 1 // Adjust as desired
  name         = "test${count.index + 1}" // yields "test1", "test2", etc. It's also the machine's name and hostname
  machine_type = "f1-micro" // smallest (CPU & RAM) available instance
  zone         = "${var.region}" // yields "europe-west1-d" as setup previously. Places your VM in Europe
 
  disk {
    image = "debian-7-wheezy-v20160301" // the operative system (and Linux flavour) that your machine will run
  }
 
  network_interface {
    network = "default"
    access_config {
      // Ephemeral IP - leaving this block empty will generate a new external IP and assign it to the machine
    }
  }
}
	
	

For this to work you're going to need:

  1. Service Account Key file.
    This contains your authentication required for Terraform to talk to the Google API.
    You can get it under Google Cloud Platform -> API Manager -> Credentials -> Create Credentials -> Service account key.
    For the Key type field chose JSON. Put the downloaded file right were your Terraform config file is and name it account.json.
  2. Make sure that you have an SSH key setup for your project: Compute Engine -> Metadata -> SSH Keys
  3. Chose a valid machine image and machine type for your VM. Find an up-to-date list of available images here and available types here.
    <rant>This is where I have seen Terraform (or its providers) falling short: they expect you to know what are the valid types for their base image names (already had this issue with not only GCE but also with DigitalOcean, Packet, Triton) so you have to basically create developer accounts all over to get an API token, read through the documentation, get familiar with the concepts, curl all over until you find that name that could be easily listed somewhere else ~_~ </rant>
  4. terraform plan to make sure everything is looking good
  5. terraform apply
  6. Find the IP of the box with terraform show | grep assigned_nat_ip

You're good to go!

Comments
Leave your Comment