Terraform Tutorial — Calling a Module
You call a module using the module block in your root configuration. The source argument tells Terraform where to find the module.
Calling a Local Module
module "vpc" {
source = "./modules/vpc"
name = "myapp"
cidr_block = "10.0.0.0/16"
public_subnets = ["10.0.1.0/24", "10.0.2.0/24"]
availability_zones = ["us-east-1a", "us-east-1b"]
tags = {
Environment = "dev"
Project = "myapp"
}
}
Calling a Registry Module
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "5.4.0"
name = "myapp-vpc"
cidr = "10.0.0.0/16"
azs = ["us-east-1a", "us-east-1b"]
public_subnets = ["10.0.1.0/24", "10.0.2.0/24"]
private_subnets = ["10.0.10.0/24", "10.0.20.0/24"]
enable_nat_gateway = true
single_nat_gateway = true
}
Calling a Git Module
module "vpc" {
source = "git::https://github.com/myorg/terraform-modules.git//vpc?ref=v1.2.0"
name = "myapp"
cidr_block = "10.0.0.0/16"
}
Module Block Arguments
| Argument | Required | Purpose |
|---|---|---|
source |
✅ Yes | Where to find the module |
version |
Recommended | Pin a specific version (registry only) |
| Variables | Depends | Each variable the module declares |
providers |
Optional | Pass specific provider configurations |
depends_on |
Optional | Explicit dependency on other resources |
count |
Optional | Create zero or more instances |
for_each |
Optional | Create instances from a map/set |
Re-run init After Adding a Module
When you add a new module, run terraform init to download it:
$ terraform init
Initializing modules...
- vpc in ./modules/vpc
Initializing provider plugins...
Multiple Instances of a Module
Use the same module with different inputs:
module "vpc_dev" {
source = "./modules/vpc"
name = "dev"
cidr_block = "10.0.0.0/16"
availability_zones = ["us-east-1a", "us-east-1b"]
}
module "vpc_prod" {
source = "./modules/vpc"
name = "prod"
cidr_block = "10.1.0.0/16"
availability_zones = ["us-east-1a", "us-east-1b", "us-east-1c"]
}
What’s Next?
Let’s dive deeper into passing inputs and receiving outputs from modules.