Terraform Variables, Outputs and Locals
Hard-coded values make Terraform code impossible to reuse. Variables bring values in, locals compute values once, and outputs send values out.
Input variables
# variables.tf
variable "environment" {
type = string
description = "Deployment environment"
validation {
condition = contains(["dev", "staging", "prod"], var.environment)
error_message = "environment must be dev, staging or prod."
}
}
variable "instance_count" {
type = number
default = 2
}
variable "db_password" {
type = string
sensitive = true # hidden in plan output
}
Setting values
# prod.tfvars
environment = "prod"
instance_count = 4
terraform plan -var-file=prod.tfvars
export TF_VAR_db_password="..." # environment variables work too (good for secrets)
Locals: name things once
locals {
name_prefix = "shop-${var.environment}"
common_tags = {
Project = "shop"
Environment = var.environment
ManagedBy = "terraform"
}
}
resource "aws_s3_bucket" "uploads" {
bucket = "${local.name_prefix}-uploads"
tags = local.common_tags
}
Outputs
output "uploads_bucket" {
value = aws_s3_bucket.uploads.bucket
description = "Bucket for user uploads"
}
terraform output uploads_bucket
terraform output -json # for scripts and CI
Tips
- Give every variable a
typeanddescription. - Add
validationblocks for values that have rules; errors appear before any API calls. sensitive = truehides values in output, but they're still stored in state, so protect the state too.- Prefer
optional()attributes in object types over many separate variables.
Was this article helpful?
Comments
No comments yet. Have a question or a tip? Be the first to share it.