Protect Your Secrets in Environment Variables
3 min readSep 6, 2023
with 1Password’s Cli.
It was quite a journey for me to find a use case for 1Password’s CLI , but it has proven to be both effective and helpful!
After experimenting with it on a sunny afternoon by the pool, I wrote two functions for both Zsh and PowerShell.
This essentially elevated the security standard of my development environment to a new level.
I’m excited to share the joy here!
Setting It Up
- You will likely need 1Password 8 to take advantage of this new feature.
- Follow the steps on this link to enable the CLI.
- Exercise naming conventions for your secret like this:
serviceName_tenant_env /keyName, here are a few examples:
- aws_engg_prod/secret
- jc_se_su/apiKey
Alright, done, let’s use it in our dev env.
For PowerShell
- Create or edit your profile in PowerShell, you can find the path by simply just run:
Get-ChildItem $PROFILE
new-item $PROFILE -force #Run this only when you dont have a profile setup prior
- Edit the file with the lines below:
# Read API keys from 1pw
function read-1pwSecret {
[CmdletBinding()]
param (
[Parameter(Position=0)]
[string]$svc,
[Parameter(Position=1)]
[string]$tenant,
[Parameter(Position=2)]
[string]$env,
[Parameter(Position=3)]
[string]$keyname="apiKey"
)
$keypath = "op://Personal/$($svc+"_"+$tenant+"_"+$env)/$keyname"
return op read $keypath
}
$env:TESTKEY = read-1pwSecret -svc testSVC -env ro
- Save the profile and restart the PowerShell session. You will get a nice 1Password login prompt like this:
- And these are my keys! Boom!
So, if you are using MacOS, you can setup this in Zsh, and Python will be able to access it too!
For Zsh & Python
- Add the lines below to your ~/.zshrc profile:
# Mac ~/.Zshrc profile
read_1pwSecret() {
# Default values for optional parameters
keyname="apiKey"
# Positional parameters
svc="$1"
env="$2"
# Optional parameters
[ -n "$3" ] && tenant="$3"
[ -n "$4" ] && keyname="$4"
# Build keypath and invoke 'op' command
keypath="op://Personal/${svc}_${tenant}_${env}/${keyname}"
op read "$keypath"
}
export TESTKEY=$(read_1pwSecret "testSVC" "ro")
- Start a new session and you will get a similar prompt from 1password like above. And the keys look like this:
- Now in Python, the environment variables are accessible via the built-in
os
module:
That’s it! Hope you enjoy it. Thanks for reading thus far.