Created
December 17, 2021 14:49
-
-
Save rudolphjacksonm/bed53100e802df992579e69dfe25fc30 to your computer and use it in GitHub Desktop.
Rotate CosmosDB Account Key Function
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
function rotate_keys() { | |
local keyKind=$1 | |
local cosmosDBAccountName=$2 | |
local rgName="${2%-mongo}" | |
currentConnString=$(az cosmosdb keys list -n "${cosmosDBAccountName}" -g "${rgName}" --type connection-strings -o tsv --query "connectionStrings[? contains(description, '${keyKind:1} MongoDB')].connectionString") | |
# Start key rotation | |
if az cosmosdb keys regenerate -n "${cosmosDBAccountName}" -g "${rgName}" --key-kind "${keyKind}" --verbose; then | |
echo "Key rotation for ${cosmosDBAccountName} succeeded, retrieving ${keyKind} key" | |
newConnString=$(az cosmosdb keys list -n "${cosmosDBAccountName}" -g "${rgName}" --type connection-strings -o tsv --query "connectionStrings[? contains(description, '${keyKind:1} MongoDB')].connectionString") | |
else | |
echo "Key rotation for ${cosmosDBAccountName} failed! Unable to retrieve ${keyKind} key!" | |
exit 1 | |
fi | |
# Compare current and new key to ensure new key has been fetched; if not, retry | |
until [[ "${currentConnString}" != "${newConnString}" ]]; do | |
echo 'Stale connection string has been fetched, retrying in 5 seconds...' | |
sleep 5 | |
newConnString=$(az cosmosdb keys list -n "${cosmosDBAccountName}" -g "${rgName}" --type connection-strings -o tsv --query "connectionStrings[? contains(description, '${keyKind:1} MongoDB')].connectionString") | |
done | |
echo "${newConnString}" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment