Export Azure Key Vault Secrets using PowerShell
When working with Azure Key Vault, you may need to export stored secrets for backup or migration purposes. This post provides a PowerShell script to extract secrets from a Key Vault and save them in a JSON file.
Prerequisites
Before running the script, ensure you have:
- Azure CLI installed (Install Azure CLI)
- Logged in to Azure CLI using:
az login
- Set the correct Azure subscription (if you have multiple subscriptions):
az account set --subscription "your-subscription-id"
PowerShell Script
Save the following script as Export-Secrets.ps1:
# Define variables
$vaultName = "your-key-vault-name"
$outputFile = "keyvault-secrets.json"
# Initialize an empty array
$secretsArray = @()
# Get the list of secret names
$secretIds = az keyvault secret list --vault-name $vaultName --query "[].id" -o tsv
foreach ($secretId in $secretIds) {
# Extract the secret name from the secret ID
$secretName = [System.IO.Path]::GetFileName($secretId)
# Get the secret value
$secretValue = az keyvault secret show --id $secretId --query "value" -o tsv
# Create an object with the secret name and value
$secretObject = @{
key = $secretName
value = $secretValue
}
# Add the object to the array
$secretsArray += $secretObject
}
# Convert the array to JSON and save to a file
$secretsArray | ConvertTo-Json | Set-Content $outputFile
Write-Output "Secrets exported to $outputFile"
Running the Script
- Open PowerShell.
- Navigate to the folder where you saved the script.
- Run the script:
.\Export-Secrets.ps1
Example Output
Once executed, the script generates a JSON file (keyvault-secrets.json
) with the following structure:
[
{
"key": "secret1",
"value": "value1"
},
{
"key": "secret2",
"value": "value2"
}
]
This script exports secrets in plain text. Ensure you store the keyvault-secrets.json file securely.