Environment variable setting through the 1password CLI

2 minute read

The 1password CLI

The 1password CLI allows users to fetch fields from their password manager and insert them directly into their shell environment. This can be really helpful when dealing with secrets:

> export API_KEY=$(op read "op://Private/API_PROD/api_key") python3 request.py
      

Some advantages of doing this over setting each key manually, relying on your command history, or even adding it to your ~/.*rc file, are:

A little more interesting

Changing your API_KEY most likely requires you to change other variables. Let's say there's API_ENDPOINT and API_USER. This switch from one environment to another can be encapsulated into a shell function enabling you to save precious keystrokes.

# in your .zshrc or .bashrc
function staging_credentials_export() {
  echo "Setting staging credentials environment..."
  export API_USER=$(op read "op://Private/API_STAGING/username")
  export API_KEY=$(op read "op://Private/API_STAGING/credential")
  export API_ENDPOINT=$(op read "op://Private/API_STAGING/endpoint")
  echo "... done!"
}

function prod_credentials_export() {
  echo "Setting prod credentials environment..."
  export API_USER=$(op read "op://Private/API_PROD/username")
  export API_KEY=$(op read "op://Private/API_PROD/credential")
  export API_ENDPOINT=$(op read "op://Private/API_PROD/endpoint")
  echo "... done!"
}     

Refactored:

function api_credentials_export(){
  if [[ "$1" == "staging" ]]; then
        directory="op://Private/API_STAGING"
  fi
  if [[ "$1" == "prod" ]]; then
        directory="op://Private/API_PROD"
  fi

  export API_USER=$(op read $directory"/username")
  export API_KEY=$(op read $directory"/credential")
  export API_ENDPOINT=$(op read $directory"/endpoint")
}     
Then in your terminal:
> api_credentials_export "staging"
> python3 request.py
      

Sweet!