How to Use Number Variables in Terraform: Simple Guide
In Terraform, you define a number variable using
variable block with type = number. You can then reference this variable in your configuration by using var.variable_name to use numeric values in your infrastructure code.Syntax
To declare a number variable in Terraform, use the variable block with type = number. You can optionally set a default value or leave it to be provided during runtime.
- variable "name": declares the variable name.
- type = number: specifies the variable holds numeric values.
- default: optional default numeric value.
Use the variable in your Terraform code by referencing var.name.
terraform
variable "instance_count" { type = number default = 3 } resource "aws_instance" "example" { count = var.instance_count ami = "ami-12345678" instance_type = "t2.micro" }
Example
This example shows how to declare a number variable and use it to set the number of AWS EC2 instances to create.
terraform
variable "instance_count" { type = number default = 2 } provider "aws" { region = "us-east-1" } resource "aws_instance" "example" { count = var.instance_count ami = "ami-0c55b159cbfafe1f0" instance_type = "t2.micro" } output "created_instances" { value = aws_instance.example.*.id }
Output
Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
Outputs:
created_instances = ["i-0abcd1234efgh5678", "i-0abcd1234efgh5679"]
Common Pitfalls
Common mistakes when using number variables include:
- Not specifying
type = number, which can cause Terraform to treat the variable as a string. - Passing string values instead of numbers when providing variable input.
- Using number variables in places expecting strings without conversion.
Always ensure numeric inputs are numbers, not quoted strings.
terraform
variable "wrong_number" { default = "3" # Incorrect: string instead of number } variable "correct_number" { type = number default = 3 }
Quick Reference
| Concept | Example | Description |
|---|---|---|
| Declare number variable | variable "count" { type = number } | Defines a variable that holds a number. |
| Set default value | default = 5 | Provides a default number if none is given. |
| Reference variable | count = var.count | Uses the number variable in resource configuration. |
| Input number value | terraform apply -var='count=4' | Passes a number value during apply. |
Key Takeaways
Declare number variables with type = number to ensure numeric handling.
Reference number variables using var.variable_name in your Terraform code.
Avoid passing numbers as quoted strings to prevent type errors.
Use default values to provide fallback numbers for variables.
Pass number variables at runtime with -var flag for flexible configuration.