Skip to main content

Command Palette

Search for a command to run...

Mastering Terraform Dynamic Blocks, Conditional Expressions & Splat Expressions

Published
4 min read
Mastering Terraform Dynamic Blocks, Conditional Expressions & Splat Expressions

Infrastructure as Code becomes powerful only when it becomes flexible. Today’s learning took me into three of the most essential Terraform expression tools that make configurations smarter, cleaner, and scalable: Conditional Expressions, Dynamic Blocks, and Splat Expressions. These aren’t just features — they are productivity boosters that help you write reusable, environment-aware, and maintainable Terraform code. Here's what I learned and how each of these techniques transforms the way we build cloud infrastructure.


1. Conditional Expressions — Making Terraform Think Before Acting

Conditional expressions allow Terraform to decide what value to use based on a condition.
It works just like the “ternary operator” in general programming:

 resource "aws_instance" "conditional_example" {
   ami           = "ami-0360c520857dsfsde3138f"
   instance_type = var.environment == "prod" ? "t3.large" : "t2.micro"

   tags = var.tags
 }

This simple check helps in avoiding long repeated configurations and makes your Terraform aware of environments like dev, stage, or production.

Real-World Uses

  • Choose smaller EC2 instances in dev but larger in production

  • Enable monitoring only when needed

  • Switch AMIs based on region

  • Apply environment-specific tags

  • Reduce costs by scaling down non-prod resources

Why It Matters

With conditional expressions, I can maintain one clean Terraform module instead of different versions for each environment. It removes guesswork, prevents duplication, and keeps configuration logic crystal clear.

When NOT to use

  • Very complicated logic → better handled using locals

  • Too many environment variations → separate files may be cleaner

  • When all environments must remain uniform


2. Dynamic Blocks — Goodbye Repetitive Code

Dynamic blocks were the highlight of today’s learning.
They let you generate nested blocks programmatically, especially when you have repeating elements like multiple security group rules or multiple EBS volumes.

A typical structure looks like:

   dynamic "ingress" {
     for_each = var.ingress_rules
     content {
       from_port   = ingress.value.from_port
       to_port     = ingress.value.to_port
       protocol    = ingress.value.protocol
       cidr_blocks = ingress.value.cidr_blocks
       description = ingress.value.description
     }
   }

Instead of writing 10 separate ingress blocks, one dynamic block does the job.

Perfect Use Cases

  • Security group ingress/egress rules

  • EC2 instances with multiple EBS volumes

  • Route table routes

  • IAM policy statements

  • Load balancer listeners

  • Any nested structure that repeats

Benefits

  • Eliminates copy-paste code

  • Easy to extend or modify

  • Makes Terraform modules flexible

  • Keeps code DRY (Don’t Repeat Yourself)

  • Works beautifully with lists and maps

Avoid using dynamic blocks when:

  • There's only one static block

  • Overuse makes code harder to read

  • Complex nested dynamic blocks become confusing


3. Splat Expressions — Extract Information Like a Pro

Splat expressions use the [*] operator to extract attributes from multiple resources at once.

Example:

resource "aws_instance" "splat" {
  count = var.instance_count

  ami           = "ami-0360c5208645357e3138f"
  instance_type = "t2.micro"

  tags = {
    Name = "instance-${count.index + 1}"
  }
}

# # Use splat expressions to extract values from all instances
output "name" {
  value = aws_instance.splat[*].id
  }

This returns a list of all EC2 instance IDs created by a resource using count or for_each.

Where They Shine

  • Collecting subnet IDs from a VPC

  • Extracting private IPs of multiple EC2 instances

  • Getting all security group IDs

  • Collecting ARNs from resources

  • Returning lists as outputs

Before learning splat expressions, I would loop manually or create outputs one by one. Now it’s just a single expression. It keeps outputs neat and module usage effortless.


Bringing It All Together — The Real Power

The real impact of today’s learning became clear when I saw how these three concepts complement each other:

  • Conditionals choose which resources or values to apply

  • Dynamic blocks generate structures based on those choices

  • Splat expressions gather all resource data cleanly

Together, they allow you to build:

  • Environment-aware modules

  • Highly configurable network and compute structures

  • Clean, scalable, reusable Terraform codebases

📺 Video That Helped Me Understand this concept


🧠 Final Takeaway

Today’s session reinforced one major idea:

Terraform becomes truly powerful when you let it adapt to your requirements through expressions, instead of writing rigid code.

Conditional expressions add intelligence.
Dynamic blocks add flexibility.
Splat expressions add simplicity.

With these three tools, Terraform configurations become cleaner, smarter, and easier to maintain — especially when managing real-world AWS infrastructure at scale.

More from this blog

B

Build With Rajesh

31 posts