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.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
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:| Method | Description | Setup Commands |
|---|---|---|
| HTTPS + Personal Access Token | Use a PAT stored in an environment variable. | bash<br>export GIT_TOKEN="your_token_here"<br>Configure ~/.netrc or a Git credential helper. |
| SSH Keys | Authenticate via your SSH keypair. | bash<br>eval "$(ssh-agent -s)"<br>ssh-add ~/.ssh/id_rsa<br>Add your public key to your Git provider. |
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 yourmain.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.0suffix 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
- Initialize Terraform and download referenced modules:
- After updating the remote module, refresh your local cache:
- 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.