Terragrunt for Beginners

Terragrunt Modules

Demo Wrapper Module Approach

In this example, we'll create a wrapper module around the official Terraform S3 bucket community module. This lets you inherit all best practices while enforcing your own naming conventions and configuration rules.

Why Use a Wrapper Module?

A wrapper module allows you to:

  • Leverage community-tested code.
  • Enforce company-specific policies (e.g., naming standards).
  • Extend or override default settings without modifying upstream code.
ModuleDescriptionKey Inputs
terraform-aws-modules/s3-bucket/awsOfficial S3 bucket module on the Terraform Registrysource, version, bucket
local wrapper moduleWraps the community module to append a random suffix to namesbucket_name, suffix_length

1. Define the Wrapper Module

In your local modules/s3-bucket directory, replace the direct resource blocks with a call to the community module:

terraform {
  required_providers {
    random = {
      source  = "hashicorp/random"
      version = "3.5.1"
    }
  }
}

module "s3_bucket" {
  source  = "terraform-aws-modules/s3-bucket/aws"
  version = "4.0.0"

  bucket = local.full_bucket_name
  acl    = "private"

  # …any other inputs you normally pass…
}

2. Add a Random Suffix

Generate a unique suffix automatically so that bucket names remain globally unique:

resource "random_string" "suffix" {
  length           = 8
  special          = false
  upper            = false
}

locals {
  full_bucket_name = "${var.bucket_name}-${random_string.suffix.result}"
}

Note

We set special = false and upper = false to keep the suffix alphanumeric and lowercase only.

3. Update Module Outputs

Since the wrapper no longer defines the bucket resource directly, forward the community module outputs:

output "bucket_id" {
  value = module.s3_bucket.bucket_id
}

output "bucket_arn" {
  value = module.s3_bucket.bucket_arn
}

4. Configure Terragrunt

In your Terragrunt live configuration, reference the local wrapper module. Notice we no longer supply a suffix manually:

terraform {
  source = "../modules/s3-bucket"
}

inputs = {
  bucket_name = "testing-bucket-for-terragrunt"
}

Warning

The final bucket name is not known until apply time since it depends on the random suffix.

5. Deploy with Terragrunt

Run:

terragrunt init
terragrunt apply

Terragrunt will:

  1. Download the S3 bucket community module.
  2. Generate a random suffix.
  3. Create the bucket with your base name plus suffix.
  4. Apply default public-access-block settings from the module.

Confirm the bucket exists:

aws s3 ls
# OUTPUT: 2023-01-01 12:00:00 testing-bucket-for-terragrunt-4k7gtj3r

Learn More

Watch Video

Watch video content

Previous
Wrapper Module Approach