// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Aspire.Deployment.EndToEnd.Tests.Helpers;
using Hex1b.Automation;
using Xunit;
namespace Aspire.Deployment.EndToEnd.Tests;
/// <summary>
/// End-to-end tests for deploying Azure Storage resources via Aspire.
/// Tests the Aspire.Hosting.Azure.Storage integration package.
/// </summary>
public sealed class AzureStorageDeploymentTests(ITestOutputHelper output)
{
// Timeout set to 30 minutes for Azure resource provisioning.
private static readonly TimeSpan s_testTimeout = TimeSpan.FromMinutes(30);
[Fact]
public async Task DeployAzureStorageResource()
{
using var cts = new CancellationTokenSource(s_testTimeout);
using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(
cts.Token, TestContext.Current.CancellationToken);
var cancellationToken = linkedCts.Token;
await DeployAzureStorageResourceCore(cancellationToken);
}
[Fact]
public async Task DeployStarterWithSharedAzureStorageReferences()
{
using var cts = new CancellationTokenSource(s_testTimeout);
using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(
cts.Token, TestContext.Current.CancellationToken);
var cancellationToken = linkedCts.Token;
await DeployStarterWithSharedAzureStorageReferencesCore(cancellationToken);
}
private async Task DeployAzureStorageResourceCore(CancellationToken cancellationToken)
{
// Validate prerequisites
var subscriptionId = AzureAuthenticationHelpers.TryGetSubscriptionId();
if (string.IsNullOrEmpty(subscriptionId))
{
Assert.Skip("Azure subscription not configured. Set ASPIRE_DEPLOYMENT_TEST_SUBSCRIPTION.");
}
if (!AzureAuthenticationHelpers.IsAzureAuthAvailable())
{
if (DeploymentE2ETestHelpers.IsRunningInCI)
{
Assert.Fail("Azure authentication not available in CI. Check OIDC configuration.");
}
else
{
Assert.Skip("Azure authentication not available. Run 'az login' to authenticate.");
}
}
var workspace = TemporaryWorkspace.Create(output);
var startTime = DateTime.UtcNow;
var resourceGroupName = DeploymentE2ETestHelpers.GenerateResourceGroupName("storage");
output.WriteLine($"Test: {nameof(DeployAzureStorageResource)}");
output.WriteLine($"Resource Group: {resourceGroupName}");
output.WriteLine($"Subscription: {subscriptionId[..8]}...");
output.WriteLine($"Workspace: {workspace.WorkspaceRoot.FullName}");
try
{
using var terminal = DeploymentE2ETestHelpers.CreateTestTerminal();
var pendingRun = terminal.RunAsync(cancellationToken);
var counter = new SequenceCounter();
var auto = new Hex1bTerminalAutomator(terminal, defaultTimeout: TimeSpan.FromSeconds(500));
// Step 1: Prepare environment
output.WriteLine("Step 1: Preparing environment...");
await auto.PrepareEnvironmentAsync(workspace, counter);
// Step 2: Set up CLI environment
await auto.InstallCurrentBuildAspireCliAsync(counter, output);
// Step 3: Create single-file AppHost using aspire init
output.WriteLine("Step 3: Creating single-file AppHost with aspire init...");
await auto.AspireInitAsync(counter);
// Step 4a: Add Aspire.Hosting.Azure.ContainerApps package (for managed identity support)
// This command triggers TWO prompts in sequence:
// 1. Integration selection prompt (because "ContainerApps" matches multiple Azure packages)
// 2. Version selection prompt (in CI, to select package version)
output.WriteLine("Step 4a: Adding Azure Container Apps hosting package...");
await auto.TypeAsync("aspire add Aspire.Hosting.Azure.ContainerApps");
await auto.EnterAsync();
await auto.WaitUntilTextAsync("Select an integration to add:", timeout: TimeSpan.FromSeconds(60));
await auto.EnterAsync();
await auto.WaitForAspireAddCompletionAsync(counter);
// Step 4b: Add Aspire.Hosting.Azure.Storage package
// This command may only show version selection prompt (unique match)
output.WriteLine("Step 4b: Adding Azure Storage hosting package...");
await auto.TypeAsync("aspire add Aspire.Hosting.Azure.Storage");
await auto.EnterAsync();
// aspire add may show a version selection prompt
await auto.WaitForAspireAddCompletionAsync(counter);
// Step 5: Modify apphost.cs to add Azure Storage resource
{
var appHostFilePath = Path.Combine(workspace.WorkspaceRoot.FullName, "apphost.cs");
output.WriteLine($"Looking for apphost.cs at: {appHostFilePath}");
var content = File.ReadAllText(appHostFilePath);
// Insert Azure Storage with a container app environment (required for role assignments)
var buildRunPattern = "builder.Build().Run();";
var replacement = """
// Add Azure Container App Environment for managed identity support
_ = builder.AddAzureContainerAppEnvironment("env");
// Add Azure Storage resource for deployment testing
builder.AddAzureStorage("storage");
builder.Build().Run();
""";
content = content.Replace(buildRunPattern, replacement);
File.WriteAllText(appHostFilePath, content);
output.WriteLine($"Modified apphost.cs to add Azure Storage resource");
output.WriteLine($"New content:\n{content}");
}
// Step 6: Set environment variables for deployment
await auto.TypeAsync($"unset ASPIRE_PLAYGROUND && export AZURE__LOCATION=westus3 && export AZURE__RESOURCEGROUP={resourceGroupName}");
await auto.EnterAsync();
await auto.WaitForSuccessPromptAsync(counter);
// Step 7: Deploy to Azure using aspire deploy
output.WriteLine("Step 7: Starting Azure deployment...");
await auto.TypeAsync("aspire deploy --clear-cache");
await auto.EnterAsync();
// Wait for pipeline to complete successfully
await auto.WaitForPipelineSuccessAsync(timeout: TimeSpan.FromMinutes(20));
await auto.WaitForSuccessPromptAsync(counter, TimeSpan.FromMinutes(2));
// Step 8: Verify the Azure Storage account was created
output.WriteLine("Step 8: Verifying Azure Storage account...");
await DotnetProjectDeploymentHelpers.RunScriptAsync(auto, counter, $$"""
set -euo pipefail
az storage account list -g {{resourceGroupName}} --subscription {{subscriptionId}} -o json |
jq -e 'length == 1'
""", TimeSpan.FromSeconds(30));
// Step 9: Clean up Azure resources using aspire destroy
output.WriteLine("Step 9: Destroying Azure deployment...");
await auto.AspireDestroyAsync(counter);
// Step 10: Exit terminal
await auto.TypeAsync("exit");
await auto.EnterAsync();
await pendingRun;
var duration = DateTime.UtcNow - startTime;
output.WriteLine($"Deployment completed in {duration}");
// Report success
DeploymentReporter.ReportDeploymentSuccess(
nameof(DeployAzureStorageResource),
resourceGroupName,
new Dictionary<string, string>(),
duration);
}
catch (Exception ex)
{
output.WriteLine($"Test failed: {ex.Message}");
DeploymentReporter.ReportDeploymentFailure(
nameof(DeployAzureStorageResource),
resourceGroupName,
ex.Message);
throw;
}
finally
{
// Always attempt to clean up the resource group
output.WriteLine($"Cleaning up resource group: {resourceGroupName}");
await CleanupResourceGroupAsync(resourceGroupName);
}
}
private async Task DeployStarterWithSharedAzureStorageReferencesCore(CancellationToken cancellationToken)
{
var subscriptionId = AzureAuthenticationHelpers.TryGetSubscriptionId();
if (string.IsNullOrEmpty(subscriptionId))
{
Assert.Skip("Azure subscription not configured. Set ASPIRE_DEPLOYMENT_TEST_SUBSCRIPTION.");
}
if (!AzureAuthenticationHelpers.IsAzureAuthAvailable())
{
if (DeploymentE2ETestHelpers.IsRunningInCI)
{
Assert.Fail("Azure authentication not available in CI. Check OIDC configuration.");
}
else
{
Assert.Skip("Azure authentication not available. Run 'az login' to authenticate.");
}
}
var workspace = TemporaryWorkspace.Create(output);
var startTime = DateTime.UtcNow;
var resourceGroupName = DeploymentE2ETestHelpers.GenerateResourceGroupName("storage-shared");
var projectName = "StorageShared";
output.WriteLine($"Test: {nameof(DeployStarterWithSharedAzureStorageReferences)}");
output.WriteLine($"Project Name: {projectName}");
output.WriteLine($"Resource Group: {resourceGroupName}");
output.WriteLine($"Subscription: {subscriptionId[..8]}...");
output.WriteLine($"Workspace: {workspace.WorkspaceRoot.FullName}");
try
{
using var terminal = DeploymentE2ETestHelpers.CreateTestTerminal();
var pendingRun = terminal.RunAsync(cancellationToken);
var counter = new SequenceCounter();
var auto = new Hex1bTerminalAutomator(terminal, defaultTimeout: TimeSpan.FromSeconds(500));
output.WriteLine("Step 1: Preparing environment...");
await auto.PrepareEnvironmentAsync(workspace, counter);
await auto.InstallCurrentBuildAspireCliAsync(counter, output);
output.WriteLine("Step 3: Creating starter project...");
await auto.AspireNewAsync(projectName, counter, useRedisCache: false);
output.WriteLine("Step 4: Navigating to project directory...");
await auto.TypeAsync($"cd {projectName}");
await auto.EnterAsync();
await auto.WaitForSuccessPromptAsync(counter);
output.WriteLine("Step 5a: Adding Azure Container Apps hosting package...");
await auto.TypeAsync("aspire add Aspire.Hosting.Azure.AppContainers");
await auto.EnterAsync();
await auto.WaitForAspireAddCompletionAsync(counter);
output.WriteLine("Step 5b: Adding Azure Storage hosting package...");
await auto.TypeAsync("aspire add Aspire.Hosting.Azure.Storage");
await auto.EnterAsync();
await auto.WaitForAspireAddCompletionAsync(counter);
var projectDir = Path.Combine(workspace.WorkspaceRoot.FullName, projectName);
var appHostDir = Path.Combine(projectDir, $"{projectName}.AppHost");
var appHostFilePath = Path.Combine(appHostDir, "AppHost.cs");
output.WriteLine($"Looking for AppHost.cs at: {appHostFilePath}");
var content = File.ReadAllText(appHostFilePath);
content = DotnetProjectDeploymentHelpers.ReplaceExactlyOnce(content,
"var builder = DistributedApplication.CreateBuilder(args);",
"""
var builder = DistributedApplication.CreateBuilder(args);
var storage = builder.AddAzureStorage("storage");
var blobs = storage.AddBlobs("blobs");
""");
var apiServiceDeclaration = $"var apiService = builder.AddDotnetProject(\"apiservice\", \"../{projectName}.ApiService/{projectName}.ApiService.csproj\")";
content = DotnetProjectDeploymentHelpers.ReplaceExactlyOnce(content,
apiServiceDeclaration,
$"{apiServiceDeclaration}\n .WithReference(blobs)");
content = DotnetProjectDeploymentHelpers.ReplaceExactlyOnce(content,
".WithReference(apiService)",
"""
.WithReference(apiService)
.WithReference(blobs)
""");
var buildRunPattern = "builder.Build().Run();";
var replacement = """
// Add Azure Container App Environment for managed identity support
builder.AddAzureContainerAppEnvironment("infra");
builder.Build().Run();
""";
content = DotnetProjectDeploymentHelpers.ReplaceExactlyOnce(content, buildRunPattern, replacement);
File.WriteAllText(appHostFilePath, content);
output.WriteLine($"Modified AppHost.cs with shared Azure Storage references at: {appHostFilePath}");
output.WriteLine($"New content:\n{content}");
output.WriteLine("Step 6: Navigating to AppHost directory...");
await auto.TypeAsync($"cd {projectName}.AppHost");
await auto.EnterAsync();
await auto.WaitForSuccessPromptAsync(counter);
await auto.TypeAsync($"unset ASPIRE_PLAYGROUND && export AZURE__LOCATION=westus3 && export AZURE__RESOURCEGROUP={resourceGroupName}");
await auto.EnterAsync();
await auto.WaitForSuccessPromptAsync(counter);
output.WriteLine("Step 7: Starting Azure deployment...");
await auto.TypeAsync("aspire deploy --clear-cache");
await auto.EnterAsync();
await auto.WaitForPipelineSuccessAsync(timeout: TimeSpan.FromMinutes(25));
await auto.WaitForSuccessPromptAsync(counter, TimeSpan.FromMinutes(2));
output.WriteLine("Step 8: Verifying both workloads reference the shared storage account...");
// Listing an empty account collection succeeds. Verify one account, both deployed
// connection strings, and blob data access for each workload's managed identity.
await DotnetProjectDeploymentHelpers.RunScriptAsync(auto, counter, $$"""
set -euo pipefail
az() { command az "$@" --subscription {{subscriptionId}}; }
storage=$(az storage account list -g {{resourceGroupName}} -o json)
echo "$storage" | jq -e 'length == 1'
storage_id=$(echo "$storage" | jq -er '.[0].id')
endpoint=$(echo "$storage" | jq -er '.[0].primaryEndpoints.blob')
# Principal IDs suffice; Graph name lookup would require a new token after the
# short-lived CI OIDC assertion has expired during deployment.
roles=$(az role assignment list --scope "$storage_id" --fill-principal-name false -o json)
apps=$(az containerapp list -g {{resourceGroupName}} -o json)
for resource in apiservice webfrontend; do
app=$(echo "$apps" | jq -er --arg resource "$resource" \
'[.[] | select(.name | startswith($resource))] | if length == 1 then .[0].name else error("Expected one workload") end')
config=$(az containerapp show -g {{resourceGroupName}} -n "$app" -o json)
echo "$config" | jq -e --arg endpoint "$endpoint" \
'[.properties.template.containers[].env[] | select(.name == "ConnectionStrings__blobs")] |
length == 1 and all(.[]; .value == $endpoint)'
client_id=$(echo "$config" | jq -er \
'[.properties.template.containers[].env[] | select(.name == "AZURE_CLIENT_ID")] |
if length == 1 then .[0].value else error("Expected one workload client ID") end')
principal_id=$(echo "$config" | jq -er --arg client "$client_id" \
'[.identity.userAssignedIdentities[] | select(.clientId == $client)] |
if length == 1 then .[0].principalId else error("Workload identity is not attached") end')
echo "$roles" | jq -e --arg principal "$principal_id" \
'any(.[]; .principalId == $principal and .roleDefinitionName == "Storage Blob Data Contributor")'
echo "$resource references the shared blob endpoint with blob data access"
done
""", TimeSpan.FromMinutes(3));
output.WriteLine("Step 9: Destroying Azure deployment...");
await auto.AspireDestroyAsync(counter);
await auto.TypeAsync("exit");
await auto.EnterAsync();
await pendingRun;
var duration = DateTime.UtcNow - startTime;
output.WriteLine($"Deployment completed in {duration}");
DeploymentReporter.ReportDeploymentSuccess(
nameof(DeployStarterWithSharedAzureStorageReferences),
resourceGroupName,
new Dictionary<string, string>(),
duration);
}
catch (Exception ex)
{
output.WriteLine($"Test failed: {ex.Message}");
DeploymentReporter.ReportDeploymentFailure(
nameof(DeployStarterWithSharedAzureStorageReferences),
resourceGroupName,
ex.Message);
throw;
}
finally
{
output.WriteLine($"Cleaning up resource group: {resourceGroupName}");
await CleanupResourceGroupAsync(resourceGroupName);
}
}
private async Task CleanupResourceGroupAsync(string resourceGroupName)
{
try
{
var process = new System.Diagnostics.Process
{
StartInfo = new System.Diagnostics.ProcessStartInfo
{
FileName = "az",
Arguments = $"group delete --name {resourceGroupName} --yes --no-wait",
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false
}
};
process.Start();
await process.WaitForExitAsync();
if (process.ExitCode == 0)
{
output.WriteLine($"Resource group deletion initiated: {resourceGroupName}");
}
else
{
var error = await process.StandardError.ReadToEndAsync();
output.WriteLine($"Resource group deletion may have failed (exit code {process.ExitCode}): {error}");
}
}
catch (Exception ex)
{
output.WriteLine($"Failed to cleanup resource group: {ex.Message}");
}
}
}