How to Use Module from Registry in Terraform: Simple Guide
To use a module from the Terraform Registry, declare a
module block in your Terraform configuration with the source set to the registry module address. Then specify any required input variables for that module. Terraform will download and use the module during terraform init and terraform apply.Syntax
The basic syntax to use a module from the Terraform Registry includes a module block with a unique name, a source attribute pointing to the registry module, and optional input variables.
- module "name": Defines the module block with a unique name.
- source: The registry address of the module, e.g.,
terraform-aws-modules/vpc/aws. - version: (Optional) Specifies the module version to use.
- Input variables: Pass values required by the module.
hcl
module "example_module" { source = "terraform-aws-modules/vpc/aws" version = "~> 3.0" name = "my-vpc" cidr = "10.0.0.0/16" }
Example
This example shows how to use the official AWS VPC module from the Terraform Registry to create a simple VPC with a CIDR block.
hcl
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.0"
}
}
}
provider "aws" {
region = "us-east-1"
}
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "~> 3.0"
name = "my-vpc"
cidr = "10.0.0.0/16"
azs = ["us-east-1a", "us-east-1b", "us-east-1c"]
public_subnets = ["10.0.1.0/24", "10.0.2.0/24", "10.0.3.0/24"]
private_subnets = ["10.0.101.0/24", "10.0.102.0/24", "10.0.103.0/24"]
}Output
module.vpc.aws_vpc.main: Creating...
module.vpc.aws_vpc.main: Creation complete after 10s [id=vpc-0abcd1234efgh5678]
Apply complete! Resources: 5 added, 0 changed, 0 destroyed.
Common Pitfalls
Common mistakes when using modules from the registry include:
- Not running
terraform initafter adding a module, so Terraform does not download it. - Forgetting to specify the
sourceattribute or using an incorrect module address. - Not providing required input variables, causing errors during plan or apply.
- Using incompatible module versions without specifying
version.
hcl
/* Wrong: Missing source attribute */ module "bad_module" { name = "test" } /* Right: Correct source and inputs */ module "good_module" { source = "terraform-aws-modules/vpc/aws" version = "~> 3.0" name = "test" cidr = "10.0.0.0/16" }
Quick Reference
Remember these tips when using Terraform Registry modules:
- Always specify
sourcewith the full registry path. - Use
versionto lock module versions for stability. - Run
terraform initafter adding or changing modules. - Check module documentation for required inputs.
Key Takeaways
Use a
module block with source pointing to the registry module address.Always run
terraform init to download modules before applying.Specify required input variables as documented by the module.
Lock module versions with
version to avoid unexpected changes.Check for common mistakes like missing
source or inputs to prevent errors.