我正在编写一个脚本,将配置变量从云存储服务复制到环境变量(仅用于本地开发,以避免在应用程序或测试服务器启动时发出大量请求)。我已经有一个文件,该文件是用行分隔的变量名称列表。
我知道如何使用已知名称设置环境变量:
export SOME_VAR=some_value
我不知道如何使用“未知”(在写时)名称设置环境变量。因此,我读了该文件的变量名,并遍历列表,请求并exporting
每个变量。
所以主要问题是:如何在运行时以编程方式设置名称仅存在于字符串中的环境变量?
您的脚本实际上不应该与cat | while一起使用,因为在这种情况下,while将在子进程中执行,而任何set或export只会影响子进程。循环结束后,所有变量将丢失。
尝试这个:
#! /usr/bin/env bash
while IFS= read -r line; do
export $(echo ${line^^})=$(get_value_from_secret_store "$line")
done < list_of_vars_file.txt
我知道了!
如果您在$value
中具有所需的值,而您想要在$name
中设置的环境变量的名称,则可以执行此操作:
export "$name"="$value"
奖金提示:
我还需要大写变量名,可以使用:
up_name="$(echo "$name" | tr '[:lower:]' '[:upper:]'"
所以我的最终脚本最终是:
#! /usr/bin/env bash
cat < list_of_vars_file.txt | while IFS= read -r line; do
value="$(get_value_from_secret_store "$line")"
up_name="$(echo "$line" | tr '[:lower:]' '[:upper:]')"
export "$up_name"="$value"
done
``
So the env vars can be copied from the secret store (e.g. vault) to the current shell's environment by sourcing that script (After the correct secret retrieval command is swapped in, of course)