Image showing a key on a table.

Using Bitwarden CLI and adding your credentials token in one command.

Bitwarden CLI allows users to lookup passwords in their preferred terminal, the BW_SESSION token allows for easy authentication, this guide will show you how to set this in one command...

TLDR

For those that only want the command, here it is:

eval $(bw unlock | grep "export" | cut -c 3-)

Note this requires you to have Bitwarden CLI installed.

Now if you are still interested in what the command does go on to the next section. But before that, ensure you installed Bitwarden CLI like mentioned in the note above.

Explaining commands build-up

Alright the command is built-up out of four sections, let’s put aside the eval command for now and step through the command execution in-order.

bw unlock

This unlocks your Bitwarden vault and by default gives you an output like this:

Your vault is now unlocked!

To unlock your vault, set your session key to the `BW_SESSION` environment variable. ex:
$ export BW_SESSION="secret_token"
> $env:BW_SESSION="secret_token"

You can also pass the session key to any command with the `--session` option. ex:
$ bw list items --session secret_token

Bitwarden gives us advice here how we could add the session key to our environment, the interesting command is the export command. We want to execute that specific command, so we want to use grep for that in our second step:

grep "export"

This grep command will fetch the provided hint by Bitwarden on how to set our session key, and now we come to our last step before executing the export command. Because as you can see there is still a $ in the command, we would be left with $ export BW_SESSION="secret_token" which is almost right but not usable. For that we need the last command cut, with that we can drop the dollar sign.

cut -c 3-

We now cut the first two elements of our grepped command, so now we are left with the eval step and that will evaluate the following command export BW_SESSION="secret_token". Alright you can now try getting a password from your vault like this bw get password *password_name*, for this terminal you should not be prompted for credentials.

Now don’t forget to lock your session if you leave your device unattended.

Example use case

Now what are some actual use cases for the Bitwarden CLI, or better said, why did I want this command. For me, it was unlocking my Ansible vault when executing playbooks, I got very tired of constantly copying my password from the Bitwarden client. What I do now is fetch the password from the Bitwarden CLI and pipe it into the playbook command for setting up my k3s cluster.

Comments