Part 2 gave you every Kubernetes node as just another VM in vCenter: CPU ready, virtual disk latency, the ESXi host it sits on. The platform team, meanwhile, has pods, deployments and traces, and no idea which ESXi host any of them is running on. Neither side can quickly answer the first question in almost every Kubernetes-on-vSphere incident: which pods live on the VM that is hurting, and which VM is the pod I care about sitting in? This part puts OpenTelemetry collectors inside the cluster and, more importantly, gives both sides the same identity, so that answer becomes a query instead of a bridge call.
Level: intermediate to advanced · Stack: vSphere Kubernetes Service (VKS) on vSphere Supervisor, or kubeadm / RKE2 on vSphere VMs with the vSphere CPI and CSI; OpenTelemetry Collector 0.166 via the opentelemetry-collector Helm chart 0.184; OpenTelemetry Operator 0.164; the backends from part 4 · Build time: about 2 hours
Contents
- What we are building
- Kubernetes on vSphere: the parts that matter here
- Architecture: agent DaemonSet plus gateway Deployment
- The components, and what each one costs
- Helm chart or Operator
- The vSphere piece: node identity
- Templates
- End-to-end workflow
- Queries that prove the join works
- Troubleshooting
- Scaling, and what breaks first
01. What we are building
Two collector roles inside each cluster, an optional operator for application auto-instrumentation, and one small change to the vCenter collector you built in part 2. Nothing is installed on ESXi, and nothing changes on vCenter.
| Component | Runs as | Job |
|---|---|---|
| otel-agent | DaemonSet, one pod per node VM | Receives OTLP from pods on its node, enriches it with Kubernetes metadata (k8s_attributes), scrapes the local kubelet (kubelet_stats), tails container logs (file_log) and reads the guest OS (host_metrics). |
| otel-gateway | Deployment, 2 replicas | Single egress point to Tempo, Mimir or Prometheus, and Loki. Runs the cluster-wide k8s_cluster receiver under leader election, so only one replica scrapes the API server. |
| OpenTelemetry Operator (optional) | Deployment plus webhook | Injects language SDKs into pods that carry an annotation, configured by an Instrumentation resource. |
| vCenter collector (from part 2) | Wherever you put it | Gains one transform processor that stamps k8s.node.name on node VM metrics. That one label is what makes pod-to-VM joins possible. |
Scope. This part is about getting Kubernetes signals out and getting identity right. Following one slow request all the way down to datastore latency is part 6, and it depends on everything in section 06 here being in place.
02. Kubernetes on vSphere: the parts that matter here
A quick note on names, because they changed. What used to be vSphere with Tanzu, and Workload Management, is now vSphere Supervisor. The Tanzu Kubernetes Grid Service that builds workload clusters on it is now vSphere Kubernetes Service (VKS). Aria Operations is now VCF Operations. Everything below applies to vSphere 8 and VCF 9.
For observability, the two common shapes of Kubernetes on vSphere differ in exactly the places that matter: how a node knows which VM it is, how storage is provisioned, and what security policy the cluster enforces by default.
| Aspect | VKS on vSphere Supervisor | kubeadm, RKE2 or similar on vSphere VMs |
|---|---|---|
| Who creates node VMs | VM Operator on the Supervisor, from Cluster API objects in a vSphere Namespace | You, Terraform, or Cluster API Provider vSphere |
| Node name vs VM name | Same: the paravirtual cloud provider looks up the VirtualMachine object by node name | Whatever your provisioning chose. Often the hostname, not always the VM name |
spec.providerID | vsphere://<BIOS UUID>, taken from the VirtualMachine object | vsphere://<BIOS UUID>, set by the vSphere CPI from the node’s SMBIOS UUID |
| Persistent volumes | Paravirtual CSI: a guest PV maps to a PVC in the Supervisor namespace, which maps to a CNS volume | vSphere CSI: the PV’s volumeHandle is the CNS volume ID |
| Pod Security Admission | TKr 1.25 and later default to the restricted standard | Whatever you configured; often none |
| Kubelet serving certificate | Typically not signed by the cluster CA the service account trusts | Self-signed by default on kubeadm unless serverTLSBootstrap is on |
Two of those rows cause most first-day failures. The restricted Pod Security Standard rejects the agent, because it mounts /var/log/pods and the host root as hostPath volumes; you label the observability namespace to allow it. The kubelet certificate means kubelet_stats fails TLS verification until you either trust the right CA or set insecure_skip_verify. Both are handled in the templates.
03. Architecture: agent DaemonSet plus gateway Deployment
k8s.node.name to node VM metrics so the two halves join.Why two roles instead of one? Because the work splits cleanly by locality. Everything that needs to be on the node (reading the kubelet, tailing log files, reading /proc, and seeing the real source IP of a pod’s OTLP connection) belongs in the DaemonSet. Everything that should happen exactly once per cluster (scraping cluster state from the API server, holding backend credentials, retrying through a backend outage) belongs in the gateway.
The flow in words
- An application pod sends OTLP to
otel-agent.observability.svc. The Service usesinternalTrafficPolicy: Local(the chart default in DaemonSet mode), so traffic stays on the node and reaches that node’s agent. - The agent’s
k8s_attributesprocessor matches the data to a pod, first byk8s.pod.ipork8s.pod.uidif the SDK sent them, then by connection IP, and adds namespace, pod, deployment and node names from its local pod cache. - In parallel the agent scrapes the kubelet on
:10250every 20 seconds, tails/var/log/pods/*/*/*.log, and reads guest CPU, memory and disk counters through/hostfs. - A
resourceprocessor stampsk8s.node.nameandk8s.cluster.nameon anything that does not already have them, which includes the guest OS metrics. - Agents export OTLP/gRPC to the gateway Service. The gateway adds cluster-level metrics from
k8s_clusterand fans out to Tempo, Mimir or Prometheus, and Loki. - Separately, the vCenter collector from part 2 keeps polling vCenter. Its new
transformrule copies the VM name intok8s.node.namefor VMs that are cluster nodes.
Do not skip the gateway on small clusters. It is tempting to export straight from every agent. Then every node holds backend credentials, every node retries independently during a backend outage, and
k8s_clusterhas nowhere sensible to run. Two small gateway replicas cost far less than the debugging they save.
04. The components, and what each one costs
Component names changed during 2026: many contrib components moved to snake_case type names, and the old spellings still load as deprecated aliases with a startup warning. Use the new names in anything you write today. The batch processor was also deprecated in favour of batching inside each exporter (sending_queue.batch), which is why it does not appear in these pipelines.
| Component (old alias) | Role here | Stability | Kubernetes permissions |
|---|---|---|---|
k8s_attributes (k8sattributes) | Agent: adds pod, namespace, workload, node metadata | Stable for traces, metrics, logs | get/list/watch pods, namespaces, replicasets; nodes if you extract node labels |
kubelet_stats (kubeletstats) | Agent: node, pod, container, volume metrics from /stats/summary | Beta | get on nodes/stats (plus nodes/pods for some optional metrics) |
file_log (filelog) | Agent: container stdout/stderr from /var/log/pods | Beta | None; needs a hostPath mount |
host_metrics (hostmetrics) | Agent: guest OS CPU, memory, disk, filesystem | Beta (metrics) | None; needs hostPath mounts of / or /proc and /sys |
k8s_cluster | Gateway: pod phase, restarts, node conditions, workload state | Beta (metrics) | get/list/watch on most core and apps objects, plus leases for leader election |
otlp_grpc, otlp_http exporters (otlp, otlphttp) | Agent to gateway, gateway to Tempo and Loki | Stable | None |
prometheus_remote_write (prometheusremotewrite) | Gateway to Mimir or Prometheus | Beta | None |
k8s_attributes: association is everything
The processor keeps a cache of pods and their metadata and attaches it to incoming telemetry, but only after it has decided which pod the data came from. The chart preset tries, in order: a k8s.pod.ip resource attribute, a k8s.pod.uid resource attribute, then the source IP of the connection. Connection IP works when the agent sees the pod’s real address. It fails silently when something in the path rewrites it, for example a CNI that SNATs hostPort traffic. Having the SDK send k8s.pod.uid (the Operator does this with addK8sUIDAttributes, and the part 6 manifests do it with the downward API) makes association independent of the network path.
In the agent, filter.node_from_env_var restricts the cache to pods on the same node, which is what keeps memory and API server watch load flat as the cluster grows. The chart preset sets that for you in DaemonSet mode.
kubelet_stats: capacity, not latency
This is where storage people get disappointed. The kubelet summary API reports CPU, memory, network and filesystem usage, and for volumes it reports capacity, available bytes and inodes (k8s.volume.capacity, k8s.volume.available). It reports nothing about I/O latency. Kubernetes has no idea how long a write to a vSphere-backed PV took. That number lives in two other places: the guest kernel (host_metrics disk counters) and vCenter (virtual disk latency from part 2). The join in section 06 is what lets you put them next to a pod.
The receiver is migrating its metric names to the Kubernetes semantic conventions behind feature gates (receiver.kubelet_stats.EmitV1K8sConventions and receiver.kubelet_stats.DontEmitV0K8sConventions, both alpha in 0.166). Pin your collector version and read the changelog before upgrading, or dashboards will quietly go blank.
k8s_cluster: exactly once
Cluster-level state (pod phase, container restarts, node conditions, deployment replica counts) comes from watching the API server, so it must run in one place. Run it in a DaemonSet and every node reports the same numbers. The chart’s clusterMetrics preset adds the k8s_leader_elector extension automatically when the gateway has more than one replica, so you get availability without duplicates.
file_log and host_metrics: the guest view
file_log reads the files the kubelet writes under /var/log/pods; the container operator parses the CRI format and recovers namespace, pod, container and pod UID from the path. host_metrics reads the node VM’s own counters. Its disk scraper gives you system.disk.operation_time and system.disk.operations per device, and their ratio is the guest-side average I/O time. When guest await and vCenter’s virtual disk latency rise together, the problem is below the VM. When only the guest number rises, look inside the VM first.
05. Helm chart or Operator
Decision 01. How to deploy the collectors
- Options. The
opentelemetry-collectorHelm chart, or the OpenTelemetry Operator’sOpenTelemetryCollectorresource (API versionv1beta1). - Choice. The Helm chart.
- Why. Its presets wire the receiver configuration, the RBAC rules, the hostPath mounts and the downward API variables together, which is exactly the part people get wrong by hand.
helm templateshows you the rendered result before anything touches the cluster. - Cost. Presets can add configuration but cannot remove it. If you need to drop part of a preset, turn the preset off and write that component yourself.
Decision 02. How to instrument applications
- Options. Bake the SDK into each image, or let the Operator inject it at admission time based on an annotation.
- Choice. Both, deliberately. Teams that own their code bake it in (part 6 does this). For third-party or legacy Java, Python, .NET and Node.js workloads, the Operator’s
Instrumentationresource gets you traces without a rebuild. - Why. Injection is the fastest way to get first traces from code you cannot change. Baked-in SDKs give you version control and the ability to add custom spans where the interesting time is spent.
- Cost. The Operator runs an admission webhook, so it needs a certificate: either cert-manager, or the chart’s
autoGenerateCertoption. Injection also changes pods at admission, so annotate a test namespace before a production one.
06. The vSphere piece: node identity
Everything else in this post is standard Kubernetes observability. This section is the bit that makes it useful to a vSphere admin. The goal is that any pod-level signal can be joined to the vCenter metrics for the VM it runs on, and from there to the ESXi host.
What each side actually carries
| Hop | Left side has | Right side has | How they join |
|---|---|---|---|
| Pod to node | k8s.pod.* from k8s_attributes or the SDK | k8s.node.name (pod spec.nodeName) | Automatic. k8s_attributes adds the node name; the Operator also injects it. |
| Node to node VM | k8s.node.name, spec.providerID = vsphere://<BIOS UUID> | vcenter.vm.name, vcenter.vm.id (the instance UUID) | You configure it. Name match, or an explicit mapping. |
| Node VM to ESXi host | vcenter.host.name on every VM metric | vcenter.host.name on host metrics | Automatic. Same attribute on both. |
| Host or VM to datastore | Nothing in the VM or host resource attributes | vcenter.datastore.name, capacity and utilization only | Manual. PV to CNS volume to datastore (part 6). |
Why you cannot join on UUID
It looks as if the UUID in spec.providerID should match something in vCenter, and it does: the VM’s BIOS UUID (config.uuid). The vSphere cloud provider looks up the VM with the SearchIndex FindByUuid call using the BIOS UUID, and the paravirtual provider in VKS returns the VirtualMachine object’s BIOS UUID. The vcenter receiver, however, sets vcenter.vm.id from config.instanceUuid. Those are two different identifiers for the same VM, so a direct UUID join returns nothing. There is also a byte-order trap: the systemUUID the kubelet reports from SMBIOS can have its first three groups byte-swapped relative to vCenter’s format, which is why the vSphere CPI converts it before searching. Treat providerID, not systemUUID, as the source of truth.
The design: one canonical label, k8s.node.name
Rather than teaching every query about two naming schemes, put the same label on both sides. In-cluster, k8s.node.name is already there on pod, container, node and guest OS metrics, on spans and on logs. On the vSphere side, a transform rule in the part 2 collector copies vcenter.vm.name into k8s.node.name for VMs that are cluster nodes. After that, a pod and its node VM share a Prometheus label, k8s_node_name, and joins are ordinary PromQL.
- Option A: names already match. True for VKS (node name and VM name both come from the same Cluster API machine) and for any estate with a naming standard. One regex-scoped
set()statement covers every cluster node. - Option B: names differ. Run
node-vm-map.sh --ottl. It resolves each node’s BIOS UUID through govc and prints one explicitset()per node. Regenerate it when nodes are replaced. - Optional: put the VM identity on pod telemetry too.
node-vm-map.sh --labellabels each node with its VM name and BIOS UUID, and the agent’sk8s_attributesextracts those node labels asvsphere.vm.nameandvsphere.vm.bios_uuid. Useful in Option B so a span shows the vCenter name directly. It needs thenodesRBAC rule the agent template adds.
vMotion and node churn are fine. VM metrics carry the host the VM was on at scrape time, so after a vMotion you get a new series under the new
vcenter_host_name, and history stays correct. VKS rolling updates replace node VMs with new names; old series simply age out. The one thing to watch is a PromQL join across the few minutes right after a vMotion, when both the old and new host series are still within the lookback window. Section 10 covers that.
Several clusters? Node names are only unique within a cluster. Both templates set k8s.cluster.name; add it to every join once you have more than one cluster behind the same vCenter.
07. Templates
Everything here renders cleanly with helm template against chart 0.184.1. Placeholders are in angle brackets. No secret is written into any file.
Namespace with the right Pod Security label
apiVersion: v1
kind: Namespace
metadata:
name: observability
labels:
# The agent mounts hostPath (/var/log/pods, /hostfs) and runs as root when
# storeCheckpoints is on. VKS clusters on TKr 1.25+ default to the "restricted"
# Pod Security Standard, which rejects that, so relax it for this namespace only.
pod-security.kubernetes.io/enforce: privileged
pod-security.kubernetes.io/warn: privileged
Agent: otel-agent-values.yaml
# otel-agent-values.yaml
# Node agent: one collector per node VM (DaemonSet).
# helm upgrade --install otel-agent open-telemetry/opentelemetry-collector \
# -n observability -f otel-agent-values.yaml
mode: daemonset
fullnameOverride: otel-agent
image:
# The k8s distribution contains every component this agent uses.
repository: ghcr.io/open-telemetry/opentelemetry-collector-releases/opentelemetry-collector-k8s
# tag defaults to the chart appVersion. Pin it in production:
# tag: "<COLLECTOR_VERSION>"
presets:
kubernetesAttributes:
enabled: true # k8s_attributes processor + pods/namespaces/replicasets RBAC
kubeletMetrics:
enabled: true # kubelet_stats receiver + nodes/stats RBAC
logsCollection:
enabled: true # file_log receiver on /var/log/pods + hostPath mounts
storeCheckpoints: true # remember file offsets across agent restarts (runs as root)
hostMetrics:
enabled: true # host_metrics receiver: the guest OS view of the node VM
# The kubernetesAttributes preset does not grant access to Node objects.
# We extract node labels below, so add it here.
clusterRole:
rules:
- apiGroups: [""]
resources: ["nodes"]
verbs: ["get", "list", "watch"]
# A node-local Service (internalTrafficPolicy: Local is the chart default
# for daemonset mode) so apps can use one DNS name and still hit their own node's agent.
service:
enabled: true
ports:
jaeger-compact: { enabled: false }
jaeger-thrift: { enabled: false }
jaeger-grpc: { enabled: false }
zipkin: { enabled: false }
resources:
requests: { cpu: 100m, memory: 256Mi }
limits: { memory: 512Mi } # useGOMEMLIMIT (chart default) sets GOMEMLIMIT to 80% of this
config:
receivers:
jaeger: null
zipkin: null
prometheus: null
kubelet_stats:
# The preset sets endpoint, auth_type and a 20s interval. Most kubeadm-style
# clusters (VKS included) serve the kubelet with a self-signed certificate
# that the service account CA cannot verify.
insecure_skip_verify: true
metric_groups: [node, pod, container, volume]
processors:
batch: null # deprecated upstream; exporters batch via sending_queue instead
k8s_attributes:
# Merged on top of the preset: keep its metadata list, add node labels.
extract:
labels:
# Optional. Populated only if you label nodes with node-vm-map.sh (section 06).
- tag_name: vsphere.vm.name
key: vsphere.example.com/vm-name
from: node
- tag_name: vsphere.vm.bios_uuid
key: vsphere.example.com/bios-uuid
from: node
resource/node:
attributes:
# Every signal this agent handles originates on this node VM.
- key: k8s.node.name
value: ${env:OTEL_K8S_NODE_NAME}
action: insert
- key: k8s.cluster.name
value: <CLUSTER_NAME>
action: upsert
exporters:
otlp_grpc/gateway:
endpoint: otel-gateway.observability.svc.cluster.local:4317
tls:
insecure: true # in-cluster hop; switch to TLS if your policy requires it
sending_queue:
batch: {} # exporter-side batching replaces the deprecated batch processor
service:
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, k8s_attributes, resource/node]
exporters: [otlp_grpc/gateway]
metrics:
receivers: [otlp] # presets append kubelet_stats and host_metrics
processors: [memory_limiter, k8s_attributes, resource/node]
exporters: [otlp_grpc/gateway]
logs:
receivers: [otlp] # preset appends file_log
processors: [memory_limiter, k8s_attributes, resource/node]
exporters: [otlp_grpc/gateway]
The chart names the DaemonSet otel-agent-agent (it appends -agent in DaemonSet mode) and the Service otel-agent. The rendered agent ClusterRole contains pods, namespaces, replicasets, nodes/stats and the extra nodes rule; nothing else.
Gateway: otel-gateway-values.yaml
# otel-gateway-values.yaml
# Cluster gateway: receives from the agents, adds cluster-level metrics, exports to the backends.
# helm upgrade --install otel-gateway open-telemetry/opentelemetry-collector \
# -n observability -f otel-gateway-values.yaml
mode: deployment
fullnameOverride: otel-gateway
replicaCount: 2 # with clusterMetrics enabled the chart adds leader election, so only one replica scrapes
image:
# contrib, because prometheus_remote_write is not in the k8s distribution.
# If your metrics backend accepts OTLP, the k8s image plus otlp_http is enough.
repository: ghcr.io/open-telemetry/opentelemetry-collector-releases/opentelemetry-collector-contrib
# tag: "<COLLECTOR_VERSION>"
presets:
clusterMetrics:
enabled: true # k8s_cluster receiver + RBAC + leader election when replicas > 1
ports:
jaeger-compact: { enabled: false }
jaeger-thrift: { enabled: false }
jaeger-grpc: { enabled: false }
zipkin: { enabled: false }
resources:
requests: { cpu: 200m, memory: 512Mi }
limits: { memory: 1Gi }
podDisruptionBudget:
enabled: true
minAvailable: 1
config:
receivers:
jaeger: null
zipkin: null
prometheus: null
k8s_cluster:
node_conditions_to_report: [Ready, MemoryPressure, DiskPressure]
allocatable_types_to_report: [cpu, memory]
processors:
batch: null # deprecated upstream; exporters batch via sending_queue instead
resource/cluster:
attributes:
- key: k8s.cluster.name
value: <CLUSTER_NAME>
action: upsert
exporters:
otlp_grpc/tempo:
endpoint: <TEMPO_OTLP_GRPC_HOST>:4317
tls:
insecure: true # set ca_file instead when Tempo terminates TLS
sending_queue:
batch: {}
prometheus_remote_write:
http:
endpoint: <METRICS_REMOTE_WRITE_URL> # e.g. http://mimir-nginx.mimir.svc/api/v1/push
# Promote the attributes we join on to real labels. Everything else stays in target_info.
resource_constant_labels:
included:
- "k8s.cluster.name"
- "k8s.namespace.name"
- "k8s.node.name"
- "k8s.pod.name"
- "k8s.deployment.name"
- "k8s.statefulset.name"
- "k8s.daemonset.name"
- "k8s.container.name"
- "k8s.persistentvolumeclaim.name"
- "k8s.volume.name"
- "service.name"
otlp_http/loki:
endpoint: <LOKI_URL>/otlp # e.g. http://loki-gateway.loki.svc
sending_queue:
batch: {}
service:
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, resource/cluster]
exporters: [otlp_grpc/tempo]
metrics:
receivers: [otlp] # preset appends k8s_cluster
processors: [memory_limiter, resource/cluster]
exporters: [prometheus_remote_write]
logs:
receivers: [otlp]
processors: [memory_limiter, resource/cluster]
exporters: [otlp_http/loki]
resource_constant_labels replaced resource_to_telemetry_conversion in the remote write exporter from 0.160. On an older collector, use resource_to_telemetry_conversion: {enabled: true} instead and accept that every resource attribute becomes a label. If you prefer pure OTLP into Mimir or Prometheus, swap the exporter for otlp_http, switch the image back to the k8s distribution, and promote the same attributes on the backend side (Prometheus calls this otlp.promote_resource_attributes).
vCenter collector addition: transform/k8s_join
# Add to the vCenter collector from part 2 (the one running the vcenter receiver).
# Goal: give node-VM metrics the same k8s.node.name the in-cluster agents emit,
# so PromQL and Grafana can join on one label.
processors:
transform/k8s_join:
error_mode: ignore
metric_statements:
# Option A: VM name == node name (VKS, Cluster API, or a naming standard).
# Scope it to the clusters' VM names so ordinary VMs do not get k8s labels.
- set(resource.attributes["k8s.node.name"], resource.attributes["vcenter.vm.name"]) where resource.attributes["vcenter.vm.name"] != nil and IsMatch(resource.attributes["vcenter.vm.name"], "^<NODE_VM_NAME_REGEX>$")
- set(resource.attributes["k8s.cluster.name"], "<CLUSTER_NAME>") where resource.attributes["k8s.node.name"] != nil
# Option B: names differ. Paste the lines printed by node-vm-map.sh --ottl, e.g.
# - set(resource.attributes["k8s.node.name"], "worker-01") where resource.attributes["vcenter.vm.name"] == "prod-k8s-wrk-01"
service:
pipelines:
metrics:
receivers: [vcenter]
processors: [memory_limiter, transform/k8s_join] # keep your other processors
exporters: [prometheus_remote_write]
# ...and in the part 2 exporter, promote the new attributes:
# exporters:
# prometheus_remote_write:
# resource_constant_labels:
# included: ["vcenter.*", "site", "deployment.environment.name", "k8s.node.name", "k8s.cluster.name"]
The exporter in that collector must promote the new attributes too. The part 2 prometheus_remote_write exporter lists vcenter.*, site and deployment.environment.name under resource_constant_labels.included; add k8s.node.name and k8s.cluster.name to that list, or the transform does its work and the label never reaches Prometheus.
Node to VM mapping: node-vm-map.sh
#!/usr/bin/env bash
# node-vm-map.sh: map each Kubernetes node to its vSphere VM and ESXi host.
#
# Usage:
# export GOVC_URL='https://vcenter01.lab.local' GOVC_USERNAME='<READONLY_USER>'
# export GOVC_PASSWORD="$(cat ~/.secrets/vcenter-ro)" # never inline the password
# export GOVC_DATACENTER='<DATACENTER>' # needed if vCenter has more than one
# ./node-vm-map.sh # report only
# ./node-vm-map.sh --label # also label nodes (vsphere.example.com/vm-name, /bios-uuid)
# ./node-vm-map.sh --ottl # also print transform statements for names that differ
#
# Needs: kubectl (current context = the cluster), govc, read-only vCenter account.
set -euo pipefail
: "${GOVC_URL:?set GOVC_URL}"
: "${GOVC_USERNAME:?set GOVC_USERNAME}"
: "${GOVC_PASSWORD:?set GOVC_PASSWORD}"
MODE="${1:-report}"
LABEL_PREFIX="vsphere.example.com"
ottl=()
printf '%-38s %-38s %-26s %s\n' "NODE" "VM" "ESXI_HOST" "NAME_MATCH"
while IFS=$'\t' read -r node pid; do
uuid="${pid#vsphere://}"
if [[ -z "$pid" || "$uuid" == "$pid" ]]; then
printf '%-38s %-38s %-26s %s\n' "$node" "-" "-" "no vsphere:// providerID"
continue
fi
# providerID carries the BIOS UUID (VirtualMachine config.uuid), not the instance UUID.
info="$(govc vm.info -vm.uuid "$uuid" 2>/dev/null || true)"
vm="$(awk -F':[ \t]+' '/^Name:/{print $2; exit}' <<<"$info")"
host="$(awk -F':[ \t]+' '/^ *Host:/{print $2; exit}' <<<"$info")"
if [[ -z "$vm" ]]; then
printf '%-38s %-38s %-26s %s\n' "$node" "?" "?" "UUID $uuid not found"
continue
fi
match="yes"; [[ "$vm" == "$node" ]] || match="NO"
printf '%-38s %-38s %-26s %s\n' "$node" "$vm" "${host:-?}" "$match"
if [[ "$MODE" == "--label" ]]; then
kubectl label node "$node" --overwrite "${LABEL_PREFIX}/bios-uuid=${uuid}" >/dev/null
# Label values: max 63 chars, alphanumerics plus - _ . ; skip VM names that do not fit.
if [[ "$vm" =~ ^[A-Za-z0-9]([A-Za-z0-9._-]{0,61}[A-Za-z0-9])?$ ]]; then
kubectl label node "$node" --overwrite "${LABEL_PREFIX}/vm-name=${vm}" >/dev/null
else
echo " (vm name '$vm' is not a valid label value; bios-uuid label only)" >&2
fi
fi
if [[ "$match" == "NO" ]]; then
ottl+=("- set(resource.attributes[\"k8s.node.name\"], \"${node}\") where resource.attributes[\"vcenter.vm.name\"] == \"${vm}\"")
fi
done < <(kubectl get nodes -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.spec.providerID}{"\n"}{end}')
if [[ "$MODE" == "--ottl" && ${#ottl[@]} -gt 0 ]]; then
echo
echo "# Paste under processors.transform/k8s_join.metric_statements in the vCenter collector:"
printf '%s\n' "${ottl[@]}"
fi
The same lookup in PowerCLI, for estates where govc is not on the jump host. Config.Uuid is the BIOS UUID; Config.InstanceUuid is what the vcenter receiver reports.
# node-vm-map.ps1: run after Connect-VIServer vcenter01.lab.local (read-only account)
$nodes = kubectl get nodes -o json | ConvertFrom-Json
foreach ($n in $nodes.items) {
$uuid = $n.spec.providerID -replace '^vsphere://', ''
$vm = Get-View -ViewType VirtualMachine -Filter @{ 'Config.Uuid' = "^$uuid$" } `
-Property Name, Runtime.Host, Config.InstanceUuid
if (-not $vm) { "{0,-36} {1}" -f $n.metadata.name, 'NOT FOUND'; continue }
$esx = (Get-View $vm.Runtime.Host -Property Name).Name
"{0,-36} {1,-36} {2,-24} instance={3}" -f $n.metadata.name, $vm.Name, $esx, $vm.Config.InstanceUuid
}
OpenTelemetry Operator and the Instrumentation resource
# Operator, with a Helm-generated webhook certificate (use cert-manager if you already run it)
helm upgrade --install opentelemetry-operator open-telemetry/opentelemetry-operator \
-n opentelemetry-operator-system --create-namespace \
--set manager.collectorImage.repository=ghcr.io/open-telemetry/opentelemetry-collector-releases/opentelemetry-collector-k8s \
--set admissionWebhooks.certManager.enabled=false \
--set admissionWebhooks.autoGenerateCert.enabled=true
# Instrumentation CR: tells the OpenTelemetry Operator how to configure the SDKs it injects.
# kubectl apply -n <APP_NAMESPACE> -f instrumentation.yaml
apiVersion: opentelemetry.io/v1alpha1
kind: Instrumentation
metadata:
name: default
spec:
exporter:
# Node-local agent Service (internalTrafficPolicy: Local), OTLP/HTTP port.
# The Operator docs note that the injected Python, .NET and Go SDKs default to
# OTLP/HTTP, so the shared endpoint is 4318. If you inject a language that speaks
# OTLP/gRPC, override OTEL_EXPORTER_OTLP_ENDPOINT under that language with :4317.
endpoint: http://otel-agent.observability.svc.cluster.local:4318
propagators:
- tracecontext
- baggage
sampler:
type: parentbased_traceidratio
argument: "1" # 100% in the lab; 0.1 or lower in production
resource:
addK8sUIDAttributes: true # adds k8s.pod.uid and friends, so pod association never depends on source IP
python:
env:
- name: OTEL_PYTHON_LOG_CORRELATION # put trace_id/span_id into stdout log lines
value: "true"
---
# Opt a workload in with a pod template annotation (or annotate the whole namespace):
# metadata:
# annotations:
# instrumentation.opentelemetry.io/inject-python: "true"
# instrumentation.opentelemetry.io/inject-java: "true"
08. End-to-end workflow
Run these in order against a non-production cluster first. Each step has a check and the output you should expect before moving on.
Step 1. Confirm the nodes know they are vSphere VMs.
kubectl get nodes -o custom-columns=NODE:.metadata.name,PROVIDER:.spec.providerID
Expected: Every row shows vsphere:// followed by a UUID. An empty PROVIDER column means no vSphere cloud provider is running, and the UUID route in section 06 is unavailable; fall back to names.
Step 2. Map nodes to VMs and check the names.
export GOVC_URL=https://vcenter01.lab.local GOVC_USERNAME='<READONLY_USER>'
export GOVC_PASSWORD="$(cat ~/.secrets/vcenter-ro)"
./node-vm-map.sh
Expected: One line per node with a VM name, an ESXi host and NAME_MATCH yes. Any NO means you need Option B.
Step 3. Create the namespace.
kubectl apply -f observability-namespace.yaml
kubectl get ns observability --show-labels
Expected: Labels include pod-security.kubernetes.io/enforce=privileged.
Step 4. Add the chart repository.
helm repo add open-telemetry https://open-telemetry.github.io/opentelemetry-helm-charts
helm repo update
helm search repo open-telemetry/opentelemetry-collector
Expected: A chart version of 0.184 or later. Render once with helm template and read the ConfigMap before installing.
Step 5. Install the gateway first, so agents have somewhere to send.
helm upgrade --install otel-gateway open-telemetry/opentelemetry-collector \
-n observability -f otel-gateway-values.yaml
kubectl -n observability rollout status deploy/otel-gateway
kubectl -n observability get lease k8s.cluster.receiver.opentelemetry.io
Expected: deployment "otel-gateway" successfully rolled out, and a lease whose HOLDER is one of the two gateway pods.
Step 6. Install the agent.
helm upgrade --install otel-agent open-telemetry/opentelemetry-collector \
-n observability -f otel-agent-values.yaml
kubectl -n observability rollout status ds/otel-agent-agent
kubectl -n observability get pods -o wide -l app.kubernetes.io/instance=otel-agent
Expected: One Running agent pod per node, each on a different NODE.
Step 7. Check permissions and TLS.
kubectl auth can-i get nodes/stats --as=system:serviceaccount:observability:otel-agent
kubectl auth can-i watch nodes --as=system:serviceaccount:observability:otel-agent
kubectl -n observability logs ds/otel-agent-agent --tail=200 | grep -iE 'x509|forbidden|error'
Expected: yes, yes, and no x509 or forbidden lines.
Step 8. Confirm in-cluster metrics reached the backend (PromQL in Grafana Explore).
count by (k8s_node_name) (k8s_pod_cpu_usage)
count by (k8s_node_name) (system_disk_operations_total)
Expected: One row per node in both queries. Missing guest metrics usually means the hostPath mount was blocked.
Step 9. Add transform/k8s_join to the part 2 vCenter collector and restart it.
count by (k8s_node_name, vcenter_vm_name, vcenter_host_name) (vcenter_vm_cpu_readiness_percent{k8s_node_name!=""})
Expected: One row per node VM, with k8s_node_name equal to the node name from step 2 and the current ESXi host. Expect up to one vCenter collection interval before rows appear.
Step 10. Optional: install the Operator and instrument a test workload.
kubectl apply -n <APP_NAMESPACE> -f instrumentation.yaml
kubectl -n <APP_NAMESPACE> patch deploy <APP> -p \
'{"spec":{"template":{"metadata":{"annotations":{"instrumentation.opentelemetry.io/inject-python":"true"}}}}}'
kubectl -n <APP_NAMESPACE> get pod -l app=<APP> -o jsonpath='{.items[0].spec.initContainers[*].name}'
Expected: opentelemetry-auto-instrumentation-python, and within a minute, traces for that service in Tempo carrying k8s.node.name.
Step 11. Prove the join (section 09, first query).
max by (k8s_node_name, vcenter_host_name) (vcenter_vm_disk_latency_avg_milliseconds{disk_type="virtual"})
* on (k8s_node_name) group_right (vcenter_host_name)
(max by (k8s_node_name, k8s_namespace_name, k8s_pod_name) (k8s_pod_memory_working_set_bytes) * 0 + 1)
Expected: One row per pod, each carrying its node VM’s worst virtual disk latency and its ESXi host.
09. Queries that prove the join works
These are the queries I keep on a “Kubernetes on vSphere” dashboard. Metric names follow the default OTLP to Prometheus translation: dots become underscores and units become suffixes, so vcenter.vm.disk.latency.avg in milliseconds becomes vcenter_vm_disk_latency_avg_milliseconds, and units in braces such as {cpu} add no suffix.
| Question | PromQL |
|---|---|
| Which ESXi host is each node VM on right now? | max by (k8s_node_name, vcenter_host_name) (vcenter_vm_cpu_readiness_percent{k8s_node_name!=""}) |
| Which pods run on node VM X? | count by (k8s_namespace_name, k8s_pod_name) (k8s_pod_memory_working_set_bytes{k8s_node_name="<NODE>"}) |
| How many pods will a host maintenance mode move? | count by (vcenter_host_name) (max by (k8s_node_name, vcenter_host_name) (vcenter_vm_cpu_readiness_percent) * on (k8s_node_name) group_right (vcenter_host_name) (max by (k8s_node_name, k8s_namespace_name, k8s_pod_name) (k8s_pod_memory_working_set_bytes) * 0 + 1)) |
| Is the node VM contended for CPU? | vcenter_vm_cpu_readiness_percent{k8s_node_name="<NODE>"} |
| Guest view of disk latency, per device, ms | 1000 * sum by (device) (rate(system_disk_operation_time_seconds_total{k8s_node_name="<NODE>",direction="write"}[5m])) / sum by (device) (rate(system_disk_operations_total{k8s_node_name="<NODE>",direction="write"}[5m])) |
| vSphere view of the same disks, ms | max by (object, direction) (vcenter_vm_disk_latency_avg_milliseconds{k8s_node_name="<NODE>",disk_type="virtual"}) |
The last two belong side by side on one panel. They measure the same I/O from either side of the virtual SCSI controller. A gap between them is information: guest await well above vCenter’s number usually means queueing inside the guest (queue depth, filesystem, a single busy device), while the two moving together points below the VM, at the host or the datastore. Remember that vCenter’s value is one 20 second sample per collection (more on that in part 6), so compare trends, not individual points.
10. Troubleshooting
| Symptom | Likely cause | Check | Fix |
|---|---|---|---|
Agent pods rejected with violates PodSecurity "restricted" | VKS default Pod Security Standard, hostPath volumes | kubectl get events -n observability | Label the namespace enforce=privileged as in the template. Only that namespace. |
kubelet_stats errors with x509: certificate signed by unknown authority or IP SAN errors | Kubelet serving cert not signed by the service account CA | Agent logs | Set insecure_skip_verify: true, or enable kubelet serving certificate bootstrap and trust that CA via ca_file. |
kubelet_stats returns 403 | Missing nodes/stats permission | kubectl auth can-i get nodes/stats --as=... | Enable the kubeletMetrics preset, or add the rule to clusterRole.rules. |
Spans arrive without k8s.pod.name | Association failed: source IP rewritten, or pod not on this node | Temporarily add the debug exporter with verbosity: detailed to the agent | Send k8s.pod.uid or k8s.pod.ip from the SDK (downward API or addK8sUIDAttributes). |
vsphere.vm.name never appears | Nodes not labelled, or no nodes RBAC | kubectl get node <NODE> --show-labels | Run node-vm-map.sh --label; keep the extra ClusterRole rule. |
| Cluster metrics doubled | k8s_cluster running in more than one place | Count series per pod for k8s_pod_phase | Run it only in the gateway; keep leader election on. |
k8s_node_name missing from vCenter VM metrics | Transform not in the pipeline, regex wrong, or label not promoted by the exporter | Look at target_info or the debug exporter output of the vCenter collector | Fix the regex (anchor it with ^...$) and add k8s.node.name to the exporter’s promoted labels. |
Join query fails with many-to-many matching not allowed | A node VM was vMotioned; old and new host series both inside the lookback | Run the left-hand side alone | Drop vcenter_host_name from the by clause for joins, or wait a few minutes. |
| Logs missing for some pods | Agent restarted with start_at: end and no checkpoints | Are storeCheckpoints and the file_storage extension present? | Keep storeCheckpoints: true (the template does). |
| Dashboards blank after a collector upgrade | Metric names changed (semantic convention migration, component renames) | Changelog; compare metric names in Explore | Pin image tags; upgrade in a test cluster and diff metric names first. |
11. Scaling, and what breaks first
- API server watch load. Every agent’s
k8s_attributeswatches pods for its own node, which is cheap, but extracting node labels or workload metadata adds informers. On large clusters setwatch_sync_period: 0sas the processor documentation recommends. There is also an experimental kubelet pod source behind theprocessor.k8sattributes.EnableKubeletPodSourcefeature gate; do not run it in production yet. - Log volume.
file_logis usually the biggest consumer of agent CPU and of backend storage. Exclude noisy namespaces inexcludebefore you scale the backend. - Cardinality.
extractAllPodLabelsturns every pod label into a resource attribute and, through the exporter, potentially into a metric label. Leave it off and promote labels by name. - Gateway memory. The chart sets
GOMEMLIMITto 80 percent of the memory limit, andmemory_limiterrefuses data before the pod is OOM-killed. Scale gateway replicas horizontally; leader election keepsk8s_clustersingle. - The vCenter side. One vCenter collector now serves every cluster on that vCenter. Its sizing, not the in-cluster agents, is what limits how often you can sample node VM latency. That trade-off is covered in sizing the OTel collector for vSphere.
What’s next
With pods, node VMs and ESXi hosts sharing one label, the stack from parts 2 to 5 is complete. Part 6 uses it: one slow API request, followed from a trace in Tempo to the pod, the node VM, the ESXi host and finally the datastore, with the exact queries at every hop. If you need the cluster first, the VKS tutorial builds one on vSphere Supervisor, and running Kubernetes applications in a VMware environment covers the vanilla route. Running OpenShift instead? OpenTelemetry on OpenShift on vSphere covers the differences. For the vCenter receiver itself, go back to part 2; for the backends and dashboards, part 4.
Written against OpenTelemetry Collector 0.166 (contrib and k8s distributions), opentelemetry-collector Helm chart 0.184.1, OpenTelemetry Operator 0.164, vSphere 8 and VCF 9. Component names, metric names and chart presets move quickly; check the component READMEs before copying configuration into production, and treat everything here as a lab-first build.
Leave a Reply