Manage storage account keys with Key Vault and Azure PowerShell
Important
We recommend using Azure Storage integration with Azure Active Directory (Azure AD), Microsoft's cloud-based identity and access management service. Azure AD integration is available for Azure blobs and queues, and provides OAuth2 token-based access to Azure Storage (just like Azure Key Vault). Azure AD allows you to authenticate your client application by using an application or user identity, instead of storage account credentials. You can use an Azure AD managed identity when you run on Azure. Managed identities remove the need for client authentication and storing credentials in or with your application. Use below solution only when Azure AD authentication is not possible.
An Azure storage account uses credentials comprising an account name and a key. The key is autogenerated and serves as a password, rather than an as a cryptographic key. Key Vault manages storage account keys by periodically regenerating them in storage account and provides shared access signature tokens for delegated access to resources in your storage account.
You can use the Key Vault managed storage account key feature to list (sync) keys with an Azure storage account, and regenerate (rotate) the keys periodically. You can manage keys for both storage accounts and Classic storage accounts.
When you use the managed storage account key feature, consider the following points:
- Key values are never returned in response to a caller.
- Only Key Vault should manage your storage account keys. Don't manage the keys yourself and avoid interfering with Key Vault processes.
- Only a single Key Vault object should manage storage account keys. Don't allow key management from multiple objects.
- Regenerate keys by using Key Vault only. Don't manually regenerate your storage account keys.
Important
Regenerating key directly in storage account breaks managed storage account setup and can invalidate SAS tokens in use and cause an outage.
Note
This article uses the Azure Az PowerShell module, which is the recommended PowerShell module for interacting with Azure. To get started with the Az PowerShell module, see Install Azure PowerShell. To learn how to migrate to the Az PowerShell module, see Migrate Azure PowerShell from AzureRM to Az.
Service principal application ID
An Azure AD tenant provides each registered application with a service principal. The service principal serves as the application ID, which is used during authorization setup for access to other Azure resources via Azure RBAC.
Key Vault is a Microsoft application that's pre-registered in all Azure AD tenants. Key Vault is registered under the same Application ID in each Azure cloud.
| Tenants | Cloud | Application ID |
|---|---|---|
| Azure AD | Azure Government | 7e7c393b-45d0-48b1-a35e-2905ddf8183c |
| Azure AD | Azure public | cfa8b339-82a2-471a-a3c9-0fc0be7a4093 |
| Other | Any | cfa8b339-82a2-471a-a3c9-0fc0be7a4093 |
Prerequisites
To complete this guide, you must first do the following:
- Install the Azure PowerShell module.
- Create a key vault
- Create an Azure storage account. The storage account name must use only lowercase letters and numbers. The length of the name must be between 3 and 24 characters.
Manage storage account keys
Connect to your Azure account
Authenticate your PowerShell session using the Connect-AzAccount cmdlet.
Connect-AzAccount
If you have multiple Azure subscriptions, you can list them using the Get-AzSubscription cmdlet, and specify the subscription you wish to use with the Set-AzContext cmdlet.
Set-AzContext -SubscriptionId <subscriptionId>
Set variables
First, set the variables to be used by the PowerShell cmdlets in the following steps. Be sure to update the "YourResourceGroupName", "YourStorageAccountName", and "YourKeyVaultName" placeholders, and set $keyVaultSpAppId to cfa8b339-82a2-471a-a3c9-0fc0be7a4093 (as specified in Service principal application ID, above).
We will also use the Azure PowerShell Get-AzContext and Get-AzStorageAccount cmdlets to get your user ID and the context of your Azure storage account.
$resourceGroupName = <YourResourceGroupName>
$storageAccountName = <YourStorageAccountName>
$keyVaultName = <YourKeyVaultName>
$keyVaultSpAppId = "cfa8b339-82a2-471a-a3c9-0fc0be7a4093"
$storageAccountKey = "key1" #(key1 or key2 are allowed)
# Get your User Id
$userId = (Get-AzContext).Account.Id
# Get a reference to your Azure storage account
$storageAccount = Get-AzStorageAccount -ResourceGroupName $resourceGroupName -StorageAccountName $storageAccountName
Note
For Classic Storage Account use "primary" and "secondary" for $storageAccountKey
Use 'Get-AzResource -Name "ClassicStorageAccountName" -ResourceGroupName $resourceGroupName' instead of'Get-AzStorageAccount' for Classic Storage Account
Give Key Vault access to your storage account
Before Key Vault can access and manage your storage account keys, you must authorize its access your storage account. The Key Vault application requires permissions to list and regenerate keys for your storage account. These permissions are enabled through the Azure built-in role Storage Account Key Operator Service Role.
Assign this role to the Key Vault service principal, limiting scope to your storage account, using the Azure PowerShell New-AzRoleAssignment cmdlet.
# Assign Azure role "Storage Account Key Operator Service Role" to Key Vault, limiting the access scope to your storage account. For a classic storage account, use "Classic Storage Account Key Operator Service Role."
New-AzRoleAssignment -ApplicationId $keyVaultSpAppId -RoleDefinitionName 'Storage Account Key Operator Service Role' -Scope $storageAccount.Id
Upon successful role assignment, you should see output similar to the following example:
RoleAssignmentId : /subscriptions/03f0blll-ce69-483a-a092-d06ea46dfb8z/resourceGroups/rgContoso/providers/Microsoft.Storage/storageAccounts/sacontoso/providers/Microsoft.Authorization/roleAssignments/189cblll-12fb-406e-8699-4eef8b2b9ecz
Scope : /subscriptions/03f0blll-ce69-483a-a092-d06ea46dfb8z/resourceGroups/rgContoso/providers/Microsoft.Storage/storageAccounts/sacontoso
DisplayName : Azure Key Vault
SignInName :
RoleDefinitionName : storage account Key Operator Service Role
RoleDefinitionId : 81a9662b-bebf-436f-a333-f67b29880f12
ObjectId : 93c27d83-f79b-4cb2-8dd4-4aa716542e74
ObjectType : ServicePrincipal
CanDelegate : False
If Key Vault has already been added to the role on your storage account, you'll receive a "The role assignment already exists." error. You can also verify the role assignment, using the storage account "Access control (IAM)" page in the Azure portal.
Give your user account permission to managed storage accounts
Use the Azure PowerShell Set-AzKeyVaultAccessPolicy cmdlet to update the Key Vault access policy and grant storage account permissions to your user account.
# Give your user principal access to all storage account permissions, on your Key Vault instance
Set-AzKeyVaultAccessPolicy -VaultName $keyVaultName -UserPrincipalName $userId -PermissionsToStorage get, list, delete, set, update, regeneratekey, getsas, listsas, deletesas, setsas, recover, backup, restore, purge
Note that permissions for storage accounts aren't available on the storage account "Access policies" page in the Azure portal.
Add a managed storage account to your Key Vault instance
Use the Azure PowerShell Add-AzKeyVaultManagedStorageAccount cmdlet to create a managed storage account in your Key Vault instance. The -DisableAutoRegenerateKey switch specifies NOT to regenerate the storage account keys.
# Add your storage account to your Key Vault's managed storage accounts
Add-AzKeyVaultManagedStorageAccount -VaultName $keyVaultName -AccountName $storageAccountName -AccountResourceId $storageAccount.Id -ActiveKeyName $storageAccountKey -DisableAutoRegenerateKey
Upon successful addition of the storage account with no key regeneration, you should see output similar to the following example:
Id : https://kvcontoso.vault.azure.net:443/storage/sacontoso
Vault Name : kvcontoso
AccountName : sacontoso
Account Resource Id : /subscriptions/03f0blll-ce69-483a-a092-d06ea46dfb8z/resourceGroups/rgContoso/providers/Microsoft.Storage/storageAccounts/sacontoso
Active Key Name : key1
Auto Regenerate Key : False
Regeneration Period : 90.00:00:00
Enabled : True
Created : 11/19/2018 11:54:47 PM
Updated : 11/19/2018 11:54:47 PM
Tags :
Enable key regeneration
If you want Key Vault to regenerate your storage account keys periodically, you can use the Azure PowerShell Add-AzKeyVaultManagedStorageAccount cmdlet to set a regeneration period. In this example, we set a regeneration period of three days. When it is time to rotate, Key Vault regenerates the key that is not active, and then sets the newly created key as active. Only one of the keys are used to issue SAS tokens at any one time. This is the active key.
$regenPeriod = [System.Timespan]::FromDays(3)
Add-AzKeyVaultManagedStorageAccount -VaultName $keyVaultName -AccountName $storageAccountName -AccountResourceId $storageAccount.Id -ActiveKeyName $storageAccountKey -RegenerationPeriod $regenPeriod
Upon successful addition of the storage account with key regeneration, you should see output similar to the following example:
Id : https://kvcontoso.vault.azure.net:443/storage/sacontoso
Vault Name : kvcontoso
AccountName : sacontoso
Account Resource Id : /subscriptions/03f0blll-ce69-483a-a092-d06ea46dfb8z/resourceGroups/rgContoso/providers/Microsoft.Storage/storageAccounts/sacontoso
Active Key Name : key1
Auto Regenerate Key : True
Regeneration Period : 3.00:00:00
Enabled : True
Created : 11/19/2018 11:54:47 PM
Updated : 11/19/2018 11:54:47 PM
Tags :
Shared access signature tokens
You can also ask Key Vault to generate shared access signature tokens. A shared access signature provides delegated access to resources in your storage account. You can grant clients access to resources in your storage account without sharing your account keys. A shared access signature provides you with a secure way to share your storage resources without compromising your account keys.
The commands in this section complete the following actions:
- Set an account shared access signature definition.
- Create an account shared access signature token for Blob, File, Table, and Queue services. The token is created for resource types Service, Container, and Object. The token is created with all permissions, over https, and with the specified start and end dates.
- Set a Key Vault managed storage shared access signature definition in the vault. The definition has the template URI of the shared access signature token that was created. The definition has the shared access signature type
accountand is valid for N days. - Verify that the shared access signature was saved in your key vault as a secret.
Set variables
First, set the variables to be used by the PowerShell cmdlets in the following steps. Be sure to update the <YourStorageAccountName> and <YourKeyVaultName> placeholders.
We will also use the Azure PowerShell New-AzStorageContext cmdlets to get the context of your Azure storage account.
$storageAccountName = <YourStorageAccountName>
$keyVaultName = <YourKeyVaultName>
$storageContext = New-AzStorageContext -StorageAccountName $storageAccountName -Protocol Https -StorageAccountKey Key1 #(or "Primary" for Classic Storage Account)
Create a shared access signature token
Create a shared access signature definition using the Azure PowerShell New-AzStorageAccountSASToken cmdlets.
$start = [System.DateTime]::Now.AddDays(-1)
$end = [System.DateTime]::Now.AddMonths(1)
$sasToken = New-AzStorageAccountSasToken -Service blob,file,Table,Queue -ResourceType Service,Container,Object -Permission "racwdlup" -Protocol HttpsOnly -StartTime $start -ExpiryTime $end -Context $storageContext
The value of $sasToken will look similar to this.
?sv=2018-11-09&sig=5GWqHFkEOtM7W9alOgoXSCOJO%2B55qJr4J7tHQjCId9S%3D&spr=https&st=2019-09-18T18%3A25%3A00Z&se=2019-10-19T18%3A25%3A00Z&srt=sco&ss=bfqt&sp=racupwdl
Generate a shared access signature definition
Use the the Azure PowerShell Set-AzKeyVaultManagedStorageSasDefinition cmdlet to create a shared access signature definition. You can provide the name of your choice to the -Name parameter.
Set-AzKeyVaultManagedStorageSasDefinition -AccountName $storageAccountName -VaultName $keyVaultName -Name <YourSASDefinitionName> -TemplateUri $sasToken -SasType 'account' -ValidityPeriod ([System.Timespan]::FromDays(30))
Verify the shared access signature definition
You can verify that the shared access signature definition has been stored in your key vault using the Azure PowerShell Get-AzKeyVaultSecret cmdlet.
First, find the shared access signature definition in your key vault.
Get-AzKeyVaultSecret -VaultName <YourKeyVaultName>
The secret corresponding to your SAS definition will have these properties:
Vault Name : <YourKeyVaultName>
Name : <SecretName>
...
Content Type : application/vnd.ms-sastoken-storage
Tags :
You can now use the Get-AzKeyVaultSecret cmdlet with the VaultName and Name parameters to view the contents of that secret.
$secret = Get-AzKeyVaultSecret -VaultName <YourKeyVaultName> -Name <SecretName>
$ssPtr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secret.SecretValue)
try {
$secretValueText = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($ssPtr)
} finally {
[System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ssPtr)
}
Write-Output $secretValueText
The output of this command will show your SAS definition string.