A simple Terraform demo on GCP.
In a real life project, this code would sit in a folder within your project, perhaps under infra or similar.
For CI/CD, part of it could be triggered by (say) github action or similar.
Credits: DE Zoomcamp, Youtube
-
Install Terraform locally. For Mac OS:
brew tap hashicorp/tap brew install terraform # update to latest version brew update brew upgrade hashicorp/tap/terraform
To verify is all good, try:
terraform -help
-
A GCP service account
terraform-runner
with permissions: BigQuery Admin, Compute Admin & Storage Admin. Add its json key under underkeys/terraform-runner-gcp.json
.- If you are running Terraform from your workstation, you can also use
gcloud
and authenticate using User Application Default Credentials ("ADCs") as a primary authentication method. You can enable ADCs usinggcloud auth application-default login
. See also Google provider configuration reference
- If you are running Terraform from your workstation, you can also use
-
If authenticating using service account, Terraform will need the path to service account json key:
# Path to service account json key (optional). GOOGLE_CREDENTIALS=keys/terraform-runner-gcp.json
-
run
terraform init
to get the GCP provider.
The following assumes you are working locally to a development project.
-
terraform plan
. Check the plan - in particular the options and defaults of all resources to be created. -
terraform apply
. To deploy. A snapshot of the resources deployed will be stored in aterraform.tfstate
local file.
terraform destroy
The terraform.tfstate
file should be stored on cloud in a place that is secure but also accessible to those in your team with permission to deploy new infrastructure. This may also be a service account triggered by Github, for example. See also this guide for more examples.
-
After every update to the Terraform code, ensure to format as
terraform fmt
. -
Refer to the Terraform Registry for snippets of code; start here for GCP specific content.
-
Terraform provides snippets of code ready to copy and paste. It's worth:
-
Checking with fields are actually required.
-
Use
terraform plan
to double check the defaults are assigned to the properties of the resources.
-
-
variables and default (e.g. resource default region/zone) are defined in
variables.tf
and referred asvar.VAR_NAME
. -
Using environmental variables: Terraform can directly access environment variables that are named using the pattern
TF_VAR_
. Otherwise, use the external data source.