DEV Community

Nandan K
Nandan K

Posted on

Terraform Variables

Today I learnt variables in detail. Here are some details about it

$ What is variables?

  1. Variables in Terraform are like placeholders that store values.
  2. This makes your code reusable across environments (dev, staging, prod) and teams.

$ Types:

  1. Input variables: a. Input variables are like function parameters - they allow you to customize your Terraform configuration without hardcoding values.

Basic Input Variable Structure:
variable "variable_name" {
description = "What this variable is for"
type = string
default = "default_value" # Optional
}

Eg:

Define in variables.tf

variable "environment" {
description = "Environment name"
type = string
default = "staging"
}

Reference with var. prefix in main.tf

resource "aws_s3_bucket" "demo" {
bucket = var.bucket_name # Using input variable

tags = {
Environment = var.environment # Using input variable
}
}

  1. Output variable: a. Output variables are like function return values - they display important information after Terraform creates your infrastructure.

Basic Output Variable Structure:

output "output_name" {
description = "What this output shows"
value = resource.resource_name.attribute
}

Eg:

Output a resource attribute

output "bucket_name" {
description = "Name of the S3 bucket"
value = aws_s3_bucket.demo.bucket
}

O/P:
bucket_name = "demo-terraform-demo-bucket-abc123"

$ Variable Precedence: (Lowest to Highest)

Using default:

  1. Declare inside the .tf file
  2. Temporarily hide in terraform.tfvars

Eg:
$mv terraform.tfvars terraform.tfvars.backup

$terraform plan

Uses: environment = "staging" (from variables.tf default)

$mv terraform.tfvars.backup terraform.tfvars # restore

Using ENV variables:

  1. Shell environment variable Eg: $export TF_VAR_environment=stage

$terraform plan

Uses environment variable (but command line still wins)

Using terraform.tfvars: (automatically loaded)

  1. Create terraform.tfvars file and add environment = "preprod"

$terraform plan

Uses: environment = "demo" (from terraform.tfvars)

Command Line Override: (highest precedence)

  1. -var or -var-file: declare variables in runtime Syntax: $terraform plan -var="="

Eg:
$terraform plan -var="environment=production"
Or
$terraform plan -var-file="dev.tfvars" # environment = "development"

Precedence: Command line > tfvars > environment vars > defaults

$ Other Types:

Devops #Terraform #AWS

Thanks to Piyush sachdeva

Top comments (0)