HashiCorp Terraform is a powerful open-source infrastructure automation tool that enables you to provision and manage infrastructure as code. Google has been collaborating with HashiCorp since 2013 to enable customers who use Terraform and other HashiCorp tools to make optimal use of Google Cloud Platform (GCP) services and features.

Google has also invested in creating reusable Terraform modules for common deployment patterns. In this exercise, you will use our networking module to create a custom VPC on GCP. You will then deploy a VM onto the network and connect to it.

What you'll learn

Codelab-at-a-conference setup

If you see a "request account button" at the top of the main Codelabs window, click it to obtain a temporary account. Otherwise ask one of the staff for a coupon with username/password.

These temporary accounts have existing projects that are set up with billing so that there are no costs associated for you with running this codelab.

Note that all these accounts will be disabled soon after the codelab is over.

Use these credentials to log into the machine or to open a new Google Cloud Console window https://console.cloud.google.com/. Accept the new account Terms of Service and any updates to Terms of Service.

Here's what you should see once logged in:

When presented with this console landing page, please select the only project available. Alternatively, from the console home page, click on "Select a Project" :

Start Cloud Shell

While Google Cloud can be operated remotely from your laptop, in this codelab you will be using Google Cloud Shell, a command line environment running in the Cloud.

From the GCP Console click the Cloud Shell icon on the top right toolbar:

It should only take a few moments to provision and connect to the environment. When it is finished, you should see something like this:

This virtual machine is loaded with all the development tools you'll need. It offers a persistent 5GB home directory, and runs on Google Cloud, greatly enhancing network performance and authentication. All of your work in this lab can be done with simply a browser.

Before using Terraform, you must first install it locally. This will enable you to use the terraform CLI.

You could browse to the Terraform website, but this section will teach you how to download, verify, and install Terraform securely. Even though Terraform is downloaded over a TLS connection, it may still be possible for a skilled attacker to compromise the underlying storage system or network transport. For that reason, in addition to serving the binaries over TLS, HashiCorp also signs the checksums of each release with their private key. Thus, to verify the integrity of a download, we must:

  1. Import and trust HashiCorp's GPG public key
  2. Download the Terraform binary
  3. Download the Terraform checksums
  4. Download the Terraform checksum signature
  5. Verify the signature of the checksum against HashiCorp's GPG key
  6. Verify the checksums of the binary against the file

This way, even if an attacker were able to compromise the network transport and underlying storage component, they wouldn't be able to sign the checksums with HashiCorp's GPG key. If this operation is successful, we have an extremely high degree of confidence that the software is untainted.

Since that process can be tedious, we will leverage a Docker container to do it for us. Execute the following command to install Terraform locally. We install Terraform into $HOME/bin because that will persist between restarts on Cloud Shell.

$ docker run -v $HOME/bin:/software sethvargo/hashicorp-installer terraform 0.11.10
$ sudo chown -R $(whoami):$(whoami) $HOME/bin/

Add the bin to our path:

$ export PATH=$HOME/bin:$PATH

Finally, optionally, explore the Terraform CLI help. Do not execute any non-help commands.

$ terraform -h

Add a Terraform config file which handles activating the compute API, setting up networking, and launching a VM on your network.

Download the sample Terraform configuration from GitHub:

$ curl -sSfO https://raw.githubusercontent.com/terraform-google-modules/terraform-google-network/morgante/codelab-hashiconf/codelabs/simple/main.tf

There are a few important sections in this file, which are noted below.

Activate compute API

Because networking is a part of the Google Compute API, you need to make sure the compute API is active on your project before other resources are created. This can be done using the google_project_service resource.

API Configuration

resource "google_project_service" "compute" {
  service = "compute.googleapis.com"

Create the network

A Terraform module is configured to create your global network and configure two subnets in the us-west1 region.

Network Module Configuration

module "vpc" {
  source  = "terraform-google-modules/network/google"
  version = "~> 0.4.0"

  # Give the network a name and project
  project_id   = "${google_project_service.compute.project}"
  network_name = "my-custom-vpc-${random_id.network_id.hex}"

  subnets = [
      # Creates your first subnet in us-west1 and defines a range for it
      subnet_name   = "my-first-subnet"
      subnet_ip     = ""
      subnet_region = "us-west1"

Launch a VM

The Terraform config also includes a single VM and a firewall rule to allow traffic to that VM so you can test that your new network has connectivity to the internet.

VM Configuration

resource "google_compute_instance" "default" {
  name         = "vm-${random_id.instance_id.hex}"
  machine_type = "f1-micro"
  zone         = "us-west1-a"

  # ...

We can now run Terraform. First, initialize Terraform to download the latest version of the Google and Random providers.

$ terraform init

Run a plan step to validate the configuration syntax and show a preview of what will be created.

$ terraform plan

The plan output shows Terraform is going to create 8 resources, including two random_id resources, two google_compute_subnetwork resources, a google_compute_network, a google_project_service, a google_compute_instance, and a google_compute_firewall.

Now execute Terraform apply to apply those changes:

$ terraform apply

You will see output like this:

Plan: 8 to add, 0 to change, 0 to destroy.
Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.
  Enter a value:

Enter "yes" to the prompt. After the apply has finished, you should see an output similar to the following.

Apply complete! Resources: 8 added, 0 changed, 0 destroyed.


ip = <some value here...>

You can now ping the instance, using its public IP.

$ ping $(terraform output ip)
PING ( 56 data bytes
64 bytes from icmp_seq=0 ttl=55 time=141.058 ms
64 bytes from icmp_seq=1 ttl=55 time=141.158 ms
64 bytes from icmp_seq=2 ttl=55 time=140.330 ms
64 bytes from icmp_seq=3 ttl=55 time=140.060 ms

<ctrl+c> to quit

You can also verify the custom VPC exists with gcloud:

$ gcloud compute networks list

default               AUTO         REGIONAL
my-custom-vpc-dfb...  CUSTOM       GLOBAL

That's it! You have successfully created a VPC and VM on Google Cloud.

When you no longer need the infrastructure you created, destroy it using the destroy command.

$ terraform destroy

Just like before, Terraform will prompt you for confirmation:

Plan: 0 to add, 0 to change, 8 to destroy.
Do you really want to destroy all resources?
  Terraform will destroy all your managed infrastructure, as shown above.
  There is no undo. Only 'yes' will be accepted to confirm.
  Enter a value:

Type "yes" and Terraform will destroy the infrastructure.

You learned how to use a module for HashiCorp Terraform to create a network on Google Cloud.

Clean up

If you are done exploring, please consider deleting your project.

Learn More


This work is licensed under a Creative Commons Attribution 2.0 Generic License.