Using base images with Azure Function host, Azure functions can now run inside a Kubernetes cluster. There are some traits of Azure Function that make it needs a special case to properly run Application Insights for Kubernetes
with it.
This page describes what are the challenges and explains how to work with them. For a full code example, please refer to this repository.
And in this post, we are talking about the in-proc/classlib model. With proper NuGet packages, the isolated model works with some other pitfalls, but that's out of the scope. See this repro for an example on the isolated model.
-
Azure Function will clean up assemblies that the host already carries. The problem is that the ones left might be a lower version,
System.Text.Json
for example, leading to runtime error.-
To address the assembly version mismatch, we need to disable the clean-up. Fortunately, there is a property to do it:
<PropertyGroup> <_FunctionsSkipCleanOutput>true</_FunctionsSkipCleanOutput> </PropertyGroup>
-
-
In Azure Function, HostedService is not allowed. It would halt the host.
Microsoft.ApplicationInsights.Kubernetes
leverages the BackgroundService (hosted service) to fetch K8s cluster properties.-
To compensate for that, we provided an overload to avoid registering any hosted service (6.1.0-beta1 or above):
// Set skipRegisterBackendService to true to avoid registering hosted service, which is not supported in Azure Function. builder.Services.AddApplicationInsightsKubernetesEnricher(LogLevel.Trace, disableBackgroundService: true);
-
Now that the background service is not there, we will have to bootstrap it manually in the user code. For example, it could be a timer trigger that runs at the startup:
public class ExampleAzureFunction { private readonly IK8sInfoBootstrap _bootstrap; private bool _ran = false; public ApplicationInsightsK8sBootstrap(IK8sInfoBootstrap bootstrap) { _bootstrap = bootstrap ?? throw new ArgumentNullException(nameof(bootstrap)); } [FunctionName("ExampleAzureFunction")] public void Run( [TimerTrigger("0 */5 * * * *", RunOnStartup = true)] TimerInfo myTimer, ILogger log) { if(_ran) { return; } _ran = true; log.LogInformation("Starting AIK8s Bootstrap"); _bootstrap.Run(); } }
-
-
This is not Azure Function specific, but you still will need to setup the RBAC permissions.
With those in place, Microsoft.ApplicationInsights.Kubernetes
will works in the Azure Function containers hosted in Kubernetes - just like the other apps.