What Is Variable Type in Terraform: Simple Explanation and Example
variable type defines the kind of value a variable can hold, such as string, number, list, or map. It helps Terraform understand what data to expect and ensures your configuration is correct and predictable.How It Works
Think of a variable type in Terraform like a label on a container that tells you what kind of items it holds. For example, if the label says "fruits," you expect apples or bananas, not tools or clothes. Similarly, Terraform uses variable types to know if a variable should hold a single word (string), a number, a list of items, or a map of key-value pairs.
This helps Terraform check your inputs before running your infrastructure setup. If you try to put the wrong kind of data in a variable, Terraform will warn you. This is like making sure you don’t put shoes in a fruit basket. It keeps your setup clean and avoids mistakes.
Example
This example shows how to declare variables with different types in Terraform and how to use them.
variable "region" { type = string default = "us-west-1" } variable "instance_count" { type = number default = 3 } variable "availability_zones" { type = list(string) default = ["us-west-1a", "us-west-1b"] } variable "tags" { type = map(string) default = { Environment = "dev" Project = "demo" } } output "info" { value = { region = var.region instance_count = var.instance_count availability_zones = var.availability_zones tags = var.tags } }
When to Use
Use variable types in Terraform whenever you want to make your infrastructure code clear and safe. They help you avoid mistakes by telling Terraform exactly what kind of data to expect. For example, if you expect a list of server names, use a list(string) type to prevent someone from accidentally passing a single number.
Variable types are especially useful in bigger projects where many people work together or when you reuse code modules. They make your code easier to understand and maintain, like clear instructions on a recipe.
Key Points
- Variable types define what kind of data a variable can hold.
- Common types include
string,number,list, andmap. - They help catch errors early by validating inputs.
- Using types improves code clarity and teamwork.