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

Self-paced environment setup

If you don't already have a Google Account (Gmail or Google Apps), you must create one. Sign-in to Google Cloud Platform console (console.cloud.google.com) and create a new project:

Remember the project ID, a unique name across all Google Cloud projects (the name above has already been taken and will not work for you, sorry!). It will be referred to later in this codelab as PROJECT_ID.

Next, you'll need to enable billing in the Cloud Console in order to use Google Cloud resources.

Running through this codelab shouldn't cost you more than a few dollars, but it could be more if you decide to use more resources or if you leave them running (see "cleanup" section at the end of this document).

New users of Google Cloud Platform are eligible for a $300 free trial.

Start Cloud Shell

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

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     = "10.10.10.0/24"
      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.

Outputs:

ip = <some value here...>

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

$ ping $(terraform output ip)
PING 35.233.150.123 (35.233.150.123): 56 data bytes
64 bytes from 35.233.150.123: icmp_seq=0 ttl=55 time=141.058 ms
64 bytes from 35.233.150.123: icmp_seq=1 ttl=55 time=141.158 ms
64 bytes from 35.233.150.123: icmp_seq=2 ttl=55 time=140.330 ms
64 bytes from 35.233.150.123: 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

NAME                  SUBNET_MODE  BGP_ROUTING_MODE  IPV4_RANGE  GATEWAY_IPV4
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

License

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