π Today I have completed Terraform expression, its types and use cases with practical hands-on.
πWhat is terraform expression?
- Help us to avoid rewriting the code again and again, make configurations dynamic, reusable, and smart.
β Types:
π Conditional expression:
- 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:
π Dynamic Blocks:
- It will used when you want to create repeated nested blocks automatically, instead of writing them manually.
- 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:
- for_each iterates over a list or map
- content defines what each block should contain
- Access values using block_name.value or block_name.key
Eg:
main.tf:
variable.tf:
Output:
π Use Cases:
- Security group rules
- Multiple EBS volumes on EC2 instances
- Route table routes
- IAM policies
- Kubernetes containers
- CloudFront behaviors
- Tags
- Environment variables
π Splat Expression:
- Let's you get a list of values from multiple resources created using count or for_each.
- 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)