ElastiCache may disable commands like save
or bgsave
. For reference, check Restricted Redis Commands.
The following bash script solution supports datatypes string and hash. If you want support for other data types (e.g., set, list, sorted set, bitmap), you have to extend the script (as commented in the script).
#!/bin/bash
# change KEY_PATTERN accordingly if you want a subset of the keys in redis cache
KEY_PATTERN="*"
# provide the default redis url here if you don't supply that from command line/environment:
if [[ -z $REDIS_SERVICE_URL ]]; then
REDIS_SERVICE_URL=redis://localhost:6379
fi
IFS=' '
iKey=0 # counter to iterate over the keys
echo {
# iterate through the keys in redis:
while read key; do
if [ $iKey -gt 0 ]; then
echo ","
fi
echo \"$key\":
# get the datatype for the current key
datatype=$(redis-cli -u "$REDIS_SERVICE_URL" type "$key")
# this script supports string/hash datatype.
# Extend if you want to support other data types.
if [ "$datatype" = 'string' ]; then
val=$(redis-cli -u "$REDIS_SERVICE_URL" get "$key")
echo -n \"${val//\"/\\\"}\"
elif [ "$datatype" = 'hash' ]; then
echo [
i=0
while read val; do
if [ $i -gt 0 ]; then
echo ","
fi
echo \"${val//\"/\\\"}\"
i=$((i+1))
done <<< $(redis-cli -u "$REDIS_SERVICE_URL" hgetall "$key")
echo ]
else
echo Unsupported type $datatype
exit -1
fi
iKey=$((iKey+1))
done <<< $(redis-cli -u "$REDIS_SERVICE_URL" keys "$KEY_PATTERN")
echo }
unset IFS
Formatted JSON of a sample output using above script:
{
"vlaue-key-1": "value-1",
"hash-key-1": [
"key-a",
"value of key-a in hash-key-1",
"key-b",
"20"
],
"vlaue-key-2": "25.5",
"hash-key-2": [
"key-x",
"value-x of hash-key-2/key-x",
"key-b",
"9999"
]
}