Vaccano
Vaccano

Reputation: 82487

Convert environment variables into a json file

I am trying to find a way to feed configuration settings into my SPA application that is running in a container.

My current plan is to pass in the configuration as environment variables. Then on container startup, generate a json file from those environment variables to pass to the browser (along with the SPA app).

I am planning to format my environment variables like this:

Env Variable Name:  Security:ClientId 
Env Variable Value: 123456

Env Variable Name:  Security:clientSecret
Env Variable Value: abcdefg

Env Variable Name:  AppSettings:Environment
Env Variable Value: Dev

That will convert into:

{
  "AppSettings": {
    "Environment": "Dev",
  },
  "Security": {
    "ClientId": "123456",
    "ClientSecret": "abcdefg"
  }
}

I am fairly inexperienced at shell scripting, but this has to be done in a shell script so it can run in a Linux container.

I have read of jq, and it seems to be the way to interact with Json files in a shell script. But they all seem to want you to start with an existing json file that you will be transforming to a different json file.

How do I create a new json file from a list of key value pairs, with sub sections and using jq (or something else in a shell script)?

Upvotes: 1

Views: 7465

Answers (2)

peak
peak

Reputation: 116957

The following assumes the "environment variable" names and values could be made available as variable=value strings:

function data {
cat <<EOF
Security:ClientId=123456
Security:clientSecret=abcdefg
AppSettings:Environment=Dev
EOF
}

data | jq -nR '

def parse: capture("(?<x>[^:]*):(?<y>[^=]*)=(?<value>.*)");

reduce inputs as $line ({};
   ($line | parse) as $p
   | .[$p.x][$p.y] = ($p.value) )
'

Output

As shown in the Q.

Upvotes: 4

peak
peak

Reputation: 116957

bash does not allow colons in variable names, so you will probably want to pass in the values using jq's --arg and/or --argjson command-line options, e.g. along the lines of:

jq -n --arg Security_ClientId 123456 \
      --arg Security_clientSecret abcdefg \
      --arg AppSettings_Environment Dev '
{
  "AppSettings": {
    "Environment": $AppSettings_Environment
  },
  "Security": {
    "ClientId": $Security_ClientId,
    "ClientSecret": $Security_clientSecret
  }
}
'

Note that the entire jq program could be put into a file, say config.jq, so the invocation would look like:

jq -n --arg Security_ClientId 123456 \
      --arg Security_clientSecret abcdefg \
      --arg AppSettings_Environment Dev -f config.jq

Using shell environment variables

Security_ClientId=123456
Security_clientSecret=abcdefg
AppSettings_Environment=Dev


jq -n ' {
  "AppSettings": {
    "Environment": env.AppSettings_Environment
  },
  "Security": {
    "ClientId": env.Security_ClientId,
    "ClientSecret": env.Security_clientSecret
  }
}
'

Upvotes: 0

Related Questions