I'm using Terraform with Digital Ocean from a linux desktop, but the same problem exists with other service providers: you need to provide some kind of secret for authentication, but you don't want the secret to be in your terraform files where they can accidentally be checked into revision control, thus shared with a thousand of your closest friends and hackers, not to mention search engines.
Most Terraform tutorials and such suggest you put the secret into an environment variable, and then run terraform with something like "terraform plan -var "do_pat=${DO_PAT}" " That works, but now you need to add a parameter to terraform every time you run it. Probably not a big deal when you're using automated CI/CD-type stuff, but if you're running things manually, it's a pain.
If you dig just a little deeper, you realize you can name your environment variable "TF_VAR_do_pat" and drop the -var parameter all-together. Awesome! Now you just need to modify your environment to have the variable set, probably at login.
But wait! There's another way! Keychains! Modern operating systems have mechanisms to store keys somewhat securely. In linux, there's an in-kernel keychain that is ephemeral, and Gnome has a per-user keychain that is persistent. It unlocks automagically when you log in. Turns out, we can use that keychain to get secrets into Terraform!
terraform {
required_providers {
digitalocean = {
source = "digitalocean/digitalocean"
}
external = {
source = "hashicorp/external"
}
}
}
provider "digitalocean" {
token = data.external.dopat.result.secret
}
data "external" "dopat" {
program = ["/usr/bin/python", "-c", "import keyring,json; print(json.dumps({'secret': keyring.get_password('login', 'doPAT')}))"]
}
Now we just need to store the secret in the keyring:
python -c "import keyring; keyring.set_password('login', 'doPAT', 'mySecretNotYourSecretGetYourOwn')"
You can look at what keys you already have in your keyring by running Gnome Seahorse, also known as "Passwords and Keys". I couldn't create usefull keys in Seahorse, but I could edit them. YMMV.
Thank you for letting me know about this GIST.
I am glad you found my document on the Gnome KeyRing useful.
https://antofthy.gitlab.io/info/crypto/keyring_gnome.txt
Part of my notes on cryptography and encryption, floor of the "Tower Of Computation"
https://antofthy.gitlab.io/info/crypto/
I have updated the document with the better example, and a link back to this GIST.
Anthony