Search code examples
c#c#-9.0dotnet-aspire

Aspire KeyVault configuration provider and AddAzureKeyVaultSecrets


There should be a way of using the configuration providers, Microsoft.Extensions.Configuration, to set up the KeyVault URI but the documentation is vague and has no examples. The method alluded to, AddAzureKeyVaultSecrets, has no parameterless overloads so the documentation doesn't make sense to me when it says:

If you have set up your configurations in the Aspire:Azure:Security:KeyVault section of your appsettings.json file you can just call the method AddAzureKeyVaultSecrets without passing any parameters.

Is this claim correct and I'm misunderstanding what needs doing?

This is dotnet Aspire 9.0.


Solution

  • Here is the source code of the AddAzureKeyVaultSecrets extension method:

    /// <summary>
    /// Registers <see cref="SecretClient"/> as a singleton for given <paramref name="name"/> in the services provided by the <paramref name="builder"/>.
    /// Enables retries, corresponding health check, logging and telemetry.
    /// </summary>
    /// <param name="builder">The <see cref="IHostApplicationBuilder" /> to read config from and add services to.</param>
    /// <param name="name">The name of the component, which is used as the <see cref="ServiceDescriptor.ServiceKey"/> of the service and also to retrieve the connection information from the ConnectionStrings configuration section.</param>
    /// <param name="configureSettings">An optional method that can be used for customizing the <see cref="AzureSecurityKeyVaultSettings"/>. It's invoked after the settings are read from the configuration.</param>
    /// <param name="configureClientBuilder">An optional method that can be used for customizing the <see cref="IAzureClientBuilder{TClient, TOptions}"/>.</param>
    /// <remarks>Reads the configuration from "Aspire:Azure:Security:KeyVault:{name}" section.</remarks>
    /// <exception cref="InvalidOperationException">Thrown when mandatory <see cref="AzureSecurityKeyVaultSettings.VaultUri"/> is not provided.</exception>
    public static void AddKeyedAzureKeyVaultClient(
        this IHostApplicationBuilder builder,
        string name,
        Action<AzureSecurityKeyVaultSettings>? configureSettings = null,
        Action<IAzureClientBuilder<SecretClient, SecretClientOptions>>? configureClientBuilder = null)
    {
        ArgumentException.ThrowIfNullOrEmpty(name);
    
        new KeyVaultComponent().AddClient(builder, DefaultConfigSectionName, configureSettings, configureClientBuilder, connectionName: name, serviceKey: name);
    }
    

    The name parameter is always required as it's needed to identify between both AppHost and other services but the others are optional, so basically you can call it as this:

    builder.AddAzureKeyVaultSecrets("secrets");
    

    It will read the setting in the path Aspire:Azure:Security:KeyVault:{propName} from your configuration provider (first one is appsettings.json)