0
0
TerraformHow-ToBeginner · 3 min read

How to Use Tuple Variable in Terraform: Syntax and Examples

In Terraform, you define a tuple variable using variable block with type = tuple([...]) specifying the types of each element. You can then access tuple elements by index in your configuration using var.variable_name[index].
📐

Syntax

A tuple variable in Terraform is declared inside a variable block with the type set to tuple. You specify the exact types of each element in the tuple inside square brackets. For example, tuple([string, number, bool]) means the tuple has three elements: a string, a number, and a boolean.

You access tuple elements by their index starting at 0, like var.my_tuple[0] for the first element.

terraform
variable "my_tuple" {
  type = tuple([string, number, bool])
  default = ["hello", 42, true]
}
💻

Example

This example shows how to declare a tuple variable and use its elements in a Terraform resource. The tuple contains a string, a number, and a boolean. We print each element using output blocks.

terraform
variable "example_tuple" {
  type = tuple([string, number, bool])
  default = ["Terraform", 2024, false]
}

output "first_element" {
  value = var.example_tuple[0]
}

output "second_element" {
  value = var.example_tuple[1]
}

output "third_element" {
  value = var.example_tuple[2]
}
Output
first_element = "Terraform" second_element = 2024 third_element = false
⚠️

Common Pitfalls

Common mistakes when using tuple variables include:

  • Not specifying the exact types in the tuple, which causes errors.
  • Trying to access tuple elements with keys instead of indexes.
  • Assigning a list with wrong element types to the tuple variable.

Always ensure the tuple elements match the declared types and use numeric indexes to access them.

terraform
variable "wrong_tuple" {
  type = tuple([string, number])
  default = ["text", "not a number"]  # Wrong: second element should be a number
}

# Correct usage:
variable "correct_tuple" {
  type = tuple([string, number])
  default = ["text", 123]
}
📊

Quick Reference

ConceptDescriptionExample
Declare tuple variableUse variable block with type tuple([...])variable "t" { type = tuple([string, number]) }
Assign defaultProvide a list matching tuple typesdefault = ["text", 10]
Access elementUse zero-based indexvar.t[0]
Type mismatch errorOccurs if element types differdefault = ["text", "wrong"]

Key Takeaways

Define tuple variables with exact element types using tuple([...]) in Terraform.
Access tuple elements by numeric index starting at zero.
Ensure assigned values match the declared tuple types exactly.
Avoid using keys or wrong types when working with tuples.
Use outputs to verify tuple variable values during development.