DEV Community

Nandan K
Nandan K

Posted on

Terraform Expressions

πŸ“‹ Today I have completed Terraform expression, its types and use cases with practical hands-on.

πŸ“ŒWhat is terraform expression?

  1. Help us to avoid rewriting the code again and again, make configurations dynamic, reusable, and smart.

βœ… Types:

πŸ“Œ Conditional expression:

  1. Evaluates a condition and returns one of two values based on whether the condition is true or false.

Syntax:
Condition ? True_value : false_value

Eg:

Output:

πŸ“Œ Dynamic Blocks:

  1. It will used when you want to create repeated nested blocks automatically, instead of writing them manually.
  2. It’s like a loop (for-each) inside a resource block and will create one block for each item in a list or map.

Syntax:
dynamic "block_name" {
for_each = var.collection
content {
# Block configuration using each.key and each.value
}
}

πŸ” How it works:

  1. for_each iterates over a list or map
  2. content defines what each block should contain
  3. Access values using block_name.value or block_name.key

Eg:
main.tf:

variable.tf:

Output:

πŸŒ€ Use Cases:

  1. Security group rules
  2. Multiple EBS volumes on EC2 instances
  3. Route table routes
  4. IAM policies
  5. Kubernetes containers
  6. CloudFront behaviors
  7. Tags
  8. Environment variables

πŸ“Œ Splat Expression:

  1. Let's you get a list of values from multiple resources created using count or for_each.
  2. It’s like saying β€œgive me this attribute from ALL the resources.”

Syntax:
resource_list[*].attribute_name

Eg:

Gives the instance ids from nandan_ec2 instances.

Refer: https://youtu.be/R4ShnFDJwI8?si=rlAMgR-JZjdd6djf

Thanks to Piyush, The Cloud Community

Top comments (0)