Managing private Go modules efficiently often requires a tailored setup, especially when using custom SSH keys for multiple repositories. This guide walks you through configuring your environment to seamlessly work with private Go packages using SSH keys.

Step 1: Update the GOPRIVATE Environment Variable

First, ensure your GOPRIVATE environment variable includes the repositories you intend to access privately. This prevents Go from checking these paths with public proxies or mirrors.

export GOPRIVATE=github.com/yourorg/yourrepo1,github.com/yourorg/yourrepo2

Step 2: Configure SSH Hostnames in .gitconfig

When working with multiple repositories that use deploy keys, it’s common to define unique SSH hostnames in your SSH configuration (~/.ssh/config). For example, you might use r1.github.com for yourrepo1 and r2.github.com for yourrepo2.

Next, map these SSH hostnames to your repositories within your Git configuration. This ensures that Git uses the correct SSH key when interacting with each repository.

Add the following to your ~/.gitconfig:

[url "ssh://git@r1.github.com/yourorg/yourrepo1"]
    insteadOf = https://github.com/yourorg/yourrepo1
[url "ssh://git@r2.github.com/yourorg/yourrepo2"]
    insteadOf = https://github.com/yourorg/yourrepo2

This configuration tells Git to substitute the HTTPS URLs with their SSH equivalents, ensuring secure and streamlined access.

Step 3: Set Up Global Git Configurations (Optional)

If you prefer to apply these settings globally, you can use the git config --global command. This is especially useful if you manage multiple projects or frequently switch environments.

git config --global url."ssh://git@r1.github.com/yourorg/yourrepo1".insteadOf "https://github.com/yourorg/yourrepo1"
git config --global url."ssh://git@r2.github.com/yourorg/yourrepo2".insteadOf "https://github.com/yourorg/yourrepo2"

Conclusion

By following these steps, you’ll have a robust setup for managing private Go packages using custom SSH keys, allowing you to focus on coding rather than configuration issues. This setup is particularly beneficial for organizations and teams working with private repositories that require secure and reliable access methods.