I would like to retrieve Azure Key Vault referenced secrets in App Configuration service. In dotnet it is a piece of cake, you simply add options.ConfigureKeyVault and can retrieve secret like this:
var credential = new DefaultAzureCredential();
var config = new ConfigurationBuilder().AddAzureAppConfiguration(options => {
options.Connect(
new Uri("https://app-cf.azconfig.io"), credential
).Select("*", "label");
options.ConfigureKeyVault(kv => {
kv.SetCredential(credential);
});
}).Build();
var test = config.GetValue<string>("secret_name");
But in Python I haven't found any method to add KeyVault handling in AzureAppConfigurationClient, and when you try to retrieve Key Vault referenced secret you simply get string:
'{"uri":"https://kv-name.vault.azure.net/secrets/SecretName"}'
.
I've "solved" this writing function:
import json
from pathlib import Path
from azure.appconfiguration import AzureAppConfigurationClient
from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import SecretClient
def get_appcf_label(base_url: str, label: str) -> dict:
"""Get app configurations for specified label."""
credential = DefaultAzureCredential()
client = AzureAppConfigurationClient(base_url, credential)
filtered_listed = client.list_configuration_settings(
key_filter="*", label_filter=label
)
config = dict()
for item in filtered_listed:
if (
item.content_type
== "application/vnd.microsoft.appconfig.keyvaultref+json;charset=utf-8"
):
url_parts = Path(json.loads(item.value)["uri"]).parts
vault_url = "//".join(url_parts[:2])
kv_secret = url_parts[-1]
kv_client = SecretClient(vault_url, credential)
secret_val = kv_client.get_secret(kv_secret).value
config.update({item.key: secret_val})
else:
config.update({item.key: item.value})
return config
I don't like this solution, especially string parsing, even though it's working, but I cannot figure out a better way to do it. Do you have any ideas how to do it in a smarter/cleaner way?