DEV Community

Cover image for Terraform: Conditional Expressions, Dynamic Blocks, and Splat Expressions
Sainath Patil
Sainath Patil

Posted on • Edited on

Terraform: Conditional Expressions, Dynamic Blocks, and Splat Expressions

If you want to write Terraform configurations that are clean,
want to follow DRY principle,
want to scale across environments,
You must understand three powerful features:

  • conditional expressions,
  • dynamic blocks,
  • and splat expressions.

  • Conditional Expressions (Smart decisions)

A conditional expression lets you return one value when a condition is true and another when it’s false.
Example:

  • If this is a dev environment, do X; otherwise, do Y.
resource "aws_instance" "app" {
  ami           = "ami-123456"
  instance_type = var.env == "prod" ? "t3.large" : "t3.micro"
}
Enter fullscreen mode Exit fullscreen mode

use when:

  • Per-environment configurations

  • Enabling/disabling features

  • Region-specific values


  • Dynamic Blocks (Generate repeating blocks)

Sometimes you need multiple nested blocks inside a resource, like several security group rules or EBS volumes.
Writing them manually leads to bulky, repetitive code.
Example:

variable "ingress_rules" {
  type = list(object({
    port        = number
    description = string
  }))
}

resource "aws_security_group" "app_sg" {
  name = "app-sg"

  dynamic "ingress" {
    for_each = var.ingress_rules
    content {
      from_port   = ingress.value.port
      to_port     = ingress.value.port
      protocol    = "tcp"
      cidr_blocks = ["0.0.0.0/0"]
      description = ingress.value.description
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

when to use:

  • Security groups

  • IAM policy statements

  • Route table entries

  • Load balancer listeners


  • Splat Expressions (Extract Values)

Splat expressions let you extract an attribute from every element in a list.
This is perfect when you’re working with multiple resources created using count or for_each.
Example:

resource "aws_instance" "servers" {
  count         = 3
  ami           = "ami-123456"
  instance_type = "t3.micro"
}

output "instance_ids" {
  value = aws_instance.servers[*].id
}

**when to use**
- Getting subnet IDs

- Listing private/public IPs
Enter fullscreen mode Exit fullscreen mode

Conclusion
Mastering conditional expressions, dynamic blocks, and splat expressions is a big part of leveling up your Terraform skills. Once you start using them effectively, your code becomes:

  • More reusable

  • Easier to maintain

  • Less repetitive

  • Better structured for multi-environment setups

Top comments (0)