采用
.env(dotenv)文件在开发中扮演着非常重要的角色,思想源于12 Factors Config。
.env对于Node.js开发人员基本上是家常便饭,每天都接触,JS引擎三剑客,Node.js, Deno, Bun,都是内置支持.env文件的,
但是其他语言的开发工程师则未必,所以强调一下。
我个人在实际的项目开发中,基本上也是配置.env优先,即便是Spring Boot项目,我也会在application.properties添加以下配置:
spring.config.import=optional:file:.env.properties
有同学可能会问,如果是结构化的配置,如下:
config = {
"FOO": [{
"BAR": "setting-1",
"BAZ": "setting-2",
}, {
"BAR": "setting-3",
"QUE": "setting-4",
}],
"FIZZ": [
"setting-5",
"setting-6",
],
"BILL": "setting-7",
}
那么应该如下通过环境变量实现? 你可以采用以下规范,其实就是使用__对环境变量名进行分割:
export FOO__1__BAR=setting-1
export FOO__1__BAZ=setting-2
export FOO__2__BAR=setting-3
export FOO__2__QUE=setting-4
export FIZZ__1=setting-5
export FIZZ__2=setting-6
export BILL=setting-7
dotenv-vault项目非常不错,能够解决.env文件的安全问题,推荐一下。
如果你使用direnv,那么只需要在.envrc文件添加一下dotenv或dotenv_if_exists就会自定加载.env文件中环境变量。
dotenv & Friends
- dotenv-vault: sync .env files between machines, environments, and team members https://www.dotenv.org/
- dotenv-linter: linter for .env files - https://github.com/dotenv-linter/dotenv-linter
References
- Dotenv File Format: https://hexdocs.pm/dotenvy/dotenv-file-format.html
- 12 Factors Config: Store config in the environment - https://12factor.net/config
- Structured data in environment variables: https://charemza.name/blog/posts/software-engineering/devops/structured-data-in-environment-variables/