[英]Exporting environment variables for local development and heroku deployment
我想用环境变量设置一些用于开发,登台和生产的文件,例如:
application_root/development.env
KEY1=value1
KEY2=value2
会有类似的文件staging.env
和production.env
。
我正在寻找几个不同的bash脚本,这些脚本允许在开发或暂存/生产中加载所有这些变量。
在本地开发中,我想有效地为文件中的每一行运行export KEY1=value1
。
对于登台/制作,我将部署到Heroku,并希望有效地运行heroku config:set -a herokuappname KEY1=value1
为staging
或production.env
文件中的每一行heroku config:set -a herokuappname KEY1=value1
。
我知道有一些宝石设计用于这样做,但似乎这可能非常简单。 我也喜欢将.env
文件作为简单的键和值列表的灵活性,而不是特别绑定到任何语言/框架。 如果我不得不改变一些关于这些变量需要加载的方式,那就是更改脚本而不是.env
文件。
在最简单的形式中,您可以将键值对加载到bash
数组中,如下所示:
IFS=$'\n' read -d '' -ra nameValuePairs < ./development.env
在Bash v4 +中,它甚至更简单:
readarray -t nameValuePairs < ./development.env
然后,您可以将生成的"${nameValuePairs[@]}"
数组传递给诸如export
或heroku config:set ...
命令heroku config:set ...
; 例如:
export "${nameValuePairs[@]}"
但请注意,如果输入*.env
文件满足以下所有条件,则上述操作仅按预期工作:
<key>=<value>
,周围没有空格=
对于不符合此严格格式的文件,需要采用不同的方法; 例如, 此相关问题处理可能包含引用值的文件。
下面是名为load_env
的bash
脚本的源代码( .sh
后缀通常不是必需且不明确的):
你会与调用它*.env
感兴趣的文件,它会执行相应的操作(运行heroku config:set …
或export
基础上的文件名 )。
然而,按照规定,必须执行此脚本(使用source
或者其有效bash
别名.
为了营造环境变量() export
),以当前 shell可见。
为了防止模糊的故障,如果您传递了development.env
文件并且在没有采购的情况下调用了脚本,脚本会抱怨。
例子:
./load_env ./staging.dev
. ./load_env ./development.dev # !! Note the need to source
load_env
源代码 #!/usr/bin/env bash
# Helper function that keeps its aux. variables localized.
# Note that the function itself remains defined after sourced invocation, however.
configOrExport() {
local envFile=$1 doConfig=0 doExport=0 appName
case "$(basename "$envFile" '.env')" in
staging)
doConfig=1
# Set the desired app name here.
appName=stagingapp
;;
production)
doConfig=1
# Set the desired app name here.
appName=productionapp
;;
development)
doExport=1
;;
*)
echo "ERROR: Invalid or missing *.env file name: $(basename "$envFile" '.env')" >&2; exit 2
esac
# Make sure the file exists and is readable.
[[ -r "$envFile" ]] || { echo "ERROR: *.env file not found or not readable: $envFile" >&2; exit 2; }
# If variables must be exported, make sure the script is being sourced.
[[ $doExport -eq 1 && $0 == "$BASH_SOURCE" ]] && { echo "ERROR: To define environment variables, you must *source* this script." >&2; exit 2; }
# Read all key-value pairs from the *.env file into an array.
# Note: This assumes that:
# - the keys are syntactically valid shell variable names
# - the lines contain no quoting and no leading or trailing whitespace
# - there are no empty/blank lines or comment lines in the file.
IFS=$'\n' read -d '' -ra nameValuePairs < "$envFile"
# Run configuration command.
(( doConfig )) && { heroku config:set -a "$appName" "${nameValuePairs[@]}" || exit; }
# Export variables (define as environment variables).
(( doExport )) && { export "${nameValuePairs[@]}" || exit; }
}
# Invoke the helper function.
configOrExport "$@"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.