AWS with Terraform (Day 10)
Conditional Expressions, Dynamic Blocks & Splat Expressions Explained
Today’s learning in #30DaysOfAWSTerraform was a complete game-changer in how I think about writing Terraform code. I explored three powerful expression techniques that transform Terraform from repetitive configuration to clean, automated, and scalable Infrastructure-as-Code:
1. Conditional Expressions
2. Dynamic Blocks
3. Splat Expressions
These expressions solve real-world DevOps challenges—avoiding repetitive blocks of code, enabling smart decision-making, and extracting values from multiple resources effortlessly.
Why Terraform Expressions Matter
Many beginners (including me earlier) start by hardcoding values and copy-pasting blocks repeatedly.
This quickly creates problems:
-
Manual edits = mistakes
-
Huge files = hard to read & maintain
-
Different environments = inconsistent results
Expressions fix all of this by making Terraform:
-
More concise
-
More efficient
-
More reusable
-
More scalable for Dev, Staging & Production
1. Conditional Expressions
Used when selecting values based on conditions (similar to if-else).
Example
How it works
-
If environment is
dev→ uset2.micro -
Else → use
t3.micro
Best practice
Store environment input in variables.tf and use conditionals inside resources—not hardcoded values.
2. Dynamic Blocks
Used to dynamically generate nested repeatable resource blocks—especially useful in security groups, IAM policies, scaling rules, etc.
Variable definition
Dynamic block usage
Benefits
✔ No duplicate nested blocks
✔ Easy to add/remove rules
✔ Cleaner code & great for large infra
3. Splat Expressions
Used to collect attributes from multiple resource instances.
Example
Local value
Output
Use case
-
Collect ARNs, IDs, IPs of EC2 instances created with
countorfor_each
Pre-Apply Checklist
| Check | Why |
|---|---|
terraform init | configure backend & plugins |
| Validate variable types | avoid type mismatch errors |
| Balance braces & block syntax | common source of plan failures |
| Use quotes for CIDR | "0.0.0.0/0" |
Use splat expressions for count resources | avoid index errors |
Final Thoughts
Today’s session helped me write cleaner, more professional Terraform code by removing repetition, centralizing logic, and improving scalability. Conditional expressions, dynamic blocks, and splat expressions are essential tools for building reusable Terraform modules and enterprise-grade AWS infrastructure.
Let’s Connect
Here is my repo link for detailed code lines: https://github.com/Mo-Adnan-Mo-Ayyub/Aws-with-Terraform
Here is the session link:
Always open for collaboration, DevOps discussions, and CI/CD & Cloud architecture learning exchanges!
#DevOps #Terraform #AWS #InfrastructureAsCode #CloudEngineering #SRE #30DaysOfAWSTerraform #PiyushSachdeva #HCL #Automation #IaC
Comments
Post a Comment