Labs · DevOps
Lab: Write a Reusable Terraform Module (Inputs, Resources, Outputs) for a Private, Encrypted S3 Bucket and Call It Twice
Course: DevOps · Chapter 35: Terraform Modules Writing Using Registry and Versioning · Lesson: 35.2 Write a module: inputs, resources, outputs
Chapter 35 explains writing, using, registry and versioning modules; this lab writes one from scratch.
Chala mitrano! Ekach code dahaa folder madhe copy-paste kela ki ek fix dahaa thikaani karava laagto. Module banvuya.
Suppose we are…
Suppose we are on a Netflix-style platform team and every product team creates S3 buckets. Some forget to block public access, some forget encryption. Copy-pasting the "correct" bucket code into twenty folders means twenty places to fix later.
In this lab we write one module that always creates a private, encrypted, versioned bucket, and call it twice from a root project.
Goal of this lab
By the end you will have:
- A module folder with
variables.tf,main.tfandoutputs.tf. - Two buckets (logs and assets) from two
moduleblocks. - An input validation that rejects bad names.
What you need
- Terraform 1.6 or newer (
terraform version). - AWS CLI v2 signed in to your own AWS account with an IAM user or SSO role that may create these resources (
aws sts get-caller-identityworks). Never use the root user, and never paste access keys into .tf files. - Region Mumbai (
ap-south-1) is used; changeregionif you prefer another. - 40 minutes.
Cost and cleanup
Two empty S3 buckets cost almost nothing. Small charges are possible even on the free tier. Finish the lab in one sitting and always run the Clean up part at the end.
Part 1: The module
Create the folders:
mkdir -p tf-module-lab/modules/private-bucket && cd tf-module-labInputs, with validation:
modules/private-bucket/variables.tf
variable "name_prefix" { description = "Start of the bucket name, lowercase" type = string validation { condition = can(regex("^[a-z0-9-]{3,30}$", var.name_prefix)) error_message = "Use 3-30 lowercase letters, digits or hyphens." } } variable "tags" { type = map(string) default = {} }Resources:
modules/private-bucket/main.tf
resource "aws_s3_bucket" "this" { bucket_prefix = "${var.name_prefix}-" force_destroy = true # lab only tags = var.tags } resource "aws_s3_bucket_public_access_block" "this" { bucket = aws_s3_bucket.this.id block_public_acls = true block_public_policy = true ignore_public_acls = true restrict_public_buckets = true } resource "aws_s3_bucket_server_side_encryption_configuration" "this" { bucket = aws_s3_bucket.this.id rule { apply_server_side_encryption_by_default { sse_algorithm = "AES256" } } } resource "aws_s3_bucket_versioning" "this" { bucket = aws_s3_bucket.this.id versioning_configuration { status = "Enabled" } }Outputs:
modules/private-bucket/outputs.tf
output "bucket_name" { value = aws_s3_bucket.this.bucket } output "bucket_arn" { value = aws_s3_bucket.this.arn }
Part 2: Use it twice
Root
main.tfnext to themodulesfolder:main.tf
terraform { required_version = ">= 1.6" required_providers { aws = { source = "hashicorp/aws" version = "~> 5.0" } } } provider "aws" { region = "ap-south-1" } locals { tags = { project = "badge", owner = "platform" } } module "logs" { source = "./modules/private-bucket" name_prefix = "badge-logs" tags = local.tags } module "assets" { source = "./modules/private-bucket" name_prefix = "badge-assets" tags = local.tags } output "logs_bucket" { value = module.logs.bucket_name } output "assets_bucket" { value = module.assets.bucket_name }Init, plan and apply:
terraform init terraform plan terraform applyWhat you should see:
Plan: 8 to add(4 per module) and two bucket names in the outputs.Check one bucket really blocks public access:
aws s3api get-public-access-block --bucket $(terraform output -raw logs_bucket)What you should see: all four settings
true.
Part 3: Test the validation
Add a third module block with
name_prefix = "Badge_Media"and runterraform plan.What you should see:
Invalid value for variableandUse 3-30 lowercase letters, digits or hyphens.Remove the block again.
Clean up: destroy everything
Delete everything this lab created. Type
yeswhen asked:terraform destroyWhat you should see:
Destroy complete! Resources: 8 destroyed.
Ravindra Bagale's Tip
A good module has few inputs and safe defaults. If callers must remember to switch on encryption, the module is not doing its job.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
Adding a module and forgetting terraform init | Module not installed | Run terraform init after adding or moving modules |
| Hard-coding a bucket name inside the module | Second call fails: bucket exists | Use bucket_prefix or a name input |
| Provider block inside the module | Hard to reuse across regions | Configure providers only in the root |
Skipping terraform plan | Surprise changes or deletes | Always read the plan counts before apply |
Self-check checklist
0 of 4 done
Try-at-home challenge
Add an optional input lifecycle_days (default null) and create a lifecycle rule only when it is set, using count = var.lifecycle_days == null ? 0 : 1.
Samajla ka? Write it once, call it everywhere, fix it in one place. Aata pudhe jaauya import.