Search code examples
azureazure-keyvaultazure-sdk

Azure KeyVault iterate over all secrets in a vault


For the sake of simplicity let assume I want to build a dictionary from all the secrets in specific vault with the Secret Name and the Secret Value, using Azure REST API.

The problem I'm facing is that the Get Secrets API call returns SecretListResult which contains a list of SecretItem. the SecretItem has ID element, but not a Name, nor the Value. The GetSecret API needs the secret name and not the secret ID, and so far I cant find a way the translate an ID to name.

any suggestions would be highly appreciated

Thank you.


Solution

  • // Get list of secrets

    GET https://alice.vault.azure.net/secrets?api-version=2015-06-01
    
    Response Body:
    {
      "value": [
        {
          "contentType": "text",
          "id": "https://alice.vault.azure.net/secrets/secret1",
          "attributes": {
            "enabled": true,
            "created": 1496749576,
            "updated": 1496749576
          }
        },
        {
          "contentType": "text",
          "id": "https://alice.vault.azure.net/secrets/secret2",
          "attributes": {
            "enabled": true,
            "created": 1496749590,
            "updated": 1496749590
          }
        }
      ],
      "nextLink": null
    }
    

    // Get secret properties and value

    Parse id, look for last occurrence of / to get secret name. One call per item.

    GET https://alice.vault.azure.net/secrets/secret1/?api-version=2015-06-01
    
    Response Body:
    {
      "value": "5up3r1ee7s3cr3t",
      "contentType": "text",
      "id": "https://alice.vault.azure.net/secrets/secret1/6ac15a48877148e094276504d73e95a1",
      "attributes": {
        "enabled": true,
        "created": 1496749576,
        "updated": 1496749576
      }
    }
    
    
    GET https://alice.vault.azure.net/secrets/secret2/?api-version=2015-06-01
    
    Response Body:
    {
      "value": "@n0th3r5up3r1ee7s3cr3t",
      "contentType": "text",
      "id": "https://alice.vault.azure.net/secrets/secret2/2b34de363d6445ba83bb23bafaea6658",
      "attributes": {
        "enabled": true,
        "created": 1496749590,
        "updated": 1496749590
      }
    }
    

    Source: I just looked at what Azure PowerShell calls on the wire with -Debug, e.g.:

    Get-AzureKeyVaultSecret -VaultName Alice -Debug
    Get-AzureKeyVaultSecret -VaultName Alice -Name secret1 -Debug