Tyrel's Blog

Code, Flying, Tech, Automation

May 26, 2023

Set Environment Variables with LastPass

I have to use LastPass at work, and I store some API keys in there. Rather than copy/paste and have the actual api key on my terminal, I like to use read -rs ENV_VAR_NAME to set environment variables, so they are hidden from scrollback.

Recently my coworker set something up that we need an environment variable set up for running some Terraform commands. I don't feel like pasting it in every time from LastPass, so I figured out how to set this up and automate it. I'm sure I've already talked a lot about how I love direnv and I maintain a lot of different .envrc files for work things. For my last team I had one per repo! Well direnv comes to the rescue again.

  • The first step is installing the lastpass-cli.
  • Then you need to set it up so you log in, how you do that is up to you. I have lpass checking status, and if it exits nonzero, then running lpass login again in my direnv.
  • After that you can use lpass show and capture that in a variable to export your API key as an environment variable.
lpass status
if [ $? -ne 0 ]; then
    lpass login email@address.com
fi
export API_KEY=$(lpass show "Secret-Name-Here" --password)

Example .envrc file.

I love automating things, and when a coworker says "oh no we have to do this"... I run to automate it!

 · · ·  bash  automation  work