microsoft/aspire · error · InvalidOperationException

AzureEnvironmentResource must be present in the application…

Error message

AzureEnvironmentResource must be present in the application model.

What it means

Deploying the hosted agent requires an Azure provisioning context (credential, subscription, resource group) which Aspire obtains from the AzureEnvironmentResource that provisioned the Foundry project's infrastructure. DeployAsync looks up that resource in the application model and throws this InvalidOperationException when the model contains none.

Solutions

  1. Add an AzureEnvironmentResource to the AppHost (e.g. builder.AddAzureEnvironment(...)) so infrastructure provisioning supplies the provisioning context
  2. Ensure the Azure environment is added before/alongside the Foundry project resources in the AppHost
  3. If the deployment is not intended to be Azure-based, remove the AzureHostedAgentResource from the model instead

Example fix

// before: AppHost without Azure environment
var builder = DistributedApplication.CreateBuilder(args);
var foundry = builder.AddAzureCognitiveServicesProject("foundry");
// after
var builder = DistributedApplication.CreateBuilder(args);
builder.AddAzureEnvironment(); // provisions infra and provides the provisioning context
var foundry = builder.AddAzureCognitiveServicesProject("foundry");
Defensive patterns

Strategy: validation

Validate before calling

// In AppHost code, guard before adding hosted agents:
if (!builder.Resources.OfType<AzureEnvironmentResource>().Any())
{
    builder.AddAzureEnvironment(); // or fail fast with a clear message
}

Type guard

bool HasAzureEnvironment(DistributedApplicationModel model) =>
    model.Resources.OfType<AzureEnvironmentResource>().Any();

Try / catch

try
{
    // run deploy pipeline
}
catch (InvalidOperationException ex) when (ex.Message.Contains("AzureEnvironmentResource must be present"))
{
    // add builder.AddAzureEnvironment() to the AppHost and redeploy
}

Prevention

When it happens

Trigger: The deploy pipeline step runs and `context.Model.Resources.OfType<AzureEnvironmentResource>().FirstOrDefault()` returns null, i.e. the AppHost never added an Azure environment resource (e.g. AddAzureEnvironment) even though an AzureHostedAgentResource deploy step is executing.

Common situations: AppHost deploys to Foundry but never calls the extension that adds the Azure environment resource; the Azure environment was removed during refactoring while hosted agents remained; running a deploy targeting only local resources while an AzureHostedAgentResource is still present in the model.

Understand the failure class

Background: "not installed", "pip install", "required for": how missing-dependency errors surface across open-source libraries — this error's family across 34 libraries.

Related errors


AI-assisted analysis of microsoft/aspire@25830f84bd (2026-09-16). Data as JSON: /api/errors/be8a70294128a2ba. Report an issue: GitHub.

Appendix: source

Thrown at src/Aspire.Hosting.Foundry/HostedAgent/AzureHostedAgentResource.cs:155

    {
        // Write agent manifest
        ctx.Writer.WriteString("type", "azure.ai.agent.v0");
        ctx.Writer.WriteStartObject("definition");
        ctx.Writer.WriteString("kind", "hosted");
        ctx.Writer.WriteString("target", Target.Name);
        ctx.Writer.WriteEndObject(); // definition
        ctx.TryAddDependentResources(Target);
    }

    /// <summary>
    /// Deploys the specified agent to the given Microsoft Foundry project.
    /// </summary>
    private async Task<ProjectsAgentVersion> DeployAsync(PipelineStepContext context, AzureCognitiveServicesProjectResource project)
    {
        ArgumentNullException.ThrowIfNull(project);

        var azureEnvironment = context.Model.Resources.OfType<AzureEnvironmentResource>().FirstOrDefault() ??
            throw new InvalidOperationException("AzureEnvironmentResource must be present in the application model.");

        var provisioningContext = await azureEnvironment.ProvisioningContextTask.Task.ConfigureAwait(false);
        var credential = provisioningContext.Credential;

        var projectEndpoint = await project.Endpoint.GetValueAsync(context.CancellationToken).ConfigureAwait(false);
        if (string.IsNullOrEmpty(projectEndpoint))
        {
            throw new InvalidOperationException($"Project '{project.Name}' does not have a valid connection string.");
        }
        var def = await ToHostedAgentConfigurationAsync(context).ConfigureAwait(false);
        var options = def.ToProjectsAgentVersionCreationOptions(Target.Name);

        var projectClient = new AIProjectClient(new Uri(projectEndpoint), credential);
        var result = await projectClient.AgentAdministrationClient.CreateAgentVersionAsync(
            Name,
            options,
            cancellationToken: context.CancellationToken
        ).ConfigureAwait(false);

View on GitHub (pinned to 25830f84bd)