Skip to main content
In this guide, you’ll learn how to reference Terraform modules hosted in a private Git repository (GitHub, GitLab, Bitbucket, etc.) and manage authentication securely. By the end, you’ll be able to pin module versions for reproducible Terraform runs.

Prerequisites

  • A Terraform module stored in a private Git repository
  • Credentials configured in your local environment (HTTPS token or SSH key)
  • Terraform CLI installed on your workstation

Authentication Methods

Choose one of the following authentication options to securely fetch private modules:
Avoid hard-coding tokens or keys in your .tf files. Instead, use environment variables, ~/.netrc, or a Git credential helper.

Referencing a Module in Terraform

Insert one of the following snippets into your main.tf. Replace <org>, <repo>, and modules/my_module with your repository and path.

HTTPS Example

SSH Example

  • The double slash (//modules/my_module) specifies the subdirectory within the repository.
  • The ?ref=v1.0.0 suffix pins the module to a tag, branch, or commit.
Embedding credentials in URLs can expose sensitive data if your configuration is shared. Use variables and environment-based authentication whenever possible.

Initializing and Updating Modules

  1. Initialize Terraform and download referenced modules:
  2. After updating the remote module, refresh your local cache:
  3. Review and apply your changes:

Best Practices

  • Always pin module sources with ?ref= to ensure reproducibility.
  • Store API tokens and SSH keys outside of version control.
  • Test module updates in a non-production workspace before rolling out.

Watch Video