SalvatoreMaraniello / terraform-demo

Quick guide on using Terraform.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Terraform Demo

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

Pre-requisites

  • 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 under keys/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 using gcloud auth application-default login. See also Google provider configuration reference
  • 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.

Development environment

The following assumes you are working locally to a development project.

Deploy new resources:

  • 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 a terraform.tfstate local file.

Destroy resources

  • terraform destroy

Production environment

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.

Way of working

  • 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 as var.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.

More about Terraform...

About

Quick guide on using Terraform.


Languages

Language:HCL 100.0%