skip to Main Content

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

2

Answers


  1. I think you can do this with az keyvault secret list command along with some PowerShell filtering.

    lemme share you a snippet below.

    # Set your variables
    $keyVaultName = "YourKeyVaultName"
    $resourceGroupName = "YourResourceGroupName"
    $prefix = "app"
    
    # Get the list of secret names from the key vault
    $secretListJson = az keyvault secret list --vault-name $keyVaultName --resource-group $resourceGroupName --query "[].name" --output json
    
    # Convert the JSON to a PowerShell array
    $secretList = $secretListJson | ConvertFrom-Json
    
    # Filter secrets based on the prefix
    $filteredSecrets = $secretList | Where-Object { $_ -like "$prefix*" }
    
    # Output the filtered list
    $filteredSecrets
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search