How to Use Source in Module in Terraform: Simple Guide
In Terraform, use the
source argument inside a module block to specify where the module code is located. The source can point to a local path, a Git repository, or a Terraform Registry module, enabling reuse of infrastructure code.Syntax
The source argument tells Terraform where to find the module code. It is used inside a module block with a name you choose. The source can be a local folder, a Git URL, or a registry address.
- module <name>: Defines the module block with a chosen name.
- source: Specifies the location of the module code.
- other inputs: Variables passed to the module.
terraform
module "example_module" { source = "./modules/example" # other variables here }
Example
This example shows how to use a local module stored in a folder called modules/example. The module creates an AWS S3 bucket. The source points to the local path, and the bucket name is passed as a variable.
terraform
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.0"
}
}
}
provider "aws" {
region = "us-east-1"
}
module "s3_bucket" {
source = "./modules/s3_bucket"
bucket_name = "my-unique-bucket-12345"
}
# modules/s3_bucket/main.tf
# resource "aws_s3_bucket" "this" {
# bucket = var.bucket_name
# }
# modules/s3_bucket/variables.tf
# variable "bucket_name" {
# type = string
# }
Output
Terraform will create an AWS S3 bucket named "my-unique-bucket-12345" using the module code from the local path ./modules/s3_bucket.
Common Pitfalls
Common mistakes when using source in modules include:
- Using an incorrect path or URL, causing Terraform to fail to find the module.
- Forgetting to initialize Terraform with
terraform initafter adding or changing modules. - Not passing required variables to the module, leading to errors.
- Using relative paths incorrectly, especially when running Terraform from different directories.
terraform
module "bad_module" { source = "./wrong_path" # This will cause an error because the path does not exist } # Correct usage: module "good_module" { source = "./modules/good_path" # Pass required variables here }
Quick Reference
Tips for using source in Terraform modules:
- Use
terraform initto download modules after adding them. - Local paths start with
./or../. - Git URLs can include branches or tags, e.g.,
git::https://github.com/user/repo.git?ref=v1.0.0. - Terraform Registry modules use the format
namespace/name/provider.
Key Takeaways
Use the source argument inside a module block to specify where the module code lives.
The source can be a local path, Git repository, or Terraform Registry address.
Always run terraform init after adding or changing modules to download them.
Pass all required variables to the module to avoid errors.
Check paths carefully to avoid module not found errors.