Skip to content

Instantly share code, notes, and snippets.

@rudolphjacksonm
Created December 17, 2021 14:49
Show Gist options
  • Save rudolphjacksonm/bed53100e802df992579e69dfe25fc30 to your computer and use it in GitHub Desktop.
Save rudolphjacksonm/bed53100e802df992579e69dfe25fc30 to your computer and use it in GitHub Desktop.
Rotate CosmosDB Account Key Function
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