Terraform Notes

January 4, 2020

The following are some of my notes when refreshing some terraform knowledge. Terraform is a great way of keeping track of your infrastructure as code. Making it easy to keep track and push changes to your infrastructure. I used the following YouTube video for the refresher:

Best Practices of Infrastructure as Code with HashiCorp Terraform

When Planning Changes

  • Always terraform plan before destroying or applying (just to be safe).

+: Resource will be created

-: Resource will be destroyed

~: Resource will be updated in-place

-/+: Resources will be destroyed and re-created

For something like -/+, it is good to make sure it is not for something like a DB.

Good To Do

  • It is preferable to have your state remote.
  • Its really good practice (and you should do this) to version remote state.

Good To Know

  • A terraform revert is not specifically a revert. It is more of an apply of a specific state version.
  • Sometimes a terraform revert will not save you. You may have to completely destroy and re-do.
  • There is a Kubernetes provider!
  • If you need secrets, using environment variables is a good choice. They can be sourced from a file and set in the process.
  • You can use outputs to references resources that are in other terraform modules.
  • Make sure to enable Versioning in your remote backend for state.

Scaling Challenges

Multiple Environments

Using terraform workspace you can isolate states for different environments (prod, stage, dev). This is good for preventing state contamination.

cd dev
terraform workspace dev
terraform init
terraform plan
terraform apply

Duplicate Code

Use modules to structure the code (similar to kustomize). You can pass variables to the modules to make sure they are different when referenced by different bases.

Ball of Mud Config (300 resources in one)

Using Datasources can help with this issue. This issue tends to happen on mono-repos.

Upgrades

  • Once you upgrade terraform you can’t go back!

To make upgrades easier:

  • Pinning provider versions
  • Use known functions and not using creative hacks. Using creating hacks can come to bite you in the future.
  • Decoupling configs across providers. For example separate Kubernetes from GCP.
  • Avoid provisioners.