feat: CommunityToolkit.Aspire.Hosting.K3s — k3s Kubernetes cluster hosting integration#1322
feat: CommunityToolkit.Aspire.Hosting.K3s — k3s Kubernetes cluster hosting integration#1322edmondshtogu wants to merge 37 commits into
Conversation
|
🚀 Dogfood this PR with:
curl -fsSL https://raw.githubusercontent.com/CommunityToolkit/Aspire/main/eng/scripts/dogfood-pr.sh | bash -s -- 1322Or
iex "& { $(irm https://raw.githubusercontent.com/CommunityToolkit/Aspire/main/eng/scripts/dogfood-pr.ps1) } 1322" |
|
@dotnet-policy-service agree |
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 37 out of 38 changed files in this pull request and generated 15 comments.
Comments suppressed due to low confidence (4)
src/CommunityToolkit.Aspire.Hosting.K3s/K3sBuilderExtensions.Manifest.cs:95
- This
asynccallback has no await, which will produce CS1998 and be treated as an error in this repo. Use a completedTaskreturn (or a synchronous overload) so the project builds cleanly.
resourceBuilder.WithContainerFiles("/k8s-manifests", async (ctx, ct) =>
{
if (Directory.Exists(absolutePath))
src/CommunityToolkit.Aspire.Hosting.K3s/K3sBuilderExtensions.Helm.cs:91
- This
asyncexpression-bodied callback has no await, so CS1998 will be emitted and treated as an error. Return a completed task (or use a synchronous overload) instead of marking the lambda async.
.WithContainerFiles("/helm-values", async (ctx, ct) =>
release.ValuesFiles
.Select((hostPath, i) => (ContainerFileSystemItem)new ContainerFile
src/CommunityToolkit.Aspire.Hosting.K3s/K3sInProcessPortForwarder.cs:152
- The same empty-selector case here can select the first ready pod in the namespace and forward traffic to an unrelated workload. Services without selectors are valid in Kubernetes, so the forwarder should not treat an empty selector as "all pods".
var selector = string.Join(",",
(svc.Spec.Selector ?? new Dictionary<string, string>()).Select(kv => $"{kv.Key}={kv.Value}"));
var pods = await k8sClient.CoreV1
.ListNamespacedPodAsync(@namespace, labelSelector: selector, cancellationToken: ct)
tests/CommunityToolkit.Aspire.Hosting.K3s.Tests/K3sClusterResourceTests.cs:253
- This test name says it verifies the pod subnet argument, but the assertion only checks that a cluster resource exists. It would still pass if
WithPodSubnetstopped adding--cluster-cidr, so it should assert the command-line args.
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
…isolation - Resolve .gitignore merge conflict markers (keep both sides) - Register K3sReadinessHealthCheck as a singleton to prevent per-tick client leaks - Write kubeconfig variants atomically via temp-file-then-rename - Fix stale credential recovery to not delete the raw kubeconfig k3s will not rewrite - Fix AllocatePort to probe on IPAddress.Any and re-allocate a fresh port on retry - Make WithDataVolume and WithReference(cluster) idempotent against duplicate calls - Apply HelmEscape to --set keys as well as values - Mark kubeconfig bind-mounts as read-only - Throw InvalidOperationException on no-selector services instead of silently marking ready - Add whitespace validation on serviceName/namespace in AddServiceEndpoint - Remove WithHttpsDeveloperCertificate from k3s container (no-op for k3s) - Extract K3sFileHelpers constant for 0755 script mode and /tmp/k3s-kubeconfig.yaml path - Switch kubeconfig container mount from directory to file-level to isolate kubectl cache
Health check (K3sReadinessHealthCheck): - Drop _cachedClient — registration was already fixed to singleton so the cache was live, but a fresh Kubernetes client per check is simpler, removes all stale-client invalidation complexity, and the TLS overhead every 5 s is negligible for local dev - Extract EnsureKubeconfigVariantsAsync; stale detection now only deletes the derived local/ and container/ files — rawPath is never touched Port forwarder (K3sInProcessPortForwarder): - Implement IAsyncDisposable; own a CancellationTokenSource and TcpListener as fields so DisposeAsync can cancel and release the socket independently of the outer application-lifetime token - RunAsync links _cts.Token with the outer ct so either side can stop the loop - Per-connection Task.Run now uses the linked token instead of CancellationToken.None — connections can be cancelled on shutdown - On listener failure a fresh port is re-allocated for the retry Service endpoint wiring: - K3sServiceEndpointResource retains the Forwarder reference - RunEndpointAsync wraps forwarder in await using so DisposeAsync runs on any exit path - Subscribe to ResourceStoppedEvent on the cluster to dispose the forwarder immediately when the cluster container stops, releasing the host port without waiting for the application-lifetime token
IEvangelist
left a comment
There was a problem hiding this comment.
This LGTM, I'm not going to merge it though as this really belongs to @aaronpowell — I'll leave that to him. Thank you for the PR though, @edmondshtogu.
|
Thanks @IEvangelist, also test I added are passing, the failing ones are not related with my changes. |
|
Did we verify that the TypeScript path works end to end? |
@davidfowl yes, I introduced additional changes since the callback (Action) was unusable in TypeScript polyglot apphosts — the generated Promise-based wrapper never resolved, making agentCount and the Helm/kubectl image overrides silently unreachable. Here is the TypeScript polyglot in action: |
|
Can someone approve the tests so I can see if there is anything else to be improved? |
|
Can someone approve the workflows again so I can see if there is anything else to be improved? Important The |
EndpointReference.IsAllocated caches its result on first call via a nullable bool field (??= pattern). For persistent containers in polyglot AppHosts, the health check can tick before DCP fires the endpoint allocation event, permanently caching false and making the port unresolvable for the lifetime of the process — leaving local/kubeconfig.yaml stale with port 6443. Replace the IsAllocated guard + GetValueAsync path with a direct read of EndpointAnnotation.AllocatedEndpoint.Port. This property is non-cached (checks IsValueSet on every call) and non-blocking (returns null if DCP has not yet allocated), so it picks up DCP's allocation on any subsequent health check tick regardless of when the first tick occurred. Port resolution order: 1. annotation.AllocatedEndpoint.Port — set by DCP on container start 2. annotation.Port — static apiServerPort from AddK3sCluster Remove the EndpointReference constructor parameter and the port hint file mechanism, both of which are unnecessary with this approach.
|
@aaronpowell could you please take a look at the PR and share if there is something you would like to change, or if you are happy to approve the integration? I'd love to start using this in my projects. Currently, because microsoft/aspire#16878 is still open, I can't add third-party integrations via the Aspire CLI, so having this package available is the only way around. |

Closes #1321
Overview of changes
Adds CommunityToolkit.Aspire.Hosting.K3s, a hosting integration that runs a lightweight Kubernetes cluster as an Aspire resource tree. Developers can declare a local Kubernetes cluster in Program.cs — with Helm charts, manifests, and exposed service endpoints — the same way they add Redis or PostgreSQL. No external tooling beyond a compatible container runtime (Docker or Podman) is required.
What's included
New package: src/CommunityToolkit.Aspire.Hosting.K3s/
New Tests & Examples:
Key design decisions
Health check via bind-mount, not docker exec. k3s writes its kubeconfig to
K3S_KUBECONFIG_OUTPUT=/tmp/k3s-kubeconfig/kubeconfig.yaml, bind-mounted toAppHostDirectory/.k3s/{name}/cluster/on the host. The health check pollsFile.Exists, rewrites server URLs intolocal/andcontainer/variants, then confirms node readiness viaIKubernetes.CoreV1.ListNodeAsync. No shell access, nodocker exec, works with any container runtime.Helm and kubectl run as containers.
HelmReleaseResourceandK8sManifestResourceextendContainerResourceand are shown as children of the cluster in the Aspire dashboard. The install/apply script is injected viaWithContainerFiles. They cannot useWaitFor(cluster)(Aspire forbids a child waiting for its parent), so their scripts poll for/root/.kube/kubeconfig.yaml— which only appears after the cluster health check passes — before proceeding. Consumers useWaitForCompletion(helmRelease)since these are run-to-completion containers.Kubeconfig delivered via bind-mount to all containers.
WithReference(cluster)on containers, the helm installer, and the kubectl applier all bind-mountAppHostDirectory/.k3s/{name}/container/(server:https://{name}:6443) at a known in-container path and setKUBECONFIG. Bind-mount is used uniformly so the kubeconfig updates automatically if the cluster is recreated without restarting dependent containers. NoKUBECONFIG_DATAbase64 encoding — all standard Kubernetes tooling (kubectl,helm, KubernetesClient SDK) works without custom bootstrap code.Kustomize auto-detected.
AddK8sManifestchecks forkustomization.yamlat configuration time: if present, it bind-mounts the directory (preserving relative base references) and useskubectl apply -k; otherwise it uses an asyncWithContainerFilescallback to copy only the YAML files at container-start time and applies withkubectl apply -f --server-side. The callback approach avoids Aspire's build-time path validation on the string overload. The script auto-detects the mode at runtime.Service exposure without NodePort.
K3sServiceEndpointResourcestarts an in-process KubernetesClient WebSocket port-forward bound to0.0.0.0:{hostPort}. Host resources receiveservices__{name}__url=http(s)://localhost:{port}; container resources receiveservices__{name}__url=http(s)://host.docker.internal:{port}with--add-host=host.docker.internal:host-gatewayinjected automatically viaContainerRuntimeArgsCallbackAnnotation(DCP does not inject this on Linux). The forwarder resolvestargetPortfrom the service spec (not the service port) before opening the pod WebSocket, and only signals ready after a running pod is confirmed — not when the TCP listener starts.Image overrides via K3sClusterOptions. The helm and kubectl container images are configurable via
HelmImage/HelmTag/HelmRegistryandKubectlImage/KubectlTag/KubectlRegistryonK3sClusterOptions. Defaults:docker.io/alpine/helm:3.17.3anddocker.io/alpine/kubectl:1.36.0.Robustness fixes from review.
WithK3sVersionpropagates the image tag to all agent nodes (prevents server/agent version skew).AddServiceEndpointvalidates the port is in the range 1–65535. Helm values files are indexed as{i}-{filename}so declaration order is preserved and basename collisions are safe. All helm--setvalues and--valuespaths are POSIX single-quote escaped viaShellEscape().Usage
Example
PR Checklist
Other information
Security Assumptions
This change assumes local development only. k3s runs in privileged mode (required by k3s/containerd). The bind-mounted kubeconfig directory is readable only by the AppHost user.
KubernetesClientConfigurationuses the embedded CA cert from the kubeconfig; noDangerousAcceptAnyServerCertificateValidatoris used.Remaining Follow-up Work
K3sClusterResourcehas no production counterpart configured.