Create a storage account and rotate its account access keys

This script creates an Azure Storage account, displays the new storage account's primary access key, then renews (rotates) the key.

This sample requires the Azure PowerShell module version 5.1.1 or later. Run Get-Module -ListAvailable AzureRM to find the version. If you need to install or upgrade, see Install Azure PowerShell module.

Run Login-AzureRmAccount to create a connection with Azure.

If you don't have an Azure subscription, create a 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-AzureRmLocation | select Location

# save the location you want to use  
$location = "eastus"

# create a resource group
$resourceGroup = "rotatekeystestrg"
New-AzureRmResourceGroup -Name $resourceGroup -Location $location 

# create a standard general-purpose storage account 
$storageAccountName = "contosotestkeys"
New-AzureRmStorageAccount -ResourceGroupName $resourceGroup `
  -Name $storageAccountName `
  -Location $location `
  -SkuName Standard_LRS `

# retrieve the first storage account key and display it 
$storageAccountKey = (Get-AzureRmStorageAccountKey -ResourceGroupName $resourceGroup -Name $storageAccountName).Value[0]

Write-Host "storage account key 1 = " $storageAccountKey

# re-generate the key
New-AzureRmStorageAccountKey -ResourceGroupName $resourceGroup `
    -Name $storageAccountName `
    -KeyName key1

# retrieve it again and display it 
$storageAccountKey = (Get-AzureRmStorageAccountKey -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-AzureRmResourceGroup -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-AzureRmLocation Gets all locations and the supported resource providers for each location.
New-AzureRmResourceGroup Creates an Azure resource group.
New-AzureRmStorageAccount Creates a Storage account.
Get-AzureRmStorageAccountKey Gets the access keys for an Azure Storage account.
New-AzureRmStorageAccountKey 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.