Get Comfortable in the Console First
The most important thing for a Terraform beginner is to get comfortable staying in the console for a period of time. I say it that way because I learned Terraform before AWS — and that was a mistake.
Two days into learning Terraform, I made the decision to pick up AWS first. When I looked at the Terraform code, I didn't understand anything. So I stayed in the console learning how to set up a VPC, EC2, and security groups manually.
When I tried to deep dive into AWS, everyone was showing the same architecture: one VPC, one public subnet, one private subnet, an EC2 inside the VPC, and a NAT gateway to enable internet access to the private subnet. That's when I knew I was ready to go back to Terraform.
File Structure — Don't Put Everything in One File
You can put everything under one file, e.g. main.tf. The problem is the file might get too crowded to review. So it needs to be broken down into multiple files:
- main.tf — main config, where your resources live
- provider.tf — file to declare which cloud you are using, or maybe Cloudflare to add a CNAME record
- output.tf — file that will show the output after you provision the resource
- backend.tf — people use S3 bucket as their state backend, but using HCP Terraform is a best practice
- variable.tf — file that defines real values to be called in
main.tf
You can refer to this as your reference: github.com/iqbalhakims/infra-myblog
Modules — Apply the DRY Principle
You can also use modules to apply the DRY (Don't Repeat Yourself) principle. Modules are often written by experienced people who publish their files for others to reuse. This can save you a lot of time since modules are reusable and battle-tested.
You can also create custom modules as long as you know what you are doing.
Learn the console first — once you understand what you're building, Terraform starts to make a lot more sense.