List Key Vault Secrets via Azure CLI

This won’t be a long post, but useful nonetheless. It’s more like a script-dump as a post.

A while ago, someone assigned a task to me where I had to retrieve all the existing secrets in a specific Key Vault and list them. These secrets were to be placed in another Key Vault on a shared location. The exact reasons for this migration don’t matter for this post, but it has something to do with having a single Key Vault instance compared to having a Key Vault ‘per domain’, which I like a bit better.

It is possible to extract the secrets via the UI, but I didn’t feel much for doing this manually. Most of the time, when something is possible in the Azure Portal, it can also be done via the Azure CLI or Azure PowerShell.

I quickly navigated to the az keyvault documentation to see which commands are available.
The information I got from over there pointed me to the secret list and secret show commands.

Because I had to extract the secrets of multiple Key Vault instances in several subscriptions, a small function was in order. This is what I came up with.

Function GetKeyVaultEntries(
    az account set --subscription $subscriptionName
    $keyVaultEntries = (az keyvault secret list --vault-name $keyVaultName | ConvertFrom-Json) | Select-Object id, name
    Write-Host "Secret values of '$($subscriptionName)' for key vault '$($keyVaultName)'"
    Write-Host "| key | secret value |"
    Write-Host "| --- | ------------ |"
    foreach($entry in $keyVaultEntries)
        $secretValue = (az keyvault secret show --id $ | ConvertFrom-Json) | Select-Object name, value
        Write-Host "| " $ " | " $secretValue.value " |"
    Write-Host ""

This will list all of the secrets in your console if you invoke the function like so:

GetKeyVaultEntries "Subscription Dev" "my-d-env-kv"
GetKeyVaultEntries "Subscription Test" "my-t-env-kv"
GetKeyVaultEntries "Subscription Acc" "my-a-env-kv"

You need to have to access the Key Vault instances and have Get & List permissions. In normal scenarios, I don’t have these permissions, for obvious reasons, but I had elevated my permissions for this task.

So that’s it, a small script to extract all Key Vault secrets of a specific instance.
I hope it’ll help you and me in the future.


comments powered by Disqus