How to Use tomap Function in Terraform: Syntax and Examples
In Terraform, the
tomap function converts a given value into a map type. It is useful when you want to ensure a variable or expression is treated as a map, especially when working with complex or dynamic data structures.Syntax
The tomap function takes one argument, which is the value you want to convert into a map. The value must be a compatible type like an object or a tuple of pairs.
- tomap(value): Converts
valueto a map.
If the value cannot be converted, Terraform will return an error.
terraform
tomap(value)
Example
This example shows how to convert an object into a map using tomap. It demonstrates how to use the function to ensure the variable is treated as a map type.
terraform
variable "example_object" { default = { name = "Alice" age = 30 } } output "example_map" { value = tomap(var.example_object) }
Output
{
"age" = 30
"name" = "Alice"
}
Common Pitfalls
Common mistakes when using tomap include:
- Trying to convert a list or string directly, which causes errors.
- Passing values that are not objects or tuples of pairs.
- Assuming
tomapchanges the data structure deeply; it only converts the top-level value.
Example of wrong and right usage:
terraform
# Wrong usage: converting a list directly output "wrong_map" { value = tomap(["a", "b"]) } # Right usage: converting a tuple of pairs output "right_map" { value = tomap([ ["a", 1], ["b", 2] ]) }
Output
Error: Incorrect argument type
Outputs:
right_map = {
"a" = 1
"b" = 2
}
Quick Reference
Use tomap to convert compatible values to maps. It works well with objects and tuples of pairs but not with plain lists or strings.
- Input: object or tuple of pairs
- Output: map
- Errors if input is incompatible
| Input Type | Output Type | Notes |
|---|---|---|
| Object | Map | Direct conversion works |
| Tuple of pairs | Map | Pairs become key-value entries |
| List | Error | Cannot convert directly |
| String | Error | Cannot convert directly |
Key Takeaways
Use tomap to convert objects or tuples of pairs into maps in Terraform.
tomap only converts the top-level value and errors on incompatible types like lists or strings.
Always verify the input type before using tomap to avoid runtime errors.
Use tuples of pairs as an alternative to objects when you need to create maps dynamically.