Terraform Cost Optimization for AWS - Reduce Your Cloud Bill
Practical Terraform patterns to reduce AWS costs: right-sizing, spot instances, scheduling, and reserved capacity. Step-by-step guide with code examples and ...
Guides
Complete guide to all Terraform variable types: input variables, output values, locals, and environment variables. Step-by-step guide with code examples and ...
Terraform has four ways to handle dynamic values: input variables, output values, local values, and environment variables.
Declared with variable blocks, used to parameterize configurations:
variable "instance_type" {
type = string
default = "t3.micro"
description = "EC2 instance type"
validation {
condition = contains(["t3.micro", "t3.small", "t3.medium"], var.instance_type)
error_message = "Instance type must be t3.micro, t3.small, or t3.medium."
}
}-var flag (highest): terraform apply -var="instance_type=t3.small"-var-file: terraform apply -var-file="prod.tfvars"*.auto.tfvars files (alphabetical order)terraform.tfvars fileTF_VAR_ environment variables: export TF_VAR_instance_type=t3.smallvariable "tags" {
type = map(string)
default = {
Environment = "dev"
Team = "platform"
}
}
variable "subnets" {
type = list(object({
cidr = string
az = string
}))
}Expose information from your configuration:
output "instance_ip" {
value = aws_instance.web.public_ip
description = "Public IP of the web server"
}
output "db_password" {
value = random_password.db.result
sensitive = true
}Access module outputs: module.networking.vpc_id
Computed values for use within a module — reduce repetition:
locals {
common_tags = {
Project = var.project
Environment = var.environment
ManagedBy = "terraform"
}
name_prefix = "${var.project}-${var.environment}"
}
resource "aws_instance" "web" {
tags = merge(local.common_tags, { Name = "${local.name_prefix}-web" })
}| Type | Use When |
|---|---|
| Input variable | Value differs between environments or users |
| Output | Exposing values to parent modules or CLI |
| Local | Computed values used multiple times in same module |
| Environment | CI/CD pipelines, secrets, overrides |
Practical Terraform patterns to reduce AWS costs: right-sizing, spot instances, scheduling, and reserved capacity. Step-by-step guide with code examples and ...
How to achieve zero-downtime deployments with Terraform using blue-green, rolling updates, and create_before_destroy. Step-by-step guide with code examples a...
Complete guide to testing Terraform configurations with terraform test, Terratest, and validation rules. Step-by-step guide with code examples and best pract...
Complete guide to Terraform data sources: querying existing infrastructure, filtering, and common patterns. Step-by-step guide with code examples and best pr...