如何将 JSON 转换为环境变量文件格式?

Lar*_*sen 3 bash shell json environment-variables jq

我正在使用 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
Run Code Online (Sandbox Code Playgroud)

这输出类似:

{
  "Parameters": [
    {
      "Name": "/EXAMPLE/CORS_ORIGIN",
      "Value": "https://example.com"
    },
    {
      "Name": "/EXAMPLE/DATABASE_URL",
      "Value": "db://user:pass@host:3306/example"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

我不想写入 JSON 文件,.env而是使用以下格式写入文件:

CORS_ORIGIN="https://example.com"
DATABASE_URL="db://user:pass@host:3306/example"
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?我发现了类似的问题,例如Exporting JSON toenvironmentvariables,但它们不处理嵌套的 JSON/数组

Sha*_*awn 5

轻松进行jq一些字符串插值并@sh正确引用 shell 的值字符串:

$  jq -r '.Parameters[] | "\(.Name | .[rindex("/")+1:])=\(.Value | @sh)"' input.json
CORS_ORIGIN='https://example.com'
DATABASE_URL='db://user:pass@host:3306/example'
Run Code Online (Sandbox Code Playgroud)