Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Azure Key Vault and Active Directory to Retrieve Secrets

For a Python code base I would like to have developers accessing application secrets using Azure Key Vault, with the idea that when we deploy, the application also should be able to connect. Hence, I'm thinking Active Directory.

However, I can not find any examples on the interweb that show this with the Python SDK. Initially, I would think to retrieve the CLI user:

from azure.common.credentials import get_azure_cli_credentials

credentials, subscription_id, tenant_id = get_azure_cli_credentials(with_tenant=True)

and then use this retrieved set of credentials to access the key vault:

from azure.keyvault import KeyVaultClient

vault_url = "https://########.vault.azure.net/"
secret_name = "########"
secret_version = "########"

client = KeyVaultClient(credentials)
secret = client.get_secret(vault_url, secret_name, secret_version)

print(secret)

However, I retrieve an error that:

azure.keyvault.v7_0.models.key_vault_error_py3.KeyVaultErrorException: Operation returned an invalid status code 'Unauthorized'

I can confirm that credentials, subscription_id and tenant_id are correct, and that using the CLI, I can succesfully retrieve the secret content. So it must be some Python SDK-specific thing.

Any ideas?

like image 679
casparjespersen Avatar asked Dec 06 '25 16:12

casparjespersen


1 Answers

It looks like this is a bug in the Python SDK.

https://github.com/Azure/azure-sdk-for-python/issues/5096

You can use your own AD username and password with the UserPassCredentials class. It's not the logged in user, but's it's probably as close as you'll get for now.

EG:

from azure.common.credentials import UserPassCredentials
credentials = UserPassCredentials('username','password')

client = KeyVaultClient(credentials)
secret = client.get_secret(vault_url, secret_name, secret_version)

print(secret)
like image 129
Euan Avatar answered Dec 08 '25 04:12

Euan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!