Ravindra BagaleCourses & study guides Track your progress

Labs · DevOps

Lab: Write a Reusable Terraform Module (Inputs, Resources, Outputs) for a Private, Encrypted S3 Bucket and Call It Twice

Intermediate40 minTerraform 1.6+ · AWS CLI v2 · An AWS account

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.tf and outputs.tf.
  • Two buckets (logs and assets) from two module blocks.
  • 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-identity works). Never use the root user, and never paste access keys into .tf files.
  • Region Mumbai (ap-south-1) is used; change region if 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

  1. Create the folders:

    mkdir -p tf-module-lab/modules/private-bucket && cd tf-module-lab
    
  2. Inputs, 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 = {}
    }
    
  3. 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" }
    }
    
  4. 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

  1. Root main.tf next to the modules folder:

    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
    }
    
  2. Init, plan and apply:

    terraform init
    terraform plan
    terraform apply
    

    What you should see: Plan: 8 to add (4 per module) and two bucket names in the outputs.

  3. 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

  1. Add a third module block with name_prefix = "Badge_Media" and run terraform plan.

    What you should see: Invalid value for variable and Use 3-30 lowercase letters, digits or hyphens. Remove the block again.

Clean up: destroy everything

  1. Delete everything this lab created. Type yes when asked:

    terraform destroy
    

    What 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

MistakeWhat happensFix
Adding a module and forgetting terraform initModule not installedRun terraform init after adding or moving modules
Hard-coding a bucket name inside the moduleSecond call fails: bucket existsUse bucket_prefix or a name input
Provider block inside the moduleHard to reuse across regionsConfigure providers only in the root
Skipping terraform planSurprise changes or deletesAlways 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.