Skip to main content

Using Terraform Variables, Outputs, and Locals

Learn Terraform variables, outputs, locals, expressions, and dynamic blocks by refactoring a hardcoded config into a reusable multi-environment one.

26 Terms

Overview and What You Will Learn

Terraform variables, locals, and outputs turn a hardcoded configuration into a reusable template. Input variables are the parameters callers set, locals are values the module computes for itself, and outputs are the values it returns. With them, the same code deploys dev, staging, and production, and only a small variable file changes.

By the end of this lab you will be able to:

  • Declare input variables with types, defaults, validation, and sensitivity
  • Supply values through tfvars files, environment variables, and flags, and know which one wins
  • Use locals to name expressions once and reuse them
  • Write conditionals, built-in function calls, and for expressions
  • Generate repeated nested blocks with dynamic
  • Expose outputs for people, scripts, and other configurations
  • Refactor a hardcoded configuration end to end

Why This Matters in Production

Without variables, each environment becomes a copy of the code, and every change must be made in each copy. Imagine a trading platform team at a company like Zerodha running the same stack in dev, staging, and production, where only sizes and protection flags differ. One configuration plus a tfvars file per environment means a security group change is made once and reaches all three through the pipeline, with no missed copies.

Core Principles

Values flow in one direction. Sources feed variables, variables and other data feed locals, resources use both, and outputs expose results.

flowchart TD A[tfvars, env vars, flags] -->|set| B[Input variables] B -->|used in| C[Locals] B -->|used in| D[Resources] C -->|used in| D D -->|attributes| E[Outputs] classDef src fill:#DBEAFE,color:#1E293B classDef logic fill:#326CE5,color:#ffffff classDef out fill:#D1FAE5,color:#1E293B class A src class B,C,D logic class E out

Detailed Step-by-Step Practical Lab

What Does a Hardcoded Configuration Look Like?

This is the starting point. It works once, and cannot be reused.

HCL
resource "aws_s3_bucket" "data" {
bucket = "zerodha-data-dev"
tags = {
Environment = "dev"
ManagedBy = "terraform"
}
}
resource "aws_instance" "app" {
ami = "ami-0f5ee92e2d63afc18"
instance_type = "t3.micro"
tags = {
Name = "zerodha-app-dev"
Environment = "dev"
}
}
How to Declare Input Variables

Declare every variable in variables.tf with a description and a type. A variable with no default is required.

HCL
# variables.tf
variable "environment" {
description = "Deployment environment, controls naming and sizing"
type = string
default = "dev"
validation {
condition = contains(["dev", "staging", "prod"], var.environment)
error_message = "Environment must be dev, staging, or prod."
}
}
variable "project_name" {
description = "Project slug used as a prefix in names and tags"
type = string
validation {
condition = can(regex("^[a-z0-9-]+$", var.project_name))
error_message = "Use lowercase letters, numbers, and hyphens only."
}
validation {
condition = length(var.project_name) <= 20
error_message = "Keep the project name to 20 characters or fewer."
}
}
variable "aws_region" {
description = "AWS region for all resources"
type = string
default = "ap-south-1"
}
variable "replica_count" {
description = "Number of app servers to run"
type = number
default = 1
}
variable "enable_versioning" {
description = "Turn on S3 versioning, enable in prod"
type = bool
default = false
}
variable "instance_types" {
description = "Instance type per environment"
type = map(string)
default = {
dev = "t3.micro"
staging = "t3.small"
prod = "t3.large"
}
}
variable "api_token" {
description = "Third-party API token, pass with TF_VAR_api_token"
type = string
sensitive = true # hidden in CLI output, still stored in state
}
How to Use Structured Types and Optional Attributes

An object groups related settings with different types. Mark attributes as optional with a default so callers only set what differs.

HCL
variable "database_config" {
description = "RDS sizing and backup settings"
type = object({
instance_class = string
allocated_storage_gb = number
multi_az = optional(bool, false)
backup_retention_days = optional(number, 7)
})
}
variable "sg_ingress_rules" {
description = "Inbound rules for the app security group"
type = list(object({
description = string
port = number
cidr_blocks = list(string)
}))
default = [
{
description = "HTTPS from the internet"
port = 443
cidr_blocks = ["0.0.0.0/0"]
},
{
description = "App traffic from inside the VPC"
port = 8080
cidr_blocks = ["10.0.0.0/8"]
},
]
}
Tip

