DEV Community

sugendran
sugendran

Posted on

Securing environment variables with lastpass

One thing I've struggled with in the past is where to put your secret tokens that you need for accessing an API. If you stick it in a .env file then anyone with access to your machine will be able to read it. If you paste it into your shell then it will appear in your shell's history. Yes you can use pbpaste but then you need to have the token somewhere else to copy before you paste it. I think I've stumbled onto the best way to solve this - the lastpass cli and a script for loading the content of a secure note.

Let's get on with it.

The first thing to do is to install the lastpass cli. Assuming you're using a Mac you can install it with brew. If you're not using a Mac there are other installation methods in the lastpass cli docs.

brew install lastpass-cli

You'll be able to log into lastpass in your shell by executing lpass login <username> and then following the prompts.

Next we install the script to your /usr/local/bin and make it executable. You should go have a read of the script and make sure you trust it before doing this step. It's very nicely laid out, and hopefully you can understand it enough to trust it.

curl https://raw.githubusercontent.com/luketurner/lpass-env/master/bin/lpass-env -o /usr/local/bin/lpass-env && chmod +x /usr/local/bin/lpass-env

Now head over to lastpass and create a folder called .env. I've called it this but in reality you can call it whatever you want. I like the idea of having all your scripts in the one folder so that you know where they are. The next thing to do is to create the first script. I've created one called github that has the following content:

GITHUB_TOKEN=MYMAGICTOKEN

Executing the following will load an environment variable called GITHUB_TOKEN with the value MYMAGICTOKEN

$(lpass-env export .env/github)

Amazing, right!?

Since I'm lazy and I have also added the following function to my .zshrc - it should work with your .bashrc as well.

function loadcreds() {
    $(lpass-env export .env/$1)
}

Now I can exec loadcreds github and it will load the credentials for me.

Top comments (3)

Collapse
 
brandtdaniels profile image
Brandt Daniels

I had a lot of trouble with this section since I'm new to lastpass:

Now head over to lastpass and create a folder called .env. I've called it this but in reality you can call it whatever you want. I like the idea of having all your scripts in the one folder so that you know where they are. The next thing to do is to create the first script. I've created one called github that has the following content:

Maybe you could elaborate more there.

Also, I have several values that contain space like
APP_NAME="My App Name"

The script couldn't handle those spaces...any thoughts on that?

Collapse
 
hokageyondaime profile image
Jony Ives

is there any update on this or this is the latest?

Collapse
 
hokageyondaime profile image
Jony Ives

I think this is the latest..