Skip to content

Instantly share code, notes, and snippets.

@ardiesaeidi
Created November 27, 2019 02:16
Show Gist options
  • Save ardiesaeidi/589156cda53189ca46ae6064e505de96 to your computer and use it in GitHub Desktop.
Save ardiesaeidi/589156cda53189ca46ae6064e505de96 to your computer and use it in GitHub Desktop.
Update json file using jq in bash shell
#!/bin/sh
updateAllowedHosts() {
if [ -n "$ECS_CONTAINER_METADATA_FILE" ]; then
echo "getting ecs container metadata file '$ECS_CONTAINER_METADATA_FILE'"
local appSettings='appsettings.json'
local currentHosts=
# check if env appsettings exist
if [ -n $ASPNETCORE_ENVIRONMENT ] && [ -f "appsettings.${ASPNETCORE_ENVIRONMENT}.json" ]; then
echo "found env specific appsettings for '${ASPNETCORE_ENVIRONMENT}'"
appSettings="appsettings.${ASPNETCORE_ENVIRONMENT}.json"
fi
local hostIp=$(cat $ECS_CONTAINER_METADATA_FILE | jq -r 'select(.HostPrivateIPv4Address != null) | .HostPrivateIPv4Address')
if [ -n "${hostIp}" ]; then
currentHosts=$(cat "${appSettings}" | jq -r 'select(.AllowedHosts != null) | .AllowedHosts')
local allowedHosts=
[ -n "${currentHosts}" ] && allowedHosts="${currentHosts};${hostIp}" || allowedHosts=$hostIp
echo "adding allowed hosts '${allowedHosts}'"
$(cat $appSettings | jq -e ".AllowedHosts = \"${allowedHosts}\"" > "${appSettings}.tmp" && cp "${appSettings}.tmp" $appSettings)
else
echo 'no ecs host ip was found!'
fi
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment