Rotate storage account access keys with PowerShell
This script creates an Azure Storage account, displays the new storage account's primary access key, then renews (rotates) the key.
This sample requires Azure PowerShell. Run Get-Module -ListAvailable Az
to find the version.
If you need to install or upgrade, see Install Azure PowerShell module.
Run the Connect-AzAccount cmdlet to connect to Azure.
If you don't have an Azure subscription, create an Azure free account before you begin.
Sample script
# this script will show how to rotate one of the access keys for a storage account
# get list of locations and pick one
Get-AzLocation | select Location
# save the location you want to use
$location = "eastus"
# create a resource group
$resourceGroup = "rotatekeystestrg"
New-AzResourceGroup -Name $resourceGroup -Location $location
# create a standard general-purpose storage account
$storageAccountName = "contosotestkeys"
New-AzStorageAccount -ResourceGroupName $resourceGroup `
-Name $storageAccountName `
-Location $location `
-SkuName Standard_LRS `
# retrieve the first storage account key and display it
$storageAccountKey = (Get-AzStorageAccountKey -ResourceGroupName $resourceGroup -Name $storageAccountName).Value[0]
Write-Host "storage account key 1 = " $storageAccountKey
# re-generate the key
New-AzStorageAccountKey -ResourceGroupName $resourceGroup `
-Name $storageAccountName `
-KeyName key1
# retrieve it again and display it
$storageAccountKey = (Get-AzStorageAccountKey -ResourceGroupName $resourceGroup -Name $storageAccountName).Value[0]
Write-Host "storage account key 1 = " $storageAccountKey
Clean up deployment
Run the following command to remove the resource group, storage account, and all related resources.
Remove-AzResourceGroup -Name rotatekeystestrg
Script explanation
This script uses the following commands to create the storage account and retrieve and rotate one of its access keys. Each item in the table links to command-specific documentation.
Command | Notes |
---|---|
Get-AzLocation | Gets all locations and the supported resource providers for each location. |
New-AzResourceGroup | Creates an Azure resource group. |
New-AzStorageAccount | Creates a Storage account. |
Get-AzStorageAccountKey | Gets the access keys for an Azure Storage account. |
New-AzStorageAccountKey | Regenerates an access key for an Azure Storage account. |
Next steps
For more information on the Azure PowerShell module, see Azure PowerShell documentation.
Additional storage PowerShell script samples can be found in PowerShell samples for Azure Blob storage.