on
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?
- It’s real-world useful: many apps need an object store for assets, logs, or backups.
- It teaches core module topics: inputs, outputs, defaults, validations, and structure.
- It carries important security considerations that are good to bake into a module from day one.
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:
- main.tf — resources and data sources
- variables.tf — input variables and validation
- outputs.tf — exported values
- README.md — documentation for consumers
- examples/ — small example usages (optional)
- .gitignore, LICENSE, and CI config (optional)
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:
- The module adds a random suffix to reduce naming collisions.
- Encryption and versioning are on by default; these are commonly desirable for production buckets.
- Expose only necessary knobs (like lifecycle_days) and keep the rest sane defaults.
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:
- Purpose and scope (what the module does and does not do).
- Required provider and Terraform version constraints.
- Example usage.
- Explanations of inputs, outputs, and side-effects.
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-
Testing and validation A handful of checks will keep your module healthy as you evolve it:
- terraform fmt — formatting consistency.
- terraform validate — catches syntax and schema problems.
- Static checks (linters) such as TFLint can detect provider-specific issues and common mistakes.
- Example-based integration tests (CI pipelines that run terraform init/plan in an isolated account) are ideal for production modules but optional for your first module.
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)
- Keep input variables small and meaningful—prefer objects for related settings to reduce the parameter list.
- Use descriptive variable names and complete descriptions so autogenerated docs are useful.
- Prefer preconditions/postconditions or variable validation to fail fast and provide actionable messages.
- Use tags and predictable naming to help with resource discovery in cloud consoles and audits.
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
- Terraform module creation and recommended patterns (HashiCorp). (docs.hashicorp.com)
- Terraform language: variable blocks and validation. (docs.hashicorp.com)
- Terraform style guide and module naming recommendations. (developer.hashicorp.com)
- HashiCorp guidance on writing and rightsizing modules. (hashicorp.com)
- Terraform CLI: validate, fmt and best practices for checking configurations. (developer.hashicorp.com)
- TFLint (pluggable Terraform linter) for provider-aware linting. (github.com)
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.