DEV Community

Cover image for Day 5/30: The Power of Variables – DRY Principles & Precedence πŸ”„πŸ—οΈ
GOKULPRASATH N
GOKULPRASATH N

Posted on

Day 5/30: The Power of Variables – DRY Principles & Precedence πŸ”„πŸ—οΈ

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!

AWS #Terraform #CloudEngineering #DevOps #InfrastructureAsCode #techtutorialswithpiyush #TheCloudOpsCommunity

30daysofAWSTerraform

Top comments (0)