Calling a Module

Use a module block with source and input arguments to instantiate a child module.

Syntaxmodule "name" { source = "./modules/x" }

You use a child module with a module block. The source tells Terraform where to find it, and the remaining arguments set the module's input variables.

Referencing module outputs

Read a module's outputs with module.NAME.OUTPUT, for example module.vpc.vpc_id.

Re-run init

After adding a module, run terraform init so Terraform can install it.

Example

Example · hcl
module "assets_bucket" {
  source = "./modules/s3-bucket"
  name   = "soundscode-assets-2026"
}

# Use the module's output elsewhere
resource "aws_iam_policy" "read_assets" {
  name   = "read-assets"
  policy = jsonencode({
    Statement = [{
      Effect   = "Allow"
      Action   = ["s3:GetObject"]
      Resource = "${module.assets_bucket.arn}/*"
    }]
  })
}

When to use it

  • An application team calls the platform's vpc module with a source path and three input variables, letting the module handle all 15 underlying resources.
  • A developer pins a Terraform Registry module to version 3.5.0 so upgrades are deliberate and tested rather than silently pulling in breaking changes.
  • An engineer calls the same internal module twice with different names and CIDR blocks to create separate management and application VPCs.

More examples

Call a local module

Calls a local module from a relative path, passing three input variables to configure the VPC it creates.

Example · hcl
module "network" {
  source = "./modules/vpc"

  name       = "my-app"
  cidr_block = "10.0.0.0/16"
  azs        = ["us-east-1a", "us-east-1b"]
}

Call a registry module with version

Uses a community module from the Terraform Registry, pinned to a specific version to prevent uncontrolled upgrades.

Example · hcl
module "s3_bucket" {
  source  = "terraform-aws-modules/s3-bucket/aws"
  version = "4.1.2"

  bucket        = "my-app-assets"
  force_destroy = true

  versioning = {
    enabled = true
  }
}

Call same module twice

Instantiates the same VPC module twice with different names and CIDRs, creating two independent VPCs from one module definition.

Example · hcl
module "app_vpc" {
  source     = "./modules/vpc"
  name       = "app"
  cidr_block = "10.0.0.0/16"
}

module "mgmt_vpc" {
  source     = "./modules/vpc"
  name       = "mgmt"
  cidr_block = "10.1.0.0/16"
}

Discussion

  • Be the first to comment on this lesson.