Ir al contenido
Docs Try Aspire
Docs Try

Set up Azure Key Vault in the AppHost

Esta página aún no está disponible en tu idioma.

Azure Key Vault logo

This article is the reference for the Aspire Azure Key Vault Hosting integration. It enumerates the AppHost APIs — with examples for both AppHost.cs and apphost.ts — that you use to model an Azure Key Vault resource in your AppHost project.

If you’re new to the Azure Key Vault integration, start with the Get started with Azure Key Vault integrations guide. For how consuming apps read the connection information this page exposes, see Connect to Azure Key Vault.

To start building an Aspire app that uses Azure Key Vault, install the 📦 Aspire.Hosting.Azure.KeyVault NuGet package:

Terminal
aspire add azure-key-vault

Learn more about aspire add in the command reference.

Or, choose a manual installation approach:

C# — AppHost.cs
#:package Aspire.Hosting.Azure.KeyVault@*
XML — AppHost.csproj
<PackageReference Include="Aspire.Hosting.Azure.KeyVault" Version="*" />

Once you’ve installed the hosting integration in your AppHost project, you can add an Azure Key Vault resource as shown in the following examples:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var keyVault = builder.AddAzureKeyVault("key-vault");
builder.AddProject<Projects.ExampleProject>("apiservice")
.WithReference(keyVault);
// After adding all resources, run the app...
builder.Build().Run();

The WithReference (or withReference) method configures a connection in the consuming project named after the referenced Key Vault resource.

Connect to an existing Azure Key Vault instance

Section titled “Connect to an existing Azure Key Vault instance”

You might have an existing Azure Key Vault instance that you want to connect to. Chain a call to AsExisting (or asExisting) to annotate that your resource already exists in Azure:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var existingKeyVaultName = builder.AddParameter("existingKeyVaultName");
var existingKeyVaultResourceGroup = builder.AddParameter("existingKeyVaultResourceGroup");
var keyVault = builder.AddAzureKeyVault("key-vault")
.AsExisting(existingKeyVaultName, existingKeyVaultResourceGroup);
builder.AddProject<Projects.ExampleProject>("apiservice")
.WithReference(keyVault);
// After adding all resources, run the app...
builder.Build().Run();

By default, AddAzureKeyVault configures a Key Vault Administrator built-in role for the consuming project. To assign a more restrictive role — such as KeyVaultSecretsUser — use WithRoleAssignments (or withRoleAssignments) on the consuming resource:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var keyVault = builder.AddAzureKeyVault("key-vault")
.WithRoleAssignments(builder.AddProject<Projects.ExampleProject>("apiservice"),
KeyVaultBuiltInRole.KeyVaultSecretsUser);
// After adding all resources, run the app...
builder.Build().Run();

To clear the default role assignments and configure only specific roles, call ClearDefaultRoleAssignments (or clearDefaultRoleAssignments) before adding the roles you need.

You can reference secrets stored in an Azure Key Vault directly from your AppHost and pass them to other resources. This lets you inject secret values into environment variables without storing them in plain text.

To add a secret to the Key Vault resource from the AppHost, call AddSecret (or addSecret) providing a name and a parameter:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var keyVault = builder.AddAzureKeyVault("key-vault");
var apiKey = builder.AddParameter("api-key", secret: true);
keyVault.AddSecret("my-api-key", apiKey);
// After adding all resources, run the app...
builder.Build().Run();

To reference an existing secret in the vault and pass it to a consuming resource, use GetSecret (or getSecret):

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var keyVault = builder.AddAzureKeyVault("key-vault");
var secretRef = keyVault.GetOutput("vaultUri");
builder.AddProject<Projects.ExampleProject>("apiservice")
.WithReference(keyVault)
.WithEnvironment("API_KEY", keyVault.GetSecret("my-api-key"));
// After adding all resources, run the app...
builder.Build().Run();

If you’re new to Bicep, it’s a domain-specific language for defining Azure resources. With Aspire, you don’t need to write Bicep by hand — the provisioning APIs generate Bicep for you. When you add an Azure Key Vault resource, the following Bicep is generated:

Generated Bicep — key-vault.bicep
@description('The location for the resource(s) to be deployed.')
param location string = resourceGroup().location
resource key_vault 'Microsoft.KeyVault/vaults@2024-11-01' = {
name: take('keyvault-${uniqueString(resourceGroup().id)}', 24)
location: location
properties: {
tenantId: tenant().tenantId
sku: {
family: 'A'
name: 'standard'
}
enableRbacAuthorization: true
}
tags: {
'aspire-resource-name': 'key-vault'
}
}
output vaultUri string = key_vault.properties.vaultUri
output name string = key_vault.name

The preceding Bicep is a module that provisions an Azure Key Vault resource. Additionally, role assignments are created for the Azure resource in a separate module:

Generated Bicep — key-vault-roles.bicep
@description('The location for the resource(s) to be deployed.')
param location string = resourceGroup().location
param key_vault_outputs_name string
param principalType string
param principalId string
resource key_vault 'Microsoft.KeyVault/vaults@2024-11-01' existing = {
name: key_vault_outputs_name
}
resource key_vault_KeyVaultSecretsUser 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
name: guid(key_vault.id, principalId, subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '4633458b-17de-408a-b874-0445c86b69e6'))
properties: {
principalId: principalId
roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '4633458b-17de-408a-b874-0445c86b69e6')
principalType: principalType
}
scope: key_vault
}

The generated Bicep is a starting point and is influenced by changes to the provisioning infrastructure. Customizations made directly to the Bicep file will be overwritten, so make changes through the provisioning APIs to ensure they are reflected in the generated files.

All Aspire Azure resources are subclasses of the AzureProvisioningResource type. This type enables the customization of the generated Bicep by providing a fluent API to configure the Azure resources using the ConfigureInfrastructure (or configureInfrastructure) API:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
builder.AddAzureKeyVault("key-vault")
.ConfigureInfrastructure(infra =>
{
var keyVault = infra.GetProvisionableResources()
.OfType<KeyVaultService>()
.Single();
keyVault.Properties.Sku = new()
{
Family = KeyVaultSkuFamily.A,
Name = KeyVaultSkuName.Premium,
};
keyVault.Properties.EnableRbacAuthorization = true;
keyVault.Tags.Add("ExampleKey", "Example value");
});
// After adding all resources, run the app...
builder.Build().Run();

There are many more configuration options available. For more information, see Azure.Provisioning customization.

For the full reference of Azure Key Vault connection properties — and how consuming apps in C#, TypeScript, Python, and Go read them — see Connect to Azure Key Vault.

The Azure Key Vault hosting integration doesn’t register a health check by default, because Azure Key Vault is a managed service. Health checks for the consuming app’s SecretClient are provided by the client integration.