How to Use Set Variable in Terraform: Syntax and Examples
In Terraform, you define a
set variable using the variable block with the type set(string) or other types. You assign values as a list or set, and Terraform treats them as unique unordered collections. Use var.variable_name to access the set in your configuration.Syntax
To declare a set variable in Terraform, use the variable block with type = set(element_type). This tells Terraform the variable holds a unique collection of elements of the specified type.
You can assign values as a list or set in terraform.tfvars or inline defaults.
- variable: declares the variable
- type: specifies the data type as a set
- default: optional default values
terraform
variable "example_set" { type = set(string) default = ["apple", "banana", "cherry"] }
Example
This example shows how to declare a set variable, assign values, and use it in a resource to create tags.
terraform
variable "allowed_ips" { type = set(string) default = ["10.0.0.1", "10.0.0.2"] } resource "aws_security_group" "example" { name = "example-sg" description = "Allow access from allowed IPs" ingress { from_port = 22 to_port = 22 protocol = "tcp" cidr_blocks = var.allowed_ips } }
Output
Terraform will create a security group allowing SSH access from 10.0.0.1 and 10.0.0.2 IP addresses.
Common Pitfalls
Common mistakes when using set variables include:
- Using
listtype instead ofsetwhen uniqueness is needed. - Assigning duplicate values which are automatically removed in sets but may cause confusion.
- Trying to access set elements by index, which is invalid because sets are unordered.
Always remember sets do not preserve order and do not allow duplicates.
terraform
variable "wrong_type" { type = list(string) default = ["apple", "apple", "banana"] } variable "correct_set" { type = set(string) default = ["apple", "apple", "banana"] } # Accessing by index (wrong): var.correct_set[0] # This will cause an error # Correct usage: iterate or check membership
Quick Reference
Remember these tips when using set variables in Terraform:
- Use
set(type)to declare unique collections. - Sets do not keep order; do not rely on element positions.
- Assign values as lists or sets; duplicates are removed automatically.
- Access sets by iteration or membership checks, not by index.
Key Takeaways
Declare set variables with type = set(element_type) to hold unique unordered values.
Assign values as lists or sets; Terraform removes duplicates automatically.
Do not access set elements by index because sets are unordered.
Use set variables to enforce uniqueness in collections like IP addresses or tags.
Iterate over sets or check membership instead of relying on order.