0
0
TerraformHow-ToBeginner · 3 min read

How to Use Variables in Terraform: Simple Guide

In Terraform, you use variable blocks to define variables and reference them with var.variable_name. This lets you customize your infrastructure without changing the code directly.
📐

Syntax

A variable block defines a variable with a name, optional type, default value, and description. You use var.variable_name to access its value in your configuration.

  • variable "name": declares the variable's name.
  • type: (optional) sets the data type like string, number, bool, or list.
  • default: (optional) provides a default value if none is given.
  • description: (optional) explains the variable's purpose.
terraform
variable "example" {
  type        = string
  default     = "hello"
  description = "An example variable"
}

resource "null_resource" "test" {
  triggers = {
    message = var.example
  }
}
💻

Example

This example shows how to define a variable and use it in a resource. You can override the default value by passing a value when running Terraform.

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

provider "aws" {
  region = var.region
}

resource "aws_s3_bucket" "example" {
  bucket = "my-unique-bucket-12345"
  acl    = "private"
}
Output
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
⚠️

Common Pitfalls

Common mistakes include not defining variables before use, forgetting to pass values when no default exists, or using wrong types. Also, avoid hardcoding values instead of using variables to keep code flexible.

terraform
/* Wrong: Using variable without declaration */
resource "null_resource" "fail" {
  triggers = {
    message = var.undefined_var
  }
}

/* Right: Declare variable first */
variable "defined_var" {
  type    = string
  default = "value"
}

resource "null_resource" "success" {
  triggers = {
    message = var.defined_var
  }
}
📊

Quick Reference

ConceptDescriptionExample
variable blockDefines a variablevariable "name" { type = string }
var.variable_nameAccess variable valueregion = var.region
defaultSets default valuedefault = "us-west-1"
typeSpecifies variable typetype = number
descriptionExplains variable usedescription = "AWS region"

Key Takeaways

Define variables with the variable block to make your Terraform code flexible.
Access variables using var.variable_name inside your configuration.
Always provide a default or pass a value to avoid errors.
Use types and descriptions to make variables clear and safe.
Avoid hardcoding values; use variables for reusable infrastructure.