{"record":{"id":"be8a70294128a2ba","repo":"microsoft/aspire","slug":"azureenvironmentresource-must-be-present-in-the-application-be8a70","errorCode":null,"errorMessage":"AzureEnvironmentResource must be present in the application model.","messagePattern":"AzureEnvironmentResource must be present in the application model\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/Aspire.Hosting.Foundry/HostedAgent/AzureHostedAgentResource.cs","lineNumber":155,"sourceCode":"    {\n        // Write agent manifest\n        ctx.Writer.WriteString(\"type\", \"azure.ai.agent.v0\");\n        ctx.Writer.WriteStartObject(\"definition\");\n        ctx.Writer.WriteString(\"kind\", \"hosted\");\n        ctx.Writer.WriteString(\"target\", Target.Name);\n        ctx.Writer.WriteEndObject(); // definition\n        ctx.TryAddDependentResources(Target);\n    }\n\n    /// <summary>\n    /// Deploys the specified agent to the given Microsoft Foundry project.\n    /// </summary>\n    private async Task<ProjectsAgentVersion> DeployAsync(PipelineStepContext context, AzureCognitiveServicesProjectResource project)\n    {\n        ArgumentNullException.ThrowIfNull(project);\n\n        var azureEnvironment = context.Model.Resources.OfType<AzureEnvironmentResource>().FirstOrDefault() ??\n            throw new InvalidOperationException(\"AzureEnvironmentResource must be present in the application model.\");\n\n        var provisioningContext = await azureEnvironment.ProvisioningContextTask.Task.ConfigureAwait(false);\n        var credential = provisioningContext.Credential;\n\n        var projectEndpoint = await project.Endpoint.GetValueAsync(context.CancellationToken).ConfigureAwait(false);\n        if (string.IsNullOrEmpty(projectEndpoint))\n        {\n            throw new InvalidOperationException($\"Project '{project.Name}' does not have a valid connection string.\");\n        }\n        var def = await ToHostedAgentConfigurationAsync(context).ConfigureAwait(false);\n        var options = def.ToProjectsAgentVersionCreationOptions(Target.Name);\n\n        var projectClient = new AIProjectClient(new Uri(projectEndpoint), credential);\n        var result = await projectClient.AgentAdministrationClient.CreateAgentVersionAsync(\n            Name,\n            options,\n            cancellationToken: context.CancellationToken\n        ).ConfigureAwait(false);","sourceCodeStart":137,"sourceCodeEnd":173,"githubUrl":"https://github.com/microsoft/aspire/blob/25830f84bd145686607ad00c057b3f84e2e51d43/src/Aspire.Hosting.Foundry/HostedAgent/AzureHostedAgentResource.cs#L137-L173","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Add an AzureEnvironmentResource to the AppHost (e.g. builder.AddAzureEnvironment(...)) so infrastructure provisioning supplies the provisioning context","Ensure the Azure environment is added before/alongside the Foundry project resources in the AppHost","If the deployment is not intended to be Azure-based, remove the AzureHostedAgentResource from the model instead"],"exampleFix":"// before: AppHost without Azure environment\nvar builder = DistributedApplication.CreateBuilder(args);\nvar foundry = builder.AddAzureCognitiveServicesProject(\"foundry\");\n// after\nvar builder = DistributedApplication.CreateBuilder(args);\nbuilder.AddAzureEnvironment(); // provisions infra and provides the provisioning context\nvar foundry = builder.AddAzureCognitiveServicesProject(\"foundry\");","handlingStrategy":"validation","validationCode":"// In AppHost code, guard before adding hosted agents:\nif (!builder.Resources.OfType<AzureEnvironmentResource>().Any())\n{\n    builder.AddAzureEnvironment(); // or fail fast with a clear message\n}","typeGuard":"bool HasAzureEnvironment(DistributedApplicationModel model) =>\n    model.Resources.OfType<AzureEnvironmentResource>().Any();","tryCatchPattern":"try\n{\n    // run deploy pipeline\n}\ncatch (InvalidOperationException ex) when (ex.Message.Contains(\"AzureEnvironmentResource must be present\"))\n{\n    // add builder.AddAzureEnvironment() to the AppHost and redeploy\n}","preventionTips":["Always call AddAzureEnvironment in AppHosts that deploy Foundry hosted agents","Keep the Azure environment registration at the top of the AppHost so it is hard to remove accidentally","Add a startup-time model validation check in custom AppHost tests asserting the environment resource exists"],"tags":["azure","foundry","deploy","app-model"],"backgroundTag":"missing-dependency","analyzedSha":"25830f84bd145686607ad00c057b3f84e2e51d43","analyzedAt":"2026-09-16T11:10:06.193Z","contentChangedAt":"2026-09-16T11:10:06.193Z","schemaVersion":2},"datasetVersion":"2026-09-21T04:17:39.646Z"}