Use ssh instead of https for Terraform modules
When you use Terraform modules that are hosted on GitHub, you tend to set up the module reference with https
as the protocol because you can use an auth token in CI/CD.
This then requires you to use a Personal Access Token when working locally.
What if you could use ssh instead?
There are several environmental factors that required me to use this solution:
- My business is using a GitHub Organisation
- Access to this Organisation is federated with our businesses Active Directory
- We are hosting repositories containing Terraform modules in the private organisation
- I don’t want to use ‘Personal Access Tokens’ because I have a perfectly good ssh key
My organisation have set up your modules to look like so:
module "my_module" {
source = "git::https://github.com/[org]/[project].git?ref=v1.2.3"
// variables
}
This is fantastic for a fully GitHub ecosystem, but when I try to run terraform get
on my laptop — so IntelliJ can resolve the required variables for the module — Terraform prompts me for my GitHub username/password:
$ terraform get
Downloading git::https://github.com/[org]/[project].git?ref=v1.2.3 for my_module...
Username for 'https://github.com':
Password for 'https://pwhittlesea@github.com':
Error: Failed to download module
Could not download module "my_module" source code from "git::https://github.com/[org]/[project].git?ref=v1.2.3": error downloading
remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/[org]/[project].git/'
When you head over to the documentation you are recommended to use a ‘Personal Access Token’ to download the HTTPS module.
I could create a Classic Personal Access Token and configure SSO to authorise it for my organisation, but given I already have my ssh key configured, why don’t I use that instead?
If I add the following to ~/.gitconfig
then when downloading each module, Terraform will switch out the https
for ssh
:
[url "ssh://git@github.com"]
insteadOf = https://github.com
Now when I run terraform get
:
$ terraform get
Downloading git::https://github.com/[org]/[project].git?ref=v1.2.3 for my_module...
- my_module in .terraform/modules/my_module
Success!