Running Terraform in Google Cloud Shell
Note
The code for this section is under chap01/cloudshell
in the GitHub repo of this book.
The easiest way to run Terraform in Google Cloud is using Google Cloud Shell, which is a preconfigured development environment accessible through your browser. It comes pre-installed with the latest version of common utilities, including the latest version of Terraform. Furthermore, all authentication is already set up. So, let’s give it a try.
Note
You can check the current version of Terraform using the terraform –
version
command.
If your project is new, and you have not provisioned a virtual machine (VM) (Compute Engine), run the following gcloud
command to enable the compute
API:
$ gcloud services enable compute.googleapis.com
Then place the following code in a file called main.tf
. This is known as the Terraform configuration. Configurations are written in HashiCorp Configuration Language (HCL). HCL is human readable and is used by several HashiCorp tools.
Note
In this book, we will use the term Terraform language to refer to the language in which the configuration files are written.
This book aims to make you proficient in Terraform to write high-quality, reusable code to provision resources in Google Cloud efficiently and securely.
The file’s actual name is arbitrary, but note that the .tf
extension is mandatory. Terraform uses the .tf
extension to identify Terraform configuration files.
main.tf
resource "google_compute_instance" "this" { name = "cloudshell" machine_type = "e2-small" zone = "us-central1-a" boot_disk { initialize_params { image = "debian-cloud/debian-11" } } network_interface { network = "default" } }
Next, run the following two commands:
$ terraform init $ terraform apply
Terraform will ask you where you want to perform these actions, so type in yes
to approve.
Congratulations—you have now provisioned your first server using Terraform! Go to the web console and inspect the compute engine that Terraform has created.
As expected, Terraform created a Debian server named cloudshell
of a machine type e2-small
in the default
network:
Figure 1.1 – Terraform-provisioned server in the web console
Let’s have a more detailed look at how to write Terraform configurations and how Terraform operates.