Forum Discussion
Azure Key rotation policy using Azure app function in Azure Portal
To rotate a key in Azure Key Vault using an Azure Function App, you can use the following PowerShell script:
```powershell
# Install AzureRM and Az modules
Install-Module -Name AzureRM -Force -AllowClobber
Install-Module -Name Az -AllowClobber -Force
# Connect to Azure
Connect-AzAccount -ServicePrincipal -TenantId "<TenantId>" -Credential $psCredential
# Set Key Vault details
$kvName = "<KeyVaultName>"
$keyName = "<KeyName>"
# Rotate the key by creating a new key in Key Vault
$rotatedKey = Add-AzKeyVaultKey -VaultName $kvName -Name $keyName -Destination "<KeyOperations>" -KeySize <KeySize>
# Get the latest version of the key
$targetKey = Get-AzKeyVaultKey -VaultName $kvName -Name $keyName | Sort-Object -Property Created -Descending | Select-Object -First 1
# Delete the old key
Remove-AzKeyVaultKey -VaultName $kvName -Name $targetKey.Name -InRemovedState
# Output the details of the rotated key
$rotatedKey
```
Replace the placeholders `<TenantId>`, `<KeyVaultName>`, `<KeyName>`, `<KeyOperations>`, and `<KeySize>` with your actual values.
You can deploy this script as an Azure Function App by following these steps:
1. In the Azure portal, create a new Function App.
2. Choose the runtime stack as PowerShell.
3. In the Function App settings, go to Platform Features -> Configuration -> Application Settings and set your Azure Key Vault credentials and other necessary settings as environment variables.
4. Create a new Function in the Function App and paste the script into the function code.
5. Save and run the function to rotate the key in Azure Key Vault.
Ensure that the Function App has the necessary permissions to access and manage the Azure Key Vault. You can grant the required permissions by creating a service principal and assigning the appropriate access policies in the Azure Key Vault and granting the necessary permissions to the service principal.