Terraform Setup

Terraform Setup #

Project Directory Structure #

The typical Terraform project directory looks like this:

<project>
  - main.tf
  - provider.tf
  - variables.tf
  - terraform.tfvars
  - <GCP authentication key>.json

main.tf #

This is where most of the Terraform code goes.

By convention, resource defines the resource API that Terraform will call. This is followed by the name of the resource that will internally be utilized by Terraform – note that this is different from the name that is used by the actual cloud resource, which is typically defined right below.

# Bucket for storage

resource "<cloud service>" "<name>" { # where cloud service might be something like google_storage_bucket
    provider = # if there's just one provider specified in provider.tf, like only GCP, this is optional
    name = "<some globally unique bucket name>"
    location = "US" # or some country
}

# More stuff for code to do goes down here...

main.tf can also handle access controls.

resource "<resource>" "<name>" {
  object = <resource>.name # "name" so we don't have to hard-cord anything
  ...
  role = "READER" # other other types of roles
  entity = "AllUsers" # who can access it? "AllUsers" is fully public and anyone can access it.
}

provider.tf #

Recommended place to place code for cloud provider, such as GCP.

# GCP Provider

provider "google" (
    credentials = file(var.gcp_svc_key) # service account for authentication. This points at the Key file in the Terraform project directory. Specific path is definied in a *.tfvars file.
    project = var.gcp_project_id
    region = var.gcp_regcion
)

var is a variable, allows us to not hard-code values. This is stored in the variables file.

variables.tf #

Define variables for the Terraform project here.

variable "<key name>" {

}

# an example with specific values
...

The specific variable values can be defined in a *.tfvars file, such as the immediate next section below for terraform.tfvars

Note: We’ll have a different *.tfvars file for each of Dev and Prod developments

terraform.tfvars #

gcp_svc_key = "../<authentication key>.json" 
gcp_project = "<GCP project ID>"
gcp_region = "us-east-1" # or another region

Note that gcp_svc_key is referenced in the provider.tf file.

Authentication Key #

Remember the key downloaded from creating a GCP IAM service account? Drop that in the root of the project (maybe? this feels potentially risky. Let’s revisit this point.)