Python Azure sdk: How to retrieve secrets from keyvault?

90abyss picture 90abyss · Aug 30, 2017 · Viewed 7.8k times · Source

I need to retrieve secrets from keyvault. This is my code so far:

from azure.mgmt.keyvault import KeyVaultManagementClient
from azure.common.credentials import ServicePrincipalCredentials


subscription_id = 'x'
# See above for details on creating different types of AAD credentials
credentials = ServicePrincipalCredentials(
    client_id = 'x',
    secret = 'x',
    tenant = 'x'
)

kv_client = KeyVaultManagementClient(credentials, subscription_id)

for vault in kv_client.vaults.list():
    print(vault)

But I am getting this error:

msrestazure.azure_exceptions.CloudError: Azure Error: AuthorizationFailed Message: The client 'x' with object id 'x' does not have authorization to perform action 'Microsoft.Resources/subscriptions/resources/read' over scope '/subscriptions/x'.

Now I am able to access the same keyvault with same credentials using C# code/ POwershell so there is definitely nothing wrong with authorization. Not sure why it isnt working using SDK. Please help.

Answer

Den Delimarsky picture Den Delimarsky · Apr 7, 2018

If you are looking to access via a ServicePrincipalCredentials instance, you can just use:

from azure.keyvault import KeyVaultClient, KeyVaultAuthentication
from azure.common.credentials import ServicePrincipalCredentials

credentials = None

def auth_callback(server, resource, scope):
    credentials = ServicePrincipalCredentials(
        client_id = '',
        secret = '',
        tenant = '',
        resource = "https://vault.azure.net"
    )
    token = credentials.token
    return token['token_type'], token['access_token']

client = KeyVaultClient(KeyVaultAuthentication(auth_callback))

secret_bundle = client.get_secret("https://vault_url", "secret_id", "")

print(secret_bundle.value)

This assumes that you don't want to pass a version. If you do, you can substitute the last parameter for it.