Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ public static IDistributedApplicationBuilder AddAzureProvisioning(this IDistribu
.ValidateDataAnnotations()
.ValidateOnStart();

builder.Services.AddSingleton<TokenCredentialHolder>();

builder.AddAzureProvisioner<AzureBicepResource, BicepProvisioner>();

return builder;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
using Aspire.Hosting.Lifecycle;
using Azure;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.Resources;
using Microsoft.Extensions.Configuration;
Expand All @@ -35,7 +34,8 @@ internal sealed class AzureProvisioner(
IServiceProvider serviceProvider,
ResourceNotificationService notificationService,
ResourceLoggerService loggerService,
IDistributedApplicationEventing eventing
IDistributedApplicationEventing eventing,
TokenCredentialHolder tokenCredentialHolder
) : IDistributedApplicationLifecycleHook
{
internal const string AspireResourceNameTag = "aspire-resource-name";
Expand Down Expand Up @@ -219,7 +219,7 @@ private async Task ProvisionAzureResources(
var userSecretsLazy = new Lazy<Task<JsonObject>>(() => GetUserSecretsAsync(userSecretsPath, cancellationToken));

// Make resources wait on the same provisioning context
var provisioningContextLazy = new Lazy<Task<ProvisioningContext>>(() => GetProvisioningContextAsync(userSecretsLazy, cancellationToken));
var provisioningContextLazy = new Lazy<Task<ProvisioningContext>>(() => GetProvisioningContextAsync(tokenCredentialHolder.Credential, userSecretsLazy, cancellationToken));

var tasks = new List<Task>();

Expand Down Expand Up @@ -366,39 +366,8 @@ async Task PublishConnectionStringAvailableEventAsync()
}
}

private async Task<ProvisioningContext> GetProvisioningContextAsync(Lazy<Task<JsonObject>> userSecretsLazy, CancellationToken cancellationToken)
private async Task<ProvisioningContext> GetProvisioningContextAsync(TokenCredential credential, Lazy<Task<JsonObject>> userSecretsLazy, CancellationToken cancellationToken)
{
// Optionally configured in AppHost appSettings under "Azure" : { "CredentialSource": "AzureCli" }
var credentialSetting = _options.CredentialSource;

TokenCredential credential = credentialSetting switch
{
"AzureCli" => new AzureCliCredential(),
"AzurePowerShell" => new AzurePowerShellCredential(),
"VisualStudio" => new VisualStudioCredential(),
"VisualStudioCode" => new VisualStudioCodeCredential(),
"AzureDeveloperCli" => new AzureDeveloperCliCredential(),
"InteractiveBrowser" => new InteractiveBrowserCredential(),
_ => new DefaultAzureCredential(new DefaultAzureCredentialOptions()
{
ExcludeManagedIdentityCredential = true,
ExcludeWorkloadIdentityCredential = true,
ExcludeAzurePowerShellCredential = true,
CredentialProcessTimeout = TimeSpan.FromSeconds(15)
})
};

if (credential.GetType() == typeof(DefaultAzureCredential))
{
logger.LogInformation(
"Using DefaultAzureCredential for provisioning. This may not work in all environments. " +
"See https://aka.ms/azsdk/net/identity/credential-chains#defaultazurecredential-overview for more information.");
}
else
{
logger.LogInformation("Using {credentialType} for provisioning.", credential.GetType().Name);
}

var subscriptionId = _options.SubscriptionId ?? throw new MissingConfigurationException("An Azure subscription id is required. Set the Azure:SubscriptionId configuration value.");

var armClient = new ArmClient(credential, subscriptionId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ namespace Aspire.Hosting.Azure.Provisioning;

internal sealed class BicepProvisioner(
ResourceNotificationService notificationService,
ResourceLoggerService loggerService) : AzureResourceProvisioner<AzureBicepResource>
ResourceLoggerService loggerService,
TokenCredentialHolder tokenCredentialHolder) : AzureResourceProvisioner<AzureBicepResource>
{
public override bool ShouldProvision(IConfiguration configuration, AzureBicepResource resource)
=> !resource.IsContainer();
Expand Down Expand Up @@ -67,6 +68,12 @@ public override async Task<bool> ConfigureResourceAsync(IConfiguration configura
}
}

if (resource is IAzureKeyVaultResource kvr)
{
ConfigureSecretResolver(kvr);
}

// Populate secret outputs from key vault (if any)
foreach (var item in section.GetSection("SecretOutputs").GetChildren())
{
resource.SecretOutputs[item.Key] = item.Value;
Expand Down Expand Up @@ -280,15 +287,7 @@ await notificationService.PublishUpdateAsync(resource, state =>
// Populate secret outputs from key vault (if any)
if (resource is IAzureKeyVaultResource kvr)
{
var vaultUri = resource.Outputs[kvr.VaultUriOutputReference.Name] as string ?? throw new InvalidOperationException($"{kvr.VaultUriOutputReference.Name} not found in outputs.");

// Set the client for resolving secrets at runtime
var client = new SecretClient(new(vaultUri), context.Credential);
kvr.SecretResolver = async (secretRef, ct) =>
{
var secret = await client.GetSecretAsync(secretRef.SecretName, cancellationToken: ct).ConfigureAwait(false);
return secret.Value.Value;
};
ConfigureSecretResolver(kvr);
}

await notificationService.PublishUpdateAsync(resource, state =>
Expand All @@ -308,6 +307,21 @@ await notificationService.PublishUpdateAsync(resource, state =>
.ConfigureAwait(false);
}

private void ConfigureSecretResolver(IAzureKeyVaultResource kvr)
{
var resource = (AzureBicepResource)kvr;

var vaultUri = resource.Outputs[kvr.VaultUriOutputReference.Name] as string ?? throw new InvalidOperationException($"{kvr.VaultUriOutputReference.Name} not found in outputs.");

// Set the client for resolving secrets at runtime
var client = new SecretClient(new(vaultUri), tokenCredentialHolder.Credential);
kvr.SecretResolver = async (secretRef, ct) =>
{
var secret = await client.GetSecretAsync(secretRef.SecretName, cancellationToken: ct).ConfigureAwait(false);
return secret.Value.Value;
};
}

private static void PopulateWellKnownParameters(AzureBicepResource resource, ProvisioningContext context)
{
if (resource.Parameters.TryGetValue(AzureBicepResource.KnownParameters.PrincipalId, out var principalId) && principalId is null)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Azure.Core;
using Azure.Identity;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace Aspire.Hosting.Azure.Provisioning;

internal class TokenCredentialHolder
{
public TokenCredentialHolder(ILogger<TokenCredentialHolder> logger, IOptions<AzureProvisionerOptions> options)
{
// Optionally configured in AppHost appSettings under "Azure" : { "CredentialSource": "AzureCli" }
var credentialSetting = options.Value.CredentialSource;

TokenCredential credential = credentialSetting switch
{
"AzureCli" => new AzureCliCredential(),
"AzurePowerShell" => new AzurePowerShellCredential(),
"VisualStudio" => new VisualStudioCredential(),
"VisualStudioCode" => new VisualStudioCodeCredential(),
"AzureDeveloperCli" => new AzureDeveloperCliCredential(),
"InteractiveBrowser" => new InteractiveBrowserCredential(),
_ => new DefaultAzureCredential(new DefaultAzureCredentialOptions()
{
ExcludeManagedIdentityCredential = true,
ExcludeWorkloadIdentityCredential = true,
ExcludeAzurePowerShellCredential = true,
CredentialProcessTimeout = TimeSpan.FromSeconds(15)
})
};

if (credential.GetType() == typeof(DefaultAzureCredential))
{
logger.LogInformation(
"Using DefaultAzureCredential for provisioning. This may not work in all environments. " +
"See https://aka.ms/azsdk/net/identity/credential-chains#defaultazurecredential-overview for more information.");
}
else
{
logger.LogInformation("Using {credentialType} for provisioning.", credential.GetType().Name);
}

Credential = credential;
}

public TokenCredential Credential { get; }
}