Terraform Enterprise Creds Helper – WeAreServian

Tristan Morgan

With the advent of Terraform Enterprise Free Tier and its remote state becoming available to the greater public, this has created the need to store more credentials. So not wanting to store them in plain text, I am going to show you how to use a script to store them in the macOS keychain.

First, a not very well documented feature of Terraform is in the .terraformrc config file you can specify a credentials_helper. This will allow us to call an external program. The problem is a complete lack of documentation on how to configure it. Digging through the code after the config.go parses the config file the commands.go code calls pluginDiscovery.FindPlugins(“credentials”, globalPluginDirs()). Quickly followed by available.WithName(helperType). The cryptic hints here are that the helper program must be placed in with plugins for your system and it uses a name with “credentials” in it somewhere. Well, there is a bit of a naming scheme that becomes evident and the comment is buried in the plugin/discovery/find.go, its “terraform-$KIND-$NAME-V$VERSION”. The mistake in the comment is it needs a “_v” before the version, So our helper needs to be called “terraform-credentials-$NAME_v$VERSION”.

credentials_helper keychain {  args = []}

Now we have a config file and a name “terraform-credentials-keychain_v1.0.0” next we need to work out what Terraform is expecting the helper program to do. This hint is in some of the test fixtures, the application is called with two parameters, “get” and the FQDN of the Terraform Enterprise server. This is useful because you might be connecting to Private Terraform servers as well the publicly accessible one hosted at “app.terraform.io”. It also shows the response is a JSON string in the format of “{“token”: “our-very-long-token-string”}”. To make life a little easier I’m also going to add a “store” command to my script, not used by Terraform but it will make adding my token a breeze.

#!/bin/shset -ecase $1 in  store)  security add-generic-password -U -a “TF-$USER” -c “htfm” 
-C “htfm” -D “Hashicorp Terraform” -s “$2” -w “$(cat)”
;; get) /bin/echo -n “{”token”: ”$(security find-generic-password
-g -a “TF-$USER” -s “$2” -w)”}”
;; *) echo “Usage: $0 get|store” ;;esac

Save this as “~/.terraform.d/plugins/terraform-credentials-keychain_v1.0.0” and mark it executable. To run the script call it with “./terraform-credentials-keychain_v1.0.0 store app.terraform.io”, enter your TFE token, hit enter then Ctrl-D and it should save. Now we have a secure way to store the token and not leave it on disk to be accidentally committed to code.

Enjoy.