Terraform Modules and State
Summary: in this tutorial, you will learn explore terraform modules, state management, and workspaces to build reusable infrastructure and keep deployments consistent.
Terraform Modules and State
Modules help you organize Terraform configuration into reusable components.
Create a simple module
In modules/storage/main.tf:
resource "aws_s3_bucket" "bucket" {
bucket = var.bucket_name
acl = "private"
}
variable "bucket_name" {
type = string
}Use the module from root configuration:
module "storage" {
source = "./modules/storage"
bucket_name = "shellrag-storage-demo"
}Terraform state
Terraform stores state in terraform.tfstate. The state file tracks real infrastructure and lets Terraform compare desired state against actual state.
Common state commands:
terraform show
terraform state list
terraform state rm aws_s3_bucket.websiteRemote state
For teams, store state remotely using supported backends like S3, Azure Blob Storage, or Terraform Cloud.
Example backend:
terraform {
backend "s3" {
bucket = "shellrag-terraform-state"
key = "terraform.tfstate"
region = "us-east-1"
}
}Best practices
- Keep state secure and versioned
- Use modules for reusable patterns
- Use
terraform fmtto format files - Review
terraform planbefore applying
Modules and state are the foundations of scalable Terraform usage.
Written by the ShellRAG Team
The ShellRAG editorial team writes practical, beginner-friendly Terraform tutorials with tested code examples and real-world use cases. Every article is technically reviewed for accuracy and updated regularly.
Learn more about us →