Day 02 Core Concepts

Variables, Outputs, and State

Parameterize configurations with variables, expose values with outputs, and understand what Terraform state is.

~1 hour Hands-on Precision AI Academy

Today's Objective

Learn the core concepts of Variables, Outputs, and State and apply them in practical exercises.

01

Variables

variables.tf
variables.tf
variable "region" {
  description = "AWS region"
  type        = string
  default     = "us-east-1"
}

variable "environment" {
  description = "Deployment environment"
  type        = string
  # No default = required. Must be supplied.
}

variable "allowed_ips" {
  description = "IPs allowed to access the server"
  type        = list(string)
  default     = ["0.0.0.0/0"]
}
Using variables
Using variables
# In main.tf
provider "aws" {
  region = var.region
}

resource "aws_s3_bucket" "main" {
  bucket = "my-bucket-${var.environment}"
}
terraform.tfvars
terraform.tfvars
# Values for required variables
environment = "staging"
allowed_ips = ["192.168.1.0/24", "10.0.0.0/8"]

# Never commit sensitive values — use env vars instead:
# TF_VAR_environment=staging terraform apply
outputs.tf
outputs.tf
output "bucket_name" {
  description = "Name of the created bucket"
  value       = aws_s3_bucket.main.bucket
}

output "bucket_arn" {
  value = aws_s3_bucket.main.arn
}

# After apply:
# Outputs:
# bucket_name = "my-bucket-staging"
# bucket_arn = "arn:aws:s3:::my-bucket-staging"
Terraform State
Terraform State
# terraform.tfstate is created after first apply
# It maps your config to real resources
# NEVER edit it manually
# NEVER commit it to git (may contain secrets)
# Add to .gitignore:
echo 'terraform.tfstate*' >> .gitignore
echo '.terraform/' >> .gitignore

# Remote state (team-friendly)
# terraform { backend "s3" { bucket = "my-tf-state" ... } }
⚠️
Terraform state is the source of truth. If you manually delete a resource in the console, Terraform doesn't know until the next plan. It will try to recreate it. Always use Terraform to manage resources that Terraform created.

Supporting References & Reading

Go deeper with these external resources.

Terraform Docs
Variables, Outputs, and State Official HashiCorp Terraform documentation.
YouTube
Variables, Outputs, and State Terraform tutorials on YouTube
MDN
MDN Web Docs Comprehensive web technology reference

Day 2 Checkpoint

Before moving on, confirm understanding of these key concepts:

Continue To Day 3
Day 3 of the Terraform in 5 Days course