A validation condition can only refer to its own variable on Terraform versions before 1.9. From 1.9 it can also refer to other variables and data sources.

How to Supply Variable Values

Create one tfvars file per environment. These files are configuration, not secrets, so they belong in Git.

HCL
# dev.tfvars
environment = "dev"
project_name = "zerodha-api"
replica_count = 1
enable_versioning = false
database_config = {
instance_class = "db.t3.micro"
allocated_storage_gb = 20
}
HCL
# prod.tfvars
environment = "prod"
project_name = "zerodha-api"
replica_count = 3
enable_versioning = true
database_config = {
instance_class = "db.r6g.large"
allocated_storage_gb = 500
multi_az = true
backup_retention_days = 30
}
Bash
export TF_VAR_api_token="read-from-your-secret-store" # secrets never go in tfvars
terraform plan -var-file=prod.tfvars
terraform apply -var-file=prod.tfvars
Which Variable Source Wins?

When several sources set the same variable, later entries in this list override earlier ones:

  1. The default in the variable block
  2. Environment variables named TF_VAR_name
  3. terraform.tfvars, then terraform.tfvars.json
  4. *.auto.tfvars files, in alphabetical order
  5. -var and -var-file flags, in the order given on the command line
How to Use Local Values

A local names an expression you compute once. Locals can use variables, data sources, resources, and other locals, but callers cannot override them.

HCL
# locals.tf
data "aws_caller_identity" "current" {}
locals {
name_prefix = "${var.project_name}-${var.environment}" # zerodha-api-prod
common_tags = {
Project = var.project_name
Environment = var.environment
ManagedBy = "terraform"
}
is_production = var.environment == "prod"
ec2_instance_type = lookup(var.instance_types, var.environment, "t3.micro")
# S3 names are global, so add the account ID
bucket_name = "${local.name_prefix}-data-${data.aws_caller_identity.current.account_id}"
}
How to Write Expressions and Call Built-In Functions

HCL has conditionals and a fixed set of built-in functions. You cannot define your own functions.

HCL
locals {
backup_retention = local.is_production ? 30 : 3 # condition ? true_value : false_value
upper_env = upper(var.environment) # "PROD"
full_name = join("-", [var.project_name, "api"]) # "zerodha-api-api"
underscored = replace(var.project_name, "-", "_") # "zerodha_api"
merged_tags = merge(local.common_tags, { Component = "api" }) # right side wins on conflicts
min_replicas = max(var.replica_count, 2)
}

Test any expression before putting it in code with terraform console:

Bash
terraform console
> cidrsubnet("10.0.0.0/16", 8, 3)
"10.0.3.0/24"
> upper("prod")
"PROD"
How to Transform Lists and Maps with for Expressions

A for expression builds a new list or map from an existing collection, with an optional filter.

HCL
variable "availability_zones" {
description = "AZs to spread subnets across"
type = list(string)
default = ["ap-south-1a", "ap-south-1b"]
}
locals {
az_labels = [for az in var.availability_zones : "${var.project_name}-${az}"]
non_dev = [for env in ["dev", "staging", "prod"] : env if env != "dev"]
az_index_map = { for idx, az in var.availability_zones : az => idx }
}
resource "aws_subnet" "private" {
for_each = local.az_index_map # a map gives each subnet a stable key
vpc_id = aws_vpc.main.id
availability_zone = each.key
cidr_block = cidrsubnet(var.vpc_cidr, 8, each.value + 10)
tags = merge(local.common_tags, {
Name = "${local.name_prefix}-private-${each.key}"
})
}
How to Generate Repeated Blocks with dynamic

A dynamic block creates one nested block per item in a collection, so adding a rule means adding an item to a variable instead of editing the resource.

HCL
resource "aws_security_group" "app" {
name = "${local.name_prefix}-app-sg"
description = "App security group for ${local.name_prefix}"
vpc_id = aws_vpc.main.id
dynamic "ingress" {
for_each = var.sg_ingress_rules
content {
description = ingress.value.description
from_port = ingress.value.port
to_port = ingress.value.port
protocol = "tcp"
cidr_blocks = ingress.value.cidr_blocks
}
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
tags = local.common_tags
}
How to Expose Output Values

Outputs return information to people, scripts, parent modules, and other configurations.

HCL
# outputs.tf
output "s3_bucket_name" {
description = "Data bucket name for the application config"
value = aws_s3_bucket.data.id
}
output "s3_bucket_arn" {
description = "Bucket ARN for IAM policy resources"
value = aws_s3_bucket.data.arn
}
output "instance_ids" {
description = "IDs of all app servers"
value = aws_instance.app[*].id
}
output "api_token_hint" {
description = "Example of a sensitive output"
value = var.api_token
sensitive = true
}
Bash
terraform output # all outputs, sensitive ones redacted
terraform output -raw s3_bucket_name # plain value for scripts
terraform output -json # machine-readable
BUCKET=$(terraform output -raw s3_bucket_name)
Security

sensitive = true hides a value from CLI output only. It is still stored in plaintext in state, so use an encrypted remote backend.

What Does the Refactored Configuration Look Like?

The same resources as the start of the lab, now parameterised and reusable across environments.

HCL
# main.tf (after)
data "aws_ami" "amazon_linux" {
most_recent = true
owners = ["amazon"]
filter {
name = "name"
values = ["al2023-ami-2023.*-x86_64"]
}
}
resource "aws_s3_bucket" "data" {
bucket = local.bucket_name
tags = local.common_tags
}
resource "aws_s3_bucket_versioning" "data" {
count = var.enable_versioning ? 1 : 0 # create the resource only when enabled
bucket = aws_s3_bucket.data.id
versioning_configuration {
status = "Enabled"
}
}
resource "aws_instance" "app" {
count = var.replica_count
ami = data.aws_ami.amazon_linux.id
instance_type = local.ec2_instance_type
vpc_security_group_ids = [aws_security_group.app.id]
lifecycle {
ignore_changes = [ami] # do not replace servers when a newer AMI is published
}
tags = merge(local.common_tags, {
Name = "${local.name_prefix}-app-${count.index + 1}"
})
}
Bash
terraform apply -var-file=dev.tfvars # dev
terraform apply -var-file=prod.tfvars # same code, production values

Use separate state per environment, with a different backend key or directory, so applying prod never changes dev.

Production Best Practices & Common Pitfalls

  • Describe every variable. The description is the only documentation someone sees in a tfvars file six months later.
  • Validate restricted values. Use contains() for allowed names, regex() for formats, and length() for limits, so mistakes fail at plan time.
  • Keep secrets out of tfvars. Use TF_VAR_ environment variables or read them from a secrets manager in CI.
  • Use locals for anything written twice. A naming pattern repeated in eight places is eight edits when the convention changes.
  • Prefer for_each over count for named items. Removing a middle item from a count list renumbers the rest and can recreate resources.
  • Commit non-secret tfvars per environment. It gives an audit trail of what each environment uses.
  • Test expressions in terraform console. It is faster than editing a resource and running a plan.
Common Mistake

Putting a secret in terraform.tfvars and committing it. Anyone with repository access then has it, and it stays in Git history. Pass secrets with TF_VAR_ variables.

Quick Reference & Troubleshooting Commands

Command Description
terraform validate Check syntax without calling any API
terraform console Evaluate expressions interactively
terraform plan -var-file=prod.tfvars Plan with one environment's values
terraform output -raw NAME Print one output for scripts
terraform output -json Print all outputs as JSON
Error Root Cause Fix
Variables not allowed var.x used in a backend block Use literals or -backend-config
Invalid value for variable A validation condition failed Read the error_message and fix the value
Unsupported attribute Wrong key for an object variable Check the object({...}) definition
Invalid for_each argument Value is not a map or set Use toset() or a for expression to build a map
Output shows (sensitive value) sensitive = true is set Use terraform output -raw NAME
A default is not applied A higher-precedence source overrides it Check `env

Resources

Explore More in Terraform Fundamentals and Core Workflow

All 4 Topics

Frequently Asked Questions

Is Using Terraform Variables, Outputs, and Locals free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Using Terraform Variables, Outputs, and Locals topic cover?

Learn Terraform variables, outputs, locals, expressions, and dynamic blocks by refactoring a hardcoded config into a reusable multi-environment one.

Found a mistake, an outdated step or a broken link?