json - 如何将 JSON 转换为环境变量文件格式?
问题描述
我正在使用 AWS cli 获取 AWS Parameter Store JSON 响应:
echo $(aws ssm get-parameters-by-path --with-decryption --region eu-central-1 \
--path "${PARAMETER_STORE_PREFIX}") >/home/ubuntu/.env.json
这会输出如下内容:
{
"Parameters": [
{
"Name": "/EXAMPLE/CORS_ORIGIN",
"Value": "https://example.com"
},
{
"Name": "/EXAMPLE/DATABASE_URL",
"Value": "db://user:pass@host:3306/example"
}
]
}
我不想写入 JSON 文件,.env
而是使用以下格式写入文件:
CORS_ORIGIN="https://example.com"
DATABASE_URL="db://user:pass@host:3306/example"
我怎么能做到这一点?我发现了类似的问题,例如Exporting JSON to environment variables,但它们不处理嵌套的 JSON/数组
解决方案
易于使用jq
和一些字符串插值,并@sh
正确引用 shell 的 Value 字符串:
$ jq -r '.Parameters[] | "\(.Name | .[rindex("/")+1:])=\(.Value | @sh)"' input.json
CORS_ORIGIN='https://example.com'
DATABASE_URL='db://user:pass@host:3306/example'