Created
February 6, 2023 08:15
-
-
Save peevees/1a17a42369610997c98d6a6c099b888f to your computer and use it in GitHub Desktop.
JQ example of merging files and replacing with environment variables values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Read base json file | |
if [ -f "base.json" ]; then | |
# Read the file into a variable | |
json_base=$(jq '.' base.json) | |
else | |
printf "Base json file does not exist and is required" | |
exit 1; | |
fi | |
# Read variable specific json file and merge it into base | |
if [ -f "base.${{ env.VARIABLE }}.json" ]; then | |
# Read the file and merge it into the base | |
printf "Merging base.${{ env.VARIABLE }}.json into base Json\n" | |
json_base=$(jq -s '.[0] * .[1]' <(echo $json_base) base.${{ env.VARIABLE }}.json) | |
else | |
printf "Configuration for base.${{ env.VARIABLE }} does not exist but isn't required\n" | |
fi | |
# Use jq to add environment variable to replace placeholder values in the base json and create the final form and save the file | |
# this will look for a string $VARIABLE2 anywhere in the json and replace it with the environment value of VARIABLE2 | |
printf "Current base json:\n$json_base\n"; | |
printf "Replacing placeholders with environment variables\n"; | |
jq --arg VARIABLE2 "$VARIABLE2" \ | |
'walk(if type == "string" then | |
gsub("\\$VARIABLE2"; $VARIABLE2) | | |
else . end)' <(echo -n $json_base) > json_finale.json; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment