DEV Community

ankitgadling
ankitgadling

Posted on

Day 5 - Terraform Variables

Before exploring Terraform variables, let’s first understand what variables are.

A variable is simply something whose value can change. Variables are used to avoid hardcoding, improve reusability, enhance readability, and support modular design. Every programming language uses variables and Terraform is no different.

Terraform also supports variables, and they can be categorized in two ways:

  • Based on purpose
  • Based on value

Terraform Variables

1. Input Variables

Used to pass values into Terraform from users or external sources.

Example:

variable "region" {
  type        = string
  default     = "us-east-1"
  description = "AWS region"
}
Enter fullscreen mode Exit fullscreen mode

2. Output Variables

Used to display or export values after terraform apply.

Example:

output "bucket_name" {
  value = aws_s3_bucket.demo.bucket
}
Enter fullscreen mode Exit fullscreen mode

3. Local Values (locals)

Used to simplify complex or repeated expressions.

Example:

locals {
  env_name = "dev"
}
Enter fullscreen mode Exit fullscreen mode

String Concatenation in Terraform

"${var.env}-bucket"

"${var.env}-bucket-${var.region}"
Enter fullscreen mode Exit fullscreen mode

Terraform Variable Precedence

Terraform loads variables in the following order (LOW to HIGH precedence):

Precedence Source Notes
1 Default values in variables.tf lowest priority
2 Environment variables export TF_VAR_region="us-east-1"
3 terraform.tfvars auto-loaded
4 terraform.tfvars.json auto-loaded
5 **.auto.tfvars / *.auto.tfvars.json* auto-loaded in alphabetical order
6 -var and -var-file CLI flags highest priority

Variable Precedance

Example Environment Variable

export TF_VAR_env="dev"
Enter fullscreen mode Exit fullscreen mode

✔ Example CLI Variable

terraform apply -var="env=dev"
Enter fullscreen mode Exit fullscreen mode

✔ Example CLI Var File

terraform apply -var-file="dev.tfvars"
Enter fullscreen mode Exit fullscreen mode

Example: Creating an S3 Bucket Using env = dev


variables.tf

variable "env" {
  type        = string
  description = "Environment name"
  default     = "dev"
}

variable "region" {
  type    = string
  default = "us-east-1"
}
Enter fullscreen mode Exit fullscreen mode

main.tf

provider "aws" {
  region = var.region
}

resource "aws_s3_bucket" "demo" {
  bucket = "${var.env}-bucket-demo"
}

output "bucket_name" {
  value = aws_s3_bucket.demo.bucket
}
Enter fullscreen mode Exit fullscreen mode

terraform.tfvars (optional)

env = "dev"
Enter fullscreen mode Exit fullscreen mode

Run Commands

terraform init
terraform plan
terraform apply
Enter fullscreen mode Exit fullscreen mode

Resulting Bucket Name

dev-bucket-demo
Enter fullscreen mode Exit fullscreen mode

Top comments (0)