3

I am fetching a AWS Parameter Store JSON response using the AWS cli:

echo $(aws ssm get-parameters-by-path --with-decryption --region eu-central-1 \
  --path "${PARAMETER_STORE_PREFIX}") >/home/ubuntu/.env.json

This outputs something like:

{
  "Parameters": [
    {
      "Name": "/EXAMPLE/CORS_ORIGIN",
      "Value": "https://example.com"
    },
    {
      "Name": "/EXAMPLE/DATABASE_URL",
      "Value": "db://user:pass@host:3306/example"
    }
  ]
}

Instead of writing to a JSON file, I'd like to write to a .env file instead with the following format:

CORS_ORIGIN="https://example.com"
DATABASE_URL="db://user:pass@host:3306/example"

How could I achieve this? I found similar questions like Exporting JSON to environment variables, but they do not deal with nested JSON / arrays

Larsen
  • 33
  • 3

1 Answers1

5

Easy with jq and some string interpolation and @sh to properly quote the Value strings for shells:

$  jq -r '.Parameters[] | "\(.Name | .[rindex("/")+1:])=\(.Value | @sh)"' input.json
CORS_ORIGIN='https://example.com'
DATABASE_URL='db://user:pass@host:3306/example'
Shawn
  • 47,241
  • 3
  • 26
  • 60
  • You can redirect the output to whatever file you want, of course. And you can pipe the `aws` output directly to `jq` instead of using an intermediate file if desired. – Shawn Sep 10 '21 at 09:11
  • 1
    Glad you added the `@sh` filter you initially missed. An alternate `jq` command syntax that does the same: `jq -r '.Parameters[] | (.Name | split("/")[-1])+"="+(.Value | @sh)' input.json` i find clearer than escaping parenthesis – Léa Gris Sep 10 '21 at 09:12
  • I always forget there are ones other than `@csv` until I see them in the manual. – Shawn Sep 10 '21 at 09:25
  • Anyway found this question is a dupe. – Léa Gris Sep 10 '21 at 09:26
  • Wonder if I should post this on that one too (I realized that the variable name can be extracted without a `split()` like I originally had and all the answers there also use)... – Shawn Sep 10 '21 at 09:36