0
0
TerraformHow-ToBeginner · 3 min read

How to Use Module from GitHub in Terraform: Simple Guide

To use a module from GitHub in Terraform, specify the source attribute in the module block with the GitHub URL. Terraform will download and use the module code from that repository automatically during terraform init.
📐

Syntax

The module block in Terraform defines a reusable set of resources. To use a module from GitHub, set the source to the GitHub repository URL. You can optionally specify a branch, tag, or commit with ?ref=.

  • module <name>: Names your module instance.
  • source: URL of the GitHub repo containing the module.
  • ref: Optional query to specify branch, tag, or commit.
  • inputs: Variables passed to the module.
hcl
module "example" {
  source = "github.com/owner/repo//path/to/module?ref=branch_or_tag"
  # input variables here
}
💻

Example

This example shows how to use a public Terraform module from GitHub. It uses the source URL with a specific tag and passes input variables.

hcl
terraform {
  required_version = ">= 1.0"
}

module "vpc" {
  source = "github.com/terraform-aws-modules/terraform-aws-vpc?ref=v3.14.2"

  name = "my-vpc"
  cidr = "10.0.0.0/16"

  azs             = ["us-east-1a", "us-east-1b"]
  private_subnets = ["10.0.1.0/24", "10.0.2.0/24"]
  public_subnets  = ["10.0.101.0/24", "10.0.102.0/24"]
}
Output
Terraform will download the VPC module from GitHub and create the specified VPC with subnets when you run terraform init and terraform apply.
⚠️

Common Pitfalls

  • Forgetting to run terraform init after adding a GitHub module will cause errors because Terraform hasn't downloaded the module yet.
  • Not specifying ?ref= can lead to unexpected changes if the default branch updates.
  • Incorrect module path after the repo URL (use // to specify subdirectory) causes Terraform to fail finding the module.
  • Private repositories require authentication setup, otherwise Terraform cannot access the module.
hcl
module "bad_example" {
  source = "github.com/owner/repo/path/to/module" # Missing double slash before path
}

# Correct way:
module "good_example" {
  source = "github.com/owner/repo//path/to/module"
}
📊

Quick Reference

Remember these tips when using GitHub modules in Terraform:

  • Use source = "github.com/owner/repo//path?ref=tag_or_branch"
  • Always run terraform init after adding or changing modules
  • Use tags or branches with ?ref= to avoid unexpected updates
  • For private repos, configure Git credentials or SSH access

Key Takeaways

Use the module block with source set to the GitHub repo URL including optional ref query.
Always run terraform init to download modules before applying.
Specify ?ref= to lock module version to a branch, tag, or commit.
Use double slashes // to specify a subdirectory inside the repo for the module.
Private GitHub repos require authentication setup for Terraform to access.