[英]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.