DEV Community

Cover image for Load secrets automatically with 1password and direnv
Alberto Gonzalez Escalante
Alberto Gonzalez Escalante

Posted on

Load secrets automatically with 1password and direnv

Problem

Load automatically secrets stored in 1password as environment variables.

Solution

Global config

## File: ~/.config/direnv/direnv.toml

[global]
load_dotenv = true

[whitelist]
prefix = [ "~/workspace" ]
Enter fullscreen mode Exit fullscreen mode

Root working directory

## File: ~/workspace/.envrc

# Inject 1password secrets into environment
use_sourceop() {
  if printenv | grep -q "op://"; then
    source <(printenv | grep "op://" | op inject)
  fi
}
Enter fullscreen mode Exit fullscreen mode

Project directory

## File: ~/workspace/python/project/.envrc

dotenv_if_exists
source_up_if_exists
use sourceop
Enter fullscreen mode Exit fullscreen mode
## File: ~/workspace/python/project/.env

PROJECT_VAR=<EXAMPLE>
PROJECT_SECRET="op://Private/Python Project Secret/password"
Enter fullscreen mode Exit fullscreen mode

Explanation

In the global configuration file, we enable loading environment variables from .env files by default.
In the root working directory, we create a script for loading secrets from 1password.
In the project directory, we load .env files, add config from the root working directory and finally run the script for loading secrets.

References

Top comments (0)