Skip to content

Instantly share code, notes, and snippets.

@justinyoo
Created April 30, 2020 02:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justinyoo/a6557ce58fb28e526744d85941404e75 to your computer and use it in GitHub Desktop.
Save justinyoo/a6557ce58fb28e526744d85941404e75 to your computer and use it in GitHub Desktop.
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