Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Prepare Azure environments for new workloads—subscriptions, networking, identity, and landing zones
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/recipes/azd/aspire.md
1# .NET Aspire Projects with AZD23**⛔ MANDATORY: For .NET Aspire projects, NEVER manually create azure.yaml. Use `azd init --from-code` instead.**45## Detection67| Indicator | How to Detect |8|-----------|---------------|9| `*.AppHost.csproj` | `find . -name "*.AppHost.csproj"` |10| `Aspire.Hosting` package | `grep -r "Aspire\.Hosting" . --include="*.csproj"` |11| `Aspire.AppHost.Sdk` | `grep -r "Aspire\.AppHost\.Sdk" . --include="*.csproj"` |1213## Workflow1415### ⛔ DO NOT (Wrong Approach)1617```yaml18# ❌ WRONG - Missing services section19name: aspire-app20metadata:21template: azd-init22# Results in: "Could not find infra\main.bicep" error23```2425### ✅ DO (Correct Approach)2627```bash28# Generate environment name29ENV_NAME="$(basename "$PWD" | tr '[:upper:]' '[:lower:]' | tr ' _' '-')-dev"3031# Use azd init with auto-detection32azd init --from-code -e "$ENV_NAME"33```3435**Generated azure.yaml:**36```yaml37name: aspire-app38metadata:39template: azd-init40services:41app:42language: dotnet43project: ./MyApp.AppHost/MyApp.AppHost.csproj44host: containerapp45```4647> 💡 **AddDockerfile services:** If the AppHost uses `AddDockerfile()` (e.g., `builder.AddDockerfile("ginapp", "./ginapp")`), do NOT add separate service entries for those resources. Aspire handles container builds for `AddDockerfile` resources at runtime through the AppHost. The `azure.yaml` should contain only the single `app` service pointing to the AppHost.4849> ⛔ **BEFORE continuing:** Complete the mandatory [AddParameter + WithBuildArg scan](#after-azd-init-fix-addparameter-used-with-withbuildarg-before-builddeploy) below. Skipping this step is the #1 cause of failed Aspire container-build deployments.5051## Command Flags5253| Flag | Required | Purpose |54|------|----------|---------|55| `--from-code` | ✅ | Auto-detect AppHost, no prompts |56| `-e <name>` | ✅ | Environment name (non-interactive) |57| `--no-prompt` | Optional | Skip all confirmations |5859**Why `--from-code` is critical:**60- Without: Prompts "How do you want to initialize?" (needs TTY)61- With: Auto-detects AppHost, no interaction needed62- Essential for agents and CI/CD6364## ⛔ After `azd init`: Fix AddParameter Used with WithBuildArg Before Build/Deploy6566> **MANDATORY** — After running `azd init --from-code`, but before `azd package`, `azd up`, or any Docker image build/deploy step, scan the AppHost source for `AddParameter` calls that are passed to `WithBuildArg` or `WithBuildSecret`. This pattern triggers an azd bug that causes Docker builds to fail.6768.NET Aspire [external parameters](https://aspire.dev/fundamentals/external-parameters/) let apps request values from the deployment environment. Each `AddParameter()` call generates a Bicep parameter in the deployment manifest. However, azd cannot resolve these Bicep parameters during the Docker image build phase, producing the error `parameter infra.parameters.<name> not found`. This bug has been present across all azd versions tested (including 1.24.0).6970### Scan for the pattern7172**Bash:**73```bash74grep -RIn --include="*.cs" -E "AddParameter|WithBuildArg|WithBuildSecret" <path/to/AppHost>75```7677**PowerShell:**78```powershell79Get-ChildItem -Path "<path/to/AppHost>" -Recurse -Filter "*.cs" |80Select-String -Pattern "AddParameter|WithBuildArg|WithBuildSecret"81```8283**Problematic pattern:**84```csharp85// ❌ azd cannot resolve AddParameter values during Docker builds86var goVersion = builder.AddParameter("goversion", "1.25.4", publishValueAsDefault: true);87builder.AddDockerfile("ginapp", "./ginapp")88.WithBuildArg("GO_VERSION", goVersion);89```9091### Fix Option A: Replace AddParameter with a constant (preferred)9293For every `AddParameter(name, defaultValue, ...)` whose result is used **only** as a `WithBuildArg` argument, replace it with a `const string` (or `string`) constant:9495```csharp96// ✅ Use a constant instead97const string goVersion = "1.25.4";98builder.AddDockerfile("ginapp", "./ginapp")99.WithBuildArg("GO_VERSION", goVersion);100```101102**Why:** This eliminates the parameter from Bicep output entirely, so azd never attempts to resolve it during Docker builds. Use this when the build arg value does not need to vary per deployment environment.103104### Fix Option B: Pre-set parameter in azd environment config105106If the value must remain an [external parameter](https://aspire.dev/fundamentals/external-parameters/) (e.g., it varies per environment), pre-set it in the azd environment config immediately after `azd init`:107108```bash109azd env config set infra.parameters.<name> <value>110```111112**Example:**113```bash114azd env config set infra.parameters.goversion 1.25.4115```116117**Why:** This writes the parameter value into `.azure/<env>/config.json` so azd can find it during Docker builds without modifying AppHost source code. Use this when the build arg value must be configurable per environment.118119> ⚠️ **Do NOT skip this step for container-build projects.** If the AppHost passes an `AddParameter` result to `WithBuildArg`, apply one of these fixes before running `azd up`.120121---122123## Troubleshooting124125### Error: "Could not find infra\main.bicep"126127**Cause:** Manual azure.yaml without services section128129**Fix:**1301. Delete manual azure.yaml1312. Run `azd init --from-code -e <env-name>`1323. Verify services section exists133134### Error: "no default response for prompt"135136**Cause:** Missing `--from-code` flag137138**Fix:** Always use `--from-code` for Aspire:139```bash140azd init --from-code -e "$ENV_NAME"141```142143### Error: "parameter infra.parameters.<name> not found"144145**Cause:** The AppHost uses `AddParameter()` as a `WithBuildArg` argument. azd cannot resolve Aspire [external parameters](https://aspire.dev/fundamentals/external-parameters/) during Docker builds, regardless of azd version.146147**Example error:**148```149ERROR: building service 'ginapp': parameter infra.parameters.goversion not found150```151152**Fix (Option A — preferred):** In the AppHost source, replace the `AddParameter(...)` call with a constant:153154```csharp155// ❌ Before (causes the error)156var goVersion = builder.AddParameter("goversion", "1.25.4", publishValueAsDefault: true);157builder.AddDockerfile("ginapp", "./ginapp")158.WithBuildArg("GO_VERSION", goVersion);159160// ✅ After (fix)161const string goVersion = "1.25.4";162builder.AddDockerfile("ginapp", "./ginapp")163.WithBuildArg("GO_VERSION", goVersion);164```165166**Fix (Option B):** Pre-set the parameter in azd environment config:167```bash168azd env config set infra.parameters.goversion 1.25.4169```170171### AppHost Not Detected172173**Solutions:**1741. Verify: `find . -name "*.AppHost.csproj"`1752. Build: `dotnet build`1763. Check package references in .csproj1774. Run from solution root178179### Error: "unsupported resource type" — Custom Aspire Resources180181**Symptoms:** `azd init --from-code` fails with `unsupported resource type` for one or more resources in the AppHost (e.g., custom child resources, ClockHand, or other custom Aspire integration types).182183**Cause:** The AppHost contains custom Aspire resource types designed for local development tooling only. These resources have no Azure equivalent and are not deployable.184185**Resolution:**1861871. ⛔ **Stop — do NOT fix this error by modifying source code.** Do not add `.ExcludeFromManifest()` to suppress the error.1882. ⛔ **Do NOT proceed with deployment.**1893. ✅ Inform the user: the application uses custom Aspire resource authoring patterns intended for local tooling, not cloud deployment.1904. ✅ Record a deployment blocker: "AppHost contains custom Aspire resource types (`unsupported resource type`) with no Azure deployment target."191192> ⚠️ Adding `.ExcludeFromManifest()` to work around this error violates the application's design intent and may produce an incomplete or incorrect deployment.193194## Infrastructure Auto-Generation195196| Traditional | Aspire |197|------------|--------|198| Manual infra/main.bicep | Auto-gen from AppHost |199| Define in IaC | Define in C# code |200| Update IaC per service | Add to AppHost |201202**How it works:**2031. AppHost defines services in C#2042. `azd provision` analyzes AppHost2053. Generates Bicep automatically2064. Deploys to Azure Container Apps207208## Validation Steps2092101. **⛔ Fix `AddParameter` used with `WithBuildArg`** — see [Post-Init: Fix AddParameter Used with WithBuildArg](#after-azd-init-fix-addparameter-used-with-withbuildarg-before-builddeploy)2112. Verify azure.yaml has a non-empty services section2123. Do NOT add separate service entries for `AddDockerfile()` resources — Aspire handles container builds at runtime through the AppHost2134. Run `azd package` to validate Docker build succeeds2145. Review generated infra/ (don't modify)215216## Next Steps2172181. Set subscription: `azd env set AZURE_SUBSCRIPTION_ID <id>`2192. Proceed to **azure-validate**2203. Deploy with **azure-deploy** (`azd up`)221222## References223224- [.NET Aspire External Parameters](https://aspire.dev/fundamentals/external-parameters/)225- [.NET Aspire Docs](https://learn.microsoft.com/dotnet/aspire/)226- [azd + Aspire](https://learn.microsoft.com/dotnet/aspire/deployment/azure/aca-deployment-azd-in-depth)227- [Samples](https://github.com/dotnet/aspire-samples)228- [Main Guide](../../aspire.md)229- [azure.yaml Schema](azure-yaml.md)230- [Docker Guide](docker.md)