Write Your First Module
A first module turns a repeated resource into a reusable folder. One bucket module, called twice, builds two buckets with no copied code.
The bucket, with a variable
The name is the only value that changes. Everything else stays fixed inside the module.
variable "name" {
type = string
}
resource "aws_s3_bucket" "this" {
bucket = var.name
}Give back the name
The output hands the bucket name back to the caller. The caller can use it in its own outputs.
output "bucket_name" {
value = aws_s3_bucket.this.bucket
}Run it against moto_server
The provider reads placeholder credentials and talks to moto_server instead of AWS. Destroy at the end removes the buckets.
export AWS_ACCESS_KEY_ID=test
export AWS_SECRET_ACCESS_KEY=test
terraform init
terraform apply
terraform destroyExample
# modules/bucket/main.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "6.72.0"
}
}
}
variable "name" {
type = string
}
resource "aws_s3_bucket" "this" {
bucket = var.name
}
output "bucket_name" {
value = aws_s3_bucket.this.bucket
}
# main.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "6.72.0"
}
}
}
provider "aws" {
region = "us-east-1"
skip_credentials_validation = true
skip_metadata_api_check = true
skip_requesting_account_id = true
s3_use_path_style = true
endpoints {
s3 = "http://localhost:5000"
}
}
module "logs" {
source = "./modules/bucket"
name = "my-logs-bucket"
}
module "assets" {
source = "./modules/bucket"
name = "my-assets-bucket"
}
output "buckets" {
value = [module.logs.bucket_name, module.assets.bucket_name]
}Key points
- Start with the resource you keep writing by hand.
- Move it into its own folder with variables for the values that change.
- The values that never change stay inside the module.
- Call the module from the root with a source path.
- Each call builds its own separate resources.
- The module output lets the root read back what was built.
The bucket module is written once. The root calls it twice with two names, and two buckets appear on the local AWS emulator. A destroy at the finish removes both buckets.
Note
Both buckets are created by the module in moto_server, not in real AWS.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
How does one module build two different buckets?