Best practices
| expected time |
requirements |
| 90 minutes |
A computer with Terraform installed, terraform knowledge. |
Goal: Use the most common best practices
Explanation
Let’s go over a few best practices. Likey you/your company also has best practices. There is time to discuss these.
HashiCorp has a Terraform Style Guide as well, which covers a lot!
Variables
- Use variables. Define them in
variables.tf, assign them in tfvars file, or set them in the environment.
- Set sensitive variables in environment variables.
- Use Terragrunt for environmental differences. (Workspaces can also be used…)
Dependencies
- Pin all used providers and modules in
versions.tf.
- When writing modules, keep the dependency chain as flat/short as possible.
- For air-gapped installations, use terraform-bundle or refer to your local SCM.
State
General
- Use variables for nearly all values. (In other words, write Terraform code like you are writing a Terraform module.)
- Use CI for modules. (and possibly releases)
validate and format (fmt) often.
- Terraform updates frequently, read release notes. You can “watch” a repository in github.
- Use modules over resources in your root repository.
- It’s a good idea to treat all repositories like a module. (variables.tf, output.tf, version.tf)
Modules
- Spend a good amount of time on a README.md.
- Suggest to use this order when writing new modules:
README.md - Define the purpose of the module.
variables.tf - Think about what to ask for.
locals.tf - Your place to map “simple” variables to complex variables.””
output.tf - Consider what to expose.
main.tf - The “logic” for the module.
versions.tf - Pin all dependencies.
providers.tf - All provider specific configuration.
examples/* - Try your module yourself.
LICENSE - Yes, likely a pretty open one like Apache-2.0
.gitignore - terraform.tfstate, terraform.tfstate.backup, .terraform
Assignment
Bonus assignment
Questions
- Do you know what to improve on your code now?
- Do you use other practices worth sharing?
Solution
See here.