Why do you have two access keys for Azure Storage?

On more than one occasion developers do not see the sense to have two keys for an Azure Storage account when they always use the first one to its developments. The truth is that I have found that most of the time there is no key maintenance to improve the security of the storage account.

Azure Storage - Manage Access Keys
Azure Storage – Manage Access Keys

The idea with this pair of keys is to always have a “backup key” when you regenerate one of them so that there is no loss of service at any time. The upgrade process in this case could be the following:

  1. The first key is used in your applications.
  2. When it’s time to regenerate the keys, change the first key for the second key in your applications settings that are using it.
  3. Regenerate the primary key and again change the secondary key with the new one generated.
  4. Regenerate the second key.

This process can easily be automated using PowerShell:

Param(
[string]$StorageName,
[string]$WebAppName,
[string]$ConnectionStringName
)

#Get Azure Storage Account

$StorageAccount = Get-AzureAccount -Name $StorageName;

#Get Secondary Access Key

$SecondayAccessKey = (Get-AzureStorageKey -StorageAccountName $StorageName).Secondary;

Write-Output "Current Secondary Access Key: $SecondayAccessKey";

#Change Primary Access Key in my application to the Secondary Access Key

$MyWebSite = Get-AzureWebsite -Name $WebAppName;

$ConnectionStrings = (Get-AzureWebsite $WebAppName -Slot "production").ConnectionStrings;

$NewConnectionString = "DefaultEndpointsProtocol=https;AccountName=returngisstorage;AccountKey=" + $SecondayAccessKey;

$ConnectionStrings.Find({ param($m) $m.Name.Equals($ConnectionStringName) }).ConnectionString = $NewConnectionString;

#Update the connection string

Set-AzureWebsite $WebAppName -ConnectionStrings $ConnectionStrings;

Write-Output "Primary Access Key Replaced with Secondary Access Key";

#Regenerate Primary Access Key

$PrimaryAccessKey = (New-AzureStorageKey -StorageAccountName $StorageName -KeyType Primary).Primary;

Write-Output "Primary Access Key Regenerated: $PrimaryAccessKey";

#Change Secondary Access key to my new Primary Access Key

$NewConnectionString = "DefaultEndpointsProtocol=https;AccountName=returngisstorage;AccountKey=" + $PrimaryAccessKey;

$ConnectionStrings.Find({ param($m) $m.Name.Equals($ConnectionStringName) }).ConnectionString = $NewConnectionString;

#update the connection string

Set-AzureWebsite $WebAppName -ConnectionStrings $ConnectionStrings;

Write-Output "Secondary Access Key replaced with a new Primary Access Key";

#Regenerate Secondary Access Key

$SecondaryAccessKey = (New-AzureStorageKey -StorageAccountName $StorageName -KeyType Secondary).Secondary;

Write-Output "Secondary Access Key regenerated: $SecondayAccessKey";

Write-Output "Done";

TGIF!