Writing Your First Terraform Module: a Secure, Reusable S3 Bucket

Terraform modules are like song arrangements: the same melody (cloud resource) can be played in many keys (environments) — but the arrangement (module) makes it reusable, testable, and pleasant to share. This short article walks through designing a compact, well-scoped Terraform module that provisions a secure AWS S3 bucket with reasonable defaults: encryption, versioning, lifecycle rule for old objects, and public access blocks. Along the way I’ll call out practical patterns, validation, and simple checks that keep the module honest and reusable.

Why pick a secure S3 bucket?

Keep the scope small A fundamental rule when creating modules is to choose a scope that helps consumers without hiding too many details. A module that wraps a whole platform can be hard to maintain; a module that only wraps a single trivial resource may be unnecessary. A secure S3 bucket—one resource plus a few configuration options and sensible defaults—is a great first module. This pattern and guidance are recommended by the Terraform docs and module-creation guidance. (docs.hashicorp.com)

Module layout (typical files) A clear layout makes the module easy to navigate and maintain. A minimal set of files for this module:

This conventional structure is described in the Terraform module and style guidance. Keeping configuration files focused and named consistently improves readability and makes automation easier. (docs.hashicorp.com)

Example variables.tf (with validation) Variable validation is a great way to enforce good defaults and provide clear errors to module users. Terraform evaluates validation during planning and errors out if a condition fails. Below is a compact variables.tf showing useful inputs and a validation block:

variable "name" {
  description = "Base name for the bucket; will be combined with a suffix"
  type        = string

  validation {
    condition     = length(var.name) >= 3 && length(var.name) <= 63
    error_message = "name must be between 3 and 63 characters"
  }
}

variable "enable_versioning" {
  description = "Enable S3 versioning"
  type        = bool
  default     = true
}

variable "lifecycle_days" {
  description = "Days before non-current object versions are expired; 0 disables lifecycle"
  type        = number
  default     = 365
}

The validation block above demonstrates how to surface clear, early errors to users rather than letting misconfiguration quietly propagate. The variable validation concept and behavior are documented in Terraform’s language reference. (docs.hashicorp.com)

Example main.tf (core resource) Keep the resource definition focused. Use provider-level defaults where appropriate, and expose only what consumers need to change.

resource "aws_s3_bucket" "this" {
  bucket = "${var.name}-${random_id.suffix.hex}"
  acl    = "private"

  versioning {
    enabled = var.enable_versioning
  }

  server_side_encryption_configuration {
    rule {
      apply_server_side_encryption_by_default {
        sse_algorithm = "AES256"
      }
    }
  }

  lifecycle_rule {
    id      = "noncurrent-version-expiration"
    enabled = var.lifecycle_days > 0

    noncurrent_version_expiration {
      days = var.lifecycle_days
    }
  }

  tags = {
    ManagedBy = "terraform-module-s3"
  }
}

resource "random_id" "suffix" {
  byte_length = 4
}

Notes:

Outputs.tf: what consumers need Export the bucket name and ARN, and maybe the bucket ID. Group outputs logically and document them in the README.

output "bucket_id" {
  value       = aws_s3_bucket.this.id
  description = "The ID of the S3 bucket"
}

output "bucket_arn" {
  value       = aws_s3_bucket.this.arn
  description = "The ARN of the S3 bucket"
}

Document everything (README) A README is not optional for a public module; it’s your module’s user manual. Include:

Follow style guidance for naming and documentation conventions; HashiCorp’s style guide and registry docs give good direction for naming and publishing. For public registries, a repository name format like terraform-- is recommended. ([developer.hashicorp.com](https://developer.hashicorp.com/terraform/language/style?utm_source=openai))

Testing and validation A handful of checks will keep your module healthy as you evolve it:

Run terraform validate and use a linter as part of CI to avoid regressions; those tools and practices are recommended in the Terraform docs and community tooling. (developer.hashicorp.com)

Rightsizing: avoid over-architecting A recurring advisory from Terraform authors: make modules neither too large nor trivially small. If your code is simply a one-to-one wrapper for a single resource with no meaningful defaults or opinion, it might be overkill as a module. Conversely, if it hides multiple unrelated responsibilities, it becomes brittle for consumers. Design modules around a single responsibility—here, “secure S3 bucket with lifecycle rules”—and keep optional extensibility. (hashicorp.com)

Versioning and publishing When your module is ready to share, tag releases in Git and follow semantic versioning. If you publish to a private registry or the public Terraform Registry, use consistent naming and versioning so consumers can pin a stable major release. The Terraform docs cover recommended patterns for publishing modules and version control. (developer.hashicorp.com)

A few practical tips (quick bullets)

Wrap-up: the melody and the arrangement Writing your first Terraform module is less about clever code and more about thoughtful composition: pick a clear scope, make safe defaults, document clearly, and validate early. A secure S3 bucket module is an ideal starting composition—small enough to finish quickly, broad enough to teach real-world concerns, and reusable across projects.

References and further reading

If you treat your module like a good arrangement—clear parts, readable sheet music (README), and a simple rehearsal (validate + lint)—it will be pleasant for other engineers to pick up and play.