0
0
TerraformHow-ToBeginner · 3 min read

How to Set Default Value for Variable in Terraform

In Terraform, you set a default value for a variable by adding the default argument inside the variable block. This default value is used when no other value is provided during Terraform runs.
📐

Syntax

The variable block defines a variable in Terraform. Inside it, the default argument sets the default value for that variable. If no value is provided externally, Terraform uses this default.

  • variable "name": declares the variable name.
  • type: (optional) defines the variable data type.
  • default: sets the default value used if no override is given.
  • description: (optional) explains the variable purpose.
terraform
variable "example_variable" {
  type    = string
  default = "default_value"
  description = "This is an example variable with a default value."
}
💻

Example

This example shows a Terraform configuration with a variable that has a default value. When you run Terraform without providing a value, it uses the default. You can override it by passing a value in a terraform.tfvars file or via command line.

terraform
variable "region" {
  type    = string
  default = "us-west-2"
  description = "AWS region to deploy resources"
}

provider "aws" {
  region = var.region
}

resource "aws_s3_bucket" "example" {
  bucket = "my-example-bucket-12345"
  acl    = "private"
}
Output
Terraform will deploy the S3 bucket in the us-west-2 region if no other region is specified.
⚠️

Common Pitfalls

Common mistakes include:

  • Not setting a default value and not providing a value externally, causing Terraform to prompt for input.
  • Setting a default value with the wrong data type, which causes errors.
  • Overriding defaults unintentionally by passing empty or incorrect values.

Always ensure the default value matches the declared type and that you provide values when needed.

terraform
variable "count" {
  type = number
  default = "five" # Incorrect: default should be a number, not a string
}

# Correct version:
variable "count" {
  type = number
  default = 5
}
📊

Quick Reference

ArgumentDescriptionRequired
defaultSets the default value for the variableNo
typeSpecifies the variable data type (string, number, bool, list, map, etc.)No but recommended
descriptionDescribes the variable purposeNo

Key Takeaways

Use the default argument inside a variable block to set a fallback value.
Default values prevent Terraform from prompting for input when no value is provided.
Ensure the default value matches the declared variable type to avoid errors.
You can override defaults by passing values via tfvars files or command line.
Providing descriptions helps clarify variable purpose for users.