Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
3 Ways Referencing Azure Key Vault from Azure Functions
@Microsoft.KeyVault(SecretUri=https://<key-vault-name>.vault.azure.net/secrets/<secret-name>/<secret-version>)
@Microsoft.KeyVault(VaultName=<key-vault-name>; SecretName=<secret-name>; SecretVersion=<secret-version>)
@Microsoft.KeyVault(SecretUri=https://<key-vault-name>.vault.azure.net/secrets/<secret-name>/)
public class AppSettingsHandler
{
private static Regex regexSecretUri = new Regex(@"\@Microsoft\.KeyVault\(SecretUri\=(.*)\)", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
private static Regex regexVaultName = new Regex(@"\@Microsoft\.KeyVault\(VaultName\=(.*);\s*SecretName\=(.*);\s*SecretVersion\=(.*)\)", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
...
}
public class AppSettingsHandler
{
...
public async Task<string> GetValueAsync(string key)
{
var reference = Environment.GetEnvironmentVariable(key);
if (!this.IsKeyVaultReference(reference))
{
return reference;
}
...
}
private bool IsKeyVaultReference(string value)
{
return value.StartsWith("@Microsoft.KeyVault(");
}
}
public class AppSettingsHandler
{
...
public async Task<string> GetValueAsync(string key)
{
...
var bundle = default(SecretBundle);
var match = regexSecretUri.Match(reference);
if (match.Success)
{
var uri = match.Groups[1].Value;
bundle = await this._kv.GetSecretAsync(uri).ConfigureAwait(false);
return bundle.Value;
}
...
}
}
public class AppSettingsHandler
{
...
public async Task<string> GetValueAsync(string key)
{
...
match = regexVaultName.Match(reference);
if (match.Success)
{
var vaultName = match.Groups[1].Value;
var secretName = match.Groups[2].Value;
var secretVersion = match.Groups[3].Value;
bundle = await this._kv.GetSecretAsync($"https://{vaultName}.vault.azure.net", secretName, secretVersion).ConfigureAwait(false);
return bundle.Value;
}
...
}
}
public class AppSettingsHandler
{
...
public async Task<string> GetValueAsync(string key)
{
...
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.