Search code examples
azurepowershellazure-cli

Use az cli to return secret names from keyvault that start with a known prefix in a list


I have a script that runs az cli commands (in powershell). For example, i'm using a commands like this in the script:

az keyvault secret list ...

I pass parameters into the script, one of which is the keyvault name. For a given keyvault, i would like to return all the secrets in the keyvault that start with 'app'. So for example, if the following secrets are in a keyvault:

app1name app2name app1password dbpassword1 app2password dbpassword2

i want to script to return a list that is:

app1name app2name app1password app2password


Solution

  • To return secret names from KeyVault that start with a known prefix in a list:

    In my environment, I have KeyVault and created secrets with names like app1name, app2name, app1password, dbpassword1, app2password, and dbpassword2. as you mentioned.

    Portal: enter image description here

    To get the secret names with the prefix 'app' and output as app1name, app2name, app1password, app2password, you can use the command below.

    Command:

    $vaultname="venkat0123"
    az keyvault secret list --vault-name $vaultname --query "[?starts_with(id, 'https://$vaultname.vault.azure.net/secrets/app')].name" --output tsv
    

    Output:

    PS /home/xxx> $vaultname="venkat0123"
    PS /home/xxxx> az keyvault secret list --vault-name $vaultname --query "[?starts_with(id, 'https://$vaultname.vault.azure.net/secrets/app')].name" --output tsv
    app1name
    app1password
    app2name
    app2password
    

    enter image description here

    Reference: az keyvault secret | Microsoft Learn