LastPass + Terraform
I use LastPass for storing/syncing almost all of my internet accounts and always have the lpass
binary installed on my workstation. Recently I was working on some terraform code for a personal project and wanted a way to securely store AWS credentials and various terraform input variables that I didn’t want to have stored in plain text.
Can we use LastPass as a highly-available, encrypted key-value store? Turns out, yes! We can abuse the note field of an account to store whatever blobs of data we’d like.
files
secret.json
{
"my_secret": "hunter2",
"some_vars": [
"foo",
"bar"
]
}
import.sh
#!/usr/bin/env bash
KEY=$1
base64 - \
| lpass add \
--non-interactive \
--notes \
"$KEY"
echo "imported"
export.sh
#!/usr/bin/env bash
KEY=$1
lpass show \
--notes \
"$KEY" \
| base64 -d -
usage
$ ./import.sh secrets/test < secret.json
imported
$ ./export.sh secrets/test
{
"my_secret": "hunter2",
"some_vars": [
"foo",
"bar"
]
}
Why base64 encode/decode? Honestly, I haven’t run into a problem in dealing with plain text, but since I don’t really know much about the underlying storage of the notes
field it seems best to encode to something as portable as possible.
exporting variables for terraform
The next step is to make these variables available to terraform. Given terraform expects the following:
variable "s3_bucket" {}
variable "account_id" {}
And we have the following stored in LastPass:
{
"s3_bucket": "my_secret_bucket",
"account_id": "8675309"
}
We can hack up the data with bash and jq
to export our secrets as environment variables in the format that terraform expects:
#!/usr/bin/env bash
set -eu
fetch_secret() {
local -r key=$1
lpass show --notes "$key" \
| base64 -d -
}
export_to_env() {
local -r key=${1:?<key> is required}
local data keys
data=$(fetch_secret "$key")
keys=($(jq -r 'keys[]' <<< "$data"))
for item in "${keys[@]}"; do
local var val
var="TF_VAR_${item}"
val="$(jq -r --arg k "$item" '.[$k]' <<< "$data")"
echo exporting "$var"
export "${var}"="${val}"
done
}
export_to_env "$1"