Today marks Day 5 of my #30daysofAWSTerraform challenge! π I moved beyond hardcoding values and explored Terraform Variables, a game-changer for writing reusable, clean, and scalable Infrastructure as Code.
By extracting values like Region, AMI IDs, and Instance Types into variables.tf, I learned how to deploy the exact same infrastructure across Dev, Staging, and Prod without rewriting a single line of the main configuration.
β
Tasks Completed:
Input Variables: Created a variables.tf file to define reusable inputs (e.g., variable "instance_type") with default values and type constraints (String, Number, Bool).
Code Refactoring: Updated main.tf to replace hardcoded strings with var., making the code modular.
Variable Precedence: Experimented with different ways to assign values (CLI flags, Environment Variables, terraform.tfvars, Default values) and learned the order of precedence (CLI > tfvars > Env Var > Default).
Locals: Used locals block to perform intermediate calculations (e.g., combining resource names with project IDs) to avoid repetition inside resources.
Output Variables: Defined outputs.tf to print useful information (like the EC2 Public IP) to the console after terraform apply finishes.
π Notes:
DRY Principle: "Don't Repeat Yourself." If you copy-paste a value more than twice, turn it into a variable.
Security: Never commit terraform.tfvars if it contains sensitive secrets (add it to .gitignore!).
Type Safety: Always define type = string or type = number to catch errors early during terraform plan rather than failing mid-deployment.
π Resources:
Video I watched: https://youtu.be/V-2yC39BONc?si=LmmQmXKh16BKAi2d
Mentor: Piyush Sachdeva
I am excited to learn about File Structure tomorrow to organize my growing code base!
Top comments (0)