How to Define Variables in Terraform: Syntax and Examples
In Terraform, you define a variable using the
variable block with a name and optional attributes like type and default. This lets you reuse values and customize your infrastructure code easily.Syntax
The variable block declares a variable by name. Inside, you can specify:
- type: the kind of value (string, number, bool, list, map)
- default: a fallback value if none is provided
- description: a helpful note about the variable
This structure helps Terraform know what input to expect.
terraform
variable "example_variable" { type = string default = "default value" description = "This is an example variable" }
Example
This example shows how to define a variable and use it in a resource. The variable instance_count controls how many instances to create.
terraform
variable "instance_count" { type = number default = 2 } resource "aws_instance" "example" { count = var.instance_count ami = "ami-0c55b159cbfafe1f0" instance_type = "t2.micro" }
Output
Terraform will create 2 AWS EC2 instances using the specified AMI and instance type.
Common Pitfalls
Common mistakes include:
- Not specifying a
typewhen the variable is complex, causing errors. - Forgetting to provide a value or default, leading to prompts during apply.
- Using incorrect variable references like
variable.instance_countinstead ofvar.instance_count.
terraform
/* Wrong: missing type and default, causes prompt */ variable "region" {} /* Right: specify type and default to avoid prompts */ variable "region" { type = string default = "us-west-2" }
Quick Reference
| Attribute | Description | Example |
|---|---|---|
| type | Defines the variable data type | type = string |
| default | Sets a default value | default = "value" |
| description | Explains the variable purpose | description = "Used for region" |
| sensitive | Hides value in logs | sensitive = true |
Key Takeaways
Define variables in Terraform using the variable block with a name and optional attributes.
Always specify the variable type for clarity and error prevention.
Provide default values to avoid prompts during terraform apply.
Use variables in code with the var. syntax.
Avoid common mistakes like missing types or wrong variable references.