Once you have more than two or three vCenters, the OpenTelemetry Collector config stops being the hard part. The hard part is keeping twelve nearly identical YAML files, twelve credentials, a pile of syslog ports and a few hundred ESXi Syslog.global.logHost values in agreement with each other, and with the inventory as it is today rather than as it was when someone last copied a file. This post replaces that hand-maintained sprawl with one CSV and one PowerCLI script that inventories every vCenter, renders a collector per vCenter, writes the systemd and Prometheus plumbing, points each ESXi host at the right collector, and validates the result before anything restarts.
Level: intermediate · Stack: PowerShell 7, VCF PowerCLI 9 (or VMware PowerCLI 13), Microsoft.PowerShell.SecretManagement, otelcol-contrib, systemd, Prometheus or Mimir, Loki · Build time: about 60 minutes for the first vCenter, minutes for each one after
Contents
- What the generator does, and what it refuses to do
- Design decisions
- The CSV contract
- Credentials without plaintext
- The complete script
- What it generates
- Pointing ESXi at its collector
- Validation before restart
- End-to-end workflow
- Troubleshooting
- What’s next
01. What the generator does, and what it refuses to do
The series so far built one collector by hand: the vcenter receiver in part 2, the ESXi syslog pipeline in part 3, and the exporters to Prometheus, Mimir and Loki in part 4. That is the right way to learn it and the wrong way to run it across an estate. The generator turns those hand-built pieces into a repeatable build with a single source of truth.
| Step | What happens | Touches production? |
|---|---|---|
| 1. Validate | Required columns, TlsMode values, collector names, and every TCP and UDP port on a shared collector host checked for clashes | No |
| 2. Inventory | Connect-VIServer per vCenter, then host count split by ESXi major version, VM count without templates, datastore and NFS datastore counts | Read only |
| 3. Render | Single-quoted templates with {{TOKENS}}, one collector config, env file and optional CA file per vCenter | No |
| 4. Write if changed | Byte comparison against the file on disk; untouched files stay untouched so config management and git diff stay quiet | No |
| 5. ESXi syslog | Only with -ConfigureEsxiSyslog: sets Syslog.global.logHost, enables the syslog firewall ruleset, reloads vmsyslogd, writes a marker message | Yes, honours -WhatIf and -Confirm |
| 6. Validate | Only with -OtelcolPath: runs otelcol-contrib validate against every generated config | No |
Things it deliberately does not do: it never writes a password to disk, never installs packages on the collector VMs, and never restarts a service. Distribution and restart belong to whatever you already use for Linux configuration (Ansible, Salt, a plain rsync plus a change ticket). The script produces artefacts; something with an audit trail ships them.
02. Design decisions
Decision 01. One collector per vCenter
- Options. One large collector with a
vcenter/<name>receiver per vCenter, or one collector process per vCenter. - Choice. One process per vCenter, run as instances of a single systemd template unit. Several instances can share a VM.
- Why. Syslog identity is the deciding factor. An ESXi syslog message carries a hostname, not a vCenter. If each vCenter's hosts send to their own collector, the collector stamps
service.namespaceandvcenter.serveron every record with no lookup table. It also gives you one credential per process, one restart blast radius, and the freedom to upgrade a lab vCenter's collector a week before production. - Cost. More processes and more ports to track, which is exactly what the CSV and the port clash check exist for.
Decision 02. Standard syslog ports wherever possible
- Options. One port pair per vCenter on a shared collector, or one collector VM (or IP) per vCenter on the standard ports.
- Choice. Standard ports: TCP 1514 for ESXi 8 (RFC 5424) and UDP 514 for ESXi 7 (RFC 3164). Offset ports only for hosts that support them.
- Why. The ESXi
syslogfirewall ruleset covers outbound UDP 514 and TCP 514 and 1514. Broadcom documents that from ESXi 8.0 Update 2b (and 7.0 P09) vmsyslogd opens non-standard ports automatically with dynamic rules; before that a custom port needs a custom firewall rule delivered as a VIB. The script warns whenever a row uses a non-standard port. - Cost. Binding 514 as the unprivileged
otelcol-contribuser needsCAP_NET_BIND_SERVICE, which the generated unit grants and nothing else.
Decision 03. RFC 5424 with octet counting on ESXi 8
ESXi 8.0 can emit RFC 3164 or RFC 5424 and selects it per destination with a ?formatter= suffix on the logHost URI. The vSphere 8 documentation is explicit that RFC 5424 output must use octet-counting framing, which keeps multi-line messages (stack traces, structured data) inside one record. So ESXi 8 hosts get tcp://<collector>:1514?formatter=RFC_5424&framing=octet_counting, and the matching receiver sets enable_octet_counting: true. ESXi 7 hosts stay on plain UDP and RFC 3164. The script picks per host from $vmhost.Version, so a mixed cluster mid-upgrade gets the right value on each host.
Decision 04. Templates in single-quoted here-strings
This one is PowerShell specific and bites everyone once. The collector config wants the literal text ${env:VCENTER_PASSWORD}. Inside a double-quoted PowerShell string, ${env:VCENTER_PASSWORD} is PowerShell's own syntax for reading an environment variable, so the generator would silently substitute the password of whoever ran it, or an empty string. The script keeps every template in single-quoted here-strings and replaces {{TOKEN}} markers with a plain string replace, then fails hard if any token survives. No escaping rules to remember, and no way to leak a secret through interpolation.
Decision 05. Deterministic output
Idempotency in a generator means two things: the same inputs produce byte-identical files, and identical files are not rewritten. The script therefore writes no timestamps into generated content, normalises line endings to LF (a trailing carriage return in a systemd EnvironmentFile becomes part of the value), writes UTF-8 without a BOM, and compares before writing. The second run of an unchanged CSV reports every file as Unchanged, which is the property that lets you run it from a scheduled pipeline and only get a diff when the estate actually changed.
Decision 06. Current component names
Recent otelcol-contrib releases renamed several components to snake case: prometheus_remote_write (was prometheusremotewrite), otlp_http (was otlphttp) and delta_to_cumulative (was deltatocumulative). The old names still work as deprecated aliases and log a warning. The templates use the new names and the newer http: block for the remote write endpoint, checked with otelcol-contrib components on v0.166.0. If you run an older collector, swap the names back; validate will tell you immediately which one it does not recognise. The vcenter receiver itself is still alpha for metrics and the syslog receiver is beta, so pin your collector version in the package repo rather than tracking latest.
03. The CSV contract
One row per vCenter. Empty optional cells fall back to defaults; required cells are checked before anything connects.
| Column | Required | Default | Meaning |
|---|---|---|---|
VCenter | Yes | FQDN used for Connect-VIServer and the receiver endpoint | |
Site | Yes | Free text, becomes the site label | |
CollectorName | Yes | Lowercase DNS label; systemd instance name and output folder | |
CollectorHost | Yes | Collector VM FQDN, used for scrape targets and port clash checks | |
CollectorIp | Yes | Address ESXi sends syslog to | |
SyslogTcpPort | No | 1514 | RFC 5424 listener for ESXi 8 |
SyslogUdpPort | No | 514 | RFC 3164 listener for ESXi 7 |
TelemetryPort | No | 8888 | Collector self-metrics, scraped by Prometheus |
HealthPort | No | 13133 | health_check extension |
CollectionInterval | No | 2m, or 3m above 2000 VMs | vcenter receiver interval |
ServiceAccount | Yes | Read-only account the collector uses | |
CredentialSecret | Yes | Vault secret name for the account the script uses | |
TlsMode | Yes | system (OS trust store), cafile (ship a PEM), skip (lab only) | |
CaFile | If cafile | Local path to the vCenter root CA PEM | |
Enabled | No | true | false keeps the row in the file but skips it |
Template with placeholders:
VCenter,Site,CollectorName,CollectorHost,CollectorIp,SyslogTcpPort,SyslogUdpPort,TelemetryPort,HealthPort,CollectionInterval,ServiceAccount,CredentialSecret,TlsMode,CaFile,Enabled
<VCENTER_FQDN>,<SITE>,<COLLECTOR_NAME>,<COLLECTOR_VM_FQDN>,<COLLECTOR_IP>,1514,514,8888,13133,,<READONLY_USER>@vsphere.local,<VAULT_SECRET_NAME>,cafile,./certs/<COLLECTOR_NAME>-ca.pem,true
A worked example, which is also the input for every output shown later. Note the third row: it shares otel01 with vcenter01, so every port is offset, and the script will warn that its ESXi hosts must be on 8.0 Update 2b or later.
VCenter,Site,CollectorName,CollectorHost,CollectorIp,SyslogTcpPort,SyslogUdpPort,TelemetryPort,HealthPort,CollectionInterval,ServiceAccount,CredentialSecret,TlsMode,CaFile,Enabled
vcenter01.lab.local,dc1,vcenter01,otel01.lab.local,10.0.10.51,1514,514,8888,13133,,svc-otel-ro@vsphere.local,vcenter01-admin,cafile,./certs/vcenter01-ca.pem,true
vcenter02.lab.local,dc2,vcenter02,otel02.lab.local,10.0.20.51,1514,514,8888,13133,3m,svc-otel-ro@vsphere.local,vcenter02-admin,system,,true
vcenter-lab.lab.local,lab,vcenter-lab,otel01.lab.local,10.0.10.51,1515,515,8889,13134,1m,svc-otel-ro@vsphere.local,lab-admin,skip,,true
Two identities, on purpose.
ServiceAccountis the read-only account baked into the collector's env file; the vcenter receiver documentation asks for a Read Only user with permissions on the vCenter and everything below it.CredentialSecretnames the account the script itself uses, which needs more: reading inventory is fine with Read Only, but step 5 changes host advanced settings and the host firewall (the Host > Configuration privileges for advanced settings and for security profile and firewall). Never reuse the script's account in the collector.
04. Credentials without plaintext
The script resolves the credential for each row in a fixed order: first Get-Secret -Name <CredentialSecret> -Vault <SecretVault> from Microsoft.PowerShell.SecretManagement, which must return a PSCredential; then the environment variables OTELGEN_VC_USER and OTELGEN_VC_PASSWORD, which is how a CI runner with its own secret store injects them. If neither exists it stops for that vCenter. It never prompts, so it behaves the same interactively and in a pipeline.
# One-time setup on the admin workstation or automation host
Install-Module Microsoft.PowerShell.SecretManagement, Microsoft.PowerShell.SecretStore -Scope CurrentUser
Install-Module VCF.PowerCLI -Scope CurrentUser # or VMware.PowerCLI 13.x on older estates
Register-SecretVault -Name OtelVault -ModuleName Microsoft.PowerShell.SecretStore
# One PSCredential per vCenter row (the CredentialSecret column)
Set-Secret -Vault OtelVault -Name <VAULT_SECRET_NAME> -Secret (Get-Credential -Message '<VCENTER_FQDN> automation account')
Get-SecretInfo -Vault OtelVault | Format-Table Name, Type
SecretStore asks for its own password and locks again after a timeout, which is what you want on a workstation. On a dedicated automation host running unattended you can relax that with Set-SecretStoreConfiguration -Scope CurrentUser -Authentication None -Interaction None, at which point the protection is the OS account and file permissions; make that a conscious decision, not a default. Any other SecretManagement extension vault (Azure Key Vault, HashiCorp Vault, KeePass) works the same way because the script only calls Get-Secret.
On the collector side the password is the one secret the generated files never contain. Each instance loads two env files: the generated collector.env (username and CA path) and /etc/otelcol-contrib/secrets/<name>.env, mode 0600, owned by root, created once per collector by a human or by your secrets tooling. systemd reads EnvironmentFile as root before it drops to the service user, so the collector process gets the variable without the otelcol-contrib user being able to read the file.
05. The complete script
Save as New-OtelVCenterCollectorConfig.ps1. It needs PowerShell 7 and, unless you pass -SkipInventory, the VMware.VimAutomation.Core module that ships inside VCF PowerCLI and VMware PowerCLI. Everything is parameterised; there are no hostnames inside the script.
#Requires -Version 7.0
<#
.SYNOPSIS
Inventories vCenters listed in a CSV and generates one OpenTelemetry Collector
(otelcol-contrib) configuration per vCenter, plus systemd units, env files,
a Prometheus file_sd target list and an inventory CSV. Optionally points every
ESXi host's syslog at its vCenter's collector.
.DESCRIPTION
Idempotent: files are only rewritten when their content changes, and ESXi
settings are only touched when they differ from the desired value.
Supports -WhatIf and -Confirm. Never writes a password to disk.
Credentials for Connect-VIServer are resolved in this order:
1. Microsoft.PowerShell.SecretManagement: Get-Secret -Name <CredentialSecret> -Vault <SecretVault>
(the secret must be stored as a PSCredential)
2. Environment variables OTELGEN_VC_USER and OTELGEN_VC_PASSWORD
.EXAMPLE
./New-OtelVCenterCollectorConfig.ps1 -InventoryCsv ./vcenters.csv `
-MetricsRemoteWriteUrl 'https://<MIMIR_FQDN>/api/v1/push' `
-LokiOtlpUrl 'http://<LOKI_FQDN>:3100/otlp' -WhatIf
#>
[CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')]
param(
[Parameter(Mandatory)]
[ValidateScript({ Test-Path -LiteralPath $_ -PathType Leaf })]
[string]$InventoryCsv,
[string]$OutputPath = './otel-generated',
[Parameter(Mandatory)]
[ValidatePattern('^https?://')]
[string]$MetricsRemoteWriteUrl,
[Parameter(Mandatory)]
[ValidatePattern('^https?://')]
[string]$LokiOtlpUrl,
[string]$SecretVault = 'OtelVault',
# Generate from the CSV alone, without connecting to vCenter.
[switch]$SkipInventory,
# Point ESXi syslog (Syslog.global.logHost) at the collector for that vCenter.
[switch]$ConfigureEsxiSyslog,
# Remove every existing logHost entry instead of appending ours.
[switch]$ReplaceExistingLogHosts,
# Path to an otelcol-contrib binary; when set, every generated config is validated.
[string]$OtelcolPath,
# Install prefix used inside the generated files (where configs live on the collector VM).
[string]$RemoteConfigRoot = '/etc/otelcol-contrib'
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
if ($ConfigureEsxiSyslog -and $SkipInventory) { throw '-ConfigureEsxiSyslog needs a vCenter connection; drop -SkipInventory.' }
# [IO.File] resolves relative paths against the process directory, not $PWD. Resolve once.
$OutputPath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($OutputPath)
$script:Results = [System.Collections.Generic.List[object]]::new()
$StandardSyslogPorts = @{ tcp = @(514, 1514); udp = @(514) }
#region helpers ---------------------------------------------------------------
function Write-GeneratedFile {
[CmdletBinding(SupportsShouldProcess)]
param([Parameter(Mandatory)][string]$Path, [Parameter(Mandatory)][string]$Content)
# LF only: systemd EnvironmentFile values break on a trailing CR.
$normalized = ($Content -replace "`r`n", "`n").TrimEnd("`n") + "`n"
$status = 'Created'
if (Test-Path -LiteralPath $Path) {
if ([IO.File]::ReadAllText($Path) -ceq $normalized) {
$script:Results.Add([pscustomobject]@{ Target = $Path; Action = 'File'; Status = 'Unchanged' })
return
}
$status = 'Updated'
}
if ($PSCmdlet.ShouldProcess($Path, "$status generated file")) {
$dir = Split-Path -Parent $Path
if (-not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null }
[IO.File]::WriteAllText($Path, $normalized, [Text.UTF8Encoding]::new($false))
} else { $status = "WhatIf-$status" }
$script:Results.Add([pscustomobject]@{ Target = $Path; Action = 'File'; Status = $status })
}
function Expand-Template {
param([string]$Template, [hashtable]$Values)
$out = $Template
foreach ($k in $Values.Keys) { $out = $out.Replace("{{$k}}", [string]$Values[$k]) }
if ($out -match '\{\{[A-Z_]+\}\}') { throw "Unexpanded token $($Matches[0]) in template" }
$out
}
function Get-VCenterCredential {
param([string]$SecretName)
if ($SecretName -and (Get-Command -Name Get-Secret -ErrorAction SilentlyContinue)) {
try {
$s = Get-Secret -Name $SecretName -Vault $SecretVault -ErrorAction Stop
if ($s -is [pscredential]) { return $s }
Write-Warning "Secret '$SecretName' is not a PSCredential; store it with Set-Secret -Secret (Get-Credential)."
} catch { Write-Verbose "SecretManagement lookup for '$SecretName' failed: $($_.Exception.Message)" }
}
if ($env:OTELGEN_VC_USER -and $env:OTELGEN_VC_PASSWORD) {
$sec = ConvertTo-SecureString -String $env:OTELGEN_VC_PASSWORD -AsPlainText -Force
return [pscredential]::new($env:OTELGEN_VC_USER, $sec)
}
throw "No credential for secret '$SecretName': register it in vault '$SecretVault' or set OTELGEN_VC_USER / OTELGEN_VC_PASSWORD."
}
function Get-DesiredLogHost {
param($Row, [version]$EsxiVersion)
if ($EsxiVersion -ge [version]'8.0') {
# RFC 5424 over TCP needs octet-counting framing (vSphere 8 syslog docs).
"tcp://$($Row.CollectorIp):$($Row.SyslogTcpPort)?formatter=RFC_5424&framing=octet_counting"
} else {
"udp://$($Row.CollectorIp):$($Row.SyslogUdpPort)"
}
}
#endregion
#region templates -------------------------------------------------------------
$CollectorTemplate = @'
# Generated by New-OtelVCenterCollectorConfig.ps1. Do not edit by hand; edit the CSV and regenerate.
# vCenter: {{VCENTER}} site: {{SITE}} collector: {{NAME}}
extensions:
health_check:
endpoint: 0.0.0.0:{{HEALTH_PORT}}
receivers:
vcenter:
endpoint: https://{{VCENTER}}
username: ${env:VCENTER_USERNAME}
password: ${env:VCENTER_PASSWORD}
collection_interval: {{INTERVAL}}
initial_delay: 10s
{{TLS_BLOCK}}
# ESXi 8.x hosts: RFC 5424, TCP, octet counting
syslog/esxi_rfc5424:
tcp:
listen_address: 0.0.0.0:{{TCP_PORT}}
protocol: rfc5424
enable_octet_counting: true
resource:
service.name: esxi
# ESXi 7.x hosts: RFC 3164, UDP
syslog/esxi_rfc3164:
udp:
listen_address: 0.0.0.0:{{UDP_PORT}}
protocol: rfc3164
location: UTC
resource:
service.name: esxi
processors:
memory_limiter:
check_interval: 1s
limit_percentage: 80
spike_limit_percentage: 20
resource/vcenter:
attributes:
- key: service.namespace
value: {{NAME}}
action: upsert
- key: vcenter.server
value: {{VCENTER}}
action: upsert
- key: site
value: {{SITE}}
action: upsert
exporters:
prometheus_remote_write:
http:
endpoint: {{PRW_URL}}
resource_constant_labels:
included: ["vcenter.*", "service.namespace", "site"]
otlp_http/loki:
endpoint: {{LOKI_URL}}
sending_queue:
batch: {}
service:
extensions: [health_check]
telemetry:
metrics:
readers:
- pull:
exporter:
prometheus:
host: 0.0.0.0
port: {{TELEMETRY_PORT}}
pipelines:
metrics/vcenter:
receivers: [vcenter]
processors: [memory_limiter, resource/vcenter]
exporters: [prometheus_remote_write]
logs/esxi:
receivers: [syslog/esxi_rfc5424, syslog/esxi_rfc3164]
processors: [memory_limiter, resource/vcenter]
exporters: [otlp_http/loki]
'@
$EnvTemplate = @'
# Generated. Contains no secrets. The password lives in {{ROOT}}/secrets/{{NAME}}.env (0600 root).
VCENTER_USERNAME={{USER}}
VCENTER_CA_FILE={{CA_PATH}}
'@
$UnitTemplate = @'
# Generated by New-OtelVCenterCollectorConfig.ps1
# One instance per vCenter: systemctl enable --now otelcol-contrib@<collector-name>
[Unit]
Description=OpenTelemetry Collector Contrib for %i
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=otelcol-contrib
Group=otelcol-contrib
EnvironmentFile={{ROOT}}/%i/collector.env
EnvironmentFile={{ROOT}}/secrets/%i.env
ExecStartPre=/usr/bin/otelcol-contrib validate --config={{ROOT}}/%i/config.yaml
ExecStart=/usr/bin/otelcol-contrib --config={{ROOT}}/%i/config.yaml
ExecReload=/bin/kill -HUP $MAINPID
KillMode=mixed
Restart=on-failure
RestartSec=10s
# Lets the non-root service bind UDP/TCP 514.
AmbientCapabilities=CAP_NET_BIND_SERVICE
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
NoNewPrivileges=true
LockPersonality=true
RestrictRealtime=true
RestrictSUIDSGID=true
ProtectControlGroups=true
ProtectKernelModules=true
ProtectKernelTunables=true
ProtectHostname=true
[Install]
WantedBy=multi-user.target
'@
#endregion
#region load and validate the CSV ---------------------------------------------
$required = 'VCenter', 'Site', 'CollectorName', 'CollectorHost', 'CollectorIp', 'ServiceAccount', 'CredentialSecret', 'TlsMode'
$rows = @(Import-Csv -LiteralPath $InventoryCsv)
if ($rows.Count -eq 0) { throw "$InventoryCsv has no rows" }
$missing = $required | Where-Object { $_ -notin $rows[0].PSObject.Properties.Name }
if ($missing) { throw "CSV is missing columns: $($missing -join ', ')" }
$rows = foreach ($r in $rows) {
if ($r.PSObject.Properties.Name -contains 'Enabled' -and $r.Enabled -match '^(false|no|0)$') {
Write-Verbose "Skipping disabled row $($r.VCenter)"; continue
}
foreach ($p in @{ SyslogTcpPort = 1514; SyslogUdpPort = 514; TelemetryPort = 8888; HealthPort = 13133 }.GetEnumerator()) {
if (-not ($r.PSObject.Properties.Name -contains $p.Key) -or [string]::IsNullOrWhiteSpace($r.($p.Key))) {
$r | Add-Member -NotePropertyName $p.Key -NotePropertyValue $p.Value -Force
}
$r.($p.Key) = [int]$r.($p.Key)
}
if ($r.TlsMode -notin 'system', 'cafile', 'skip') { throw "$($r.VCenter): TlsMode must be system, cafile or skip" }
if ($r.TlsMode -eq 'cafile' -and -not ($r.PSObject.Properties.Name -contains 'CaFile' -and $r.CaFile -and (Test-Path -LiteralPath $r.CaFile))) {
throw "$($r.VCenter): TlsMode cafile needs an existing CaFile path"
}
if ($r.CollectorName -notmatch '^[a-z0-9][a-z0-9-]{0,62}$') { throw "$($r.VCenter): CollectorName must be lowercase DNS-label style" }
$r
}
$rows = @($rows)
# Every port on a shared collector host must be unique.
foreach ($g in ($rows | Group-Object CollectorHost)) {
$ports = $g.Group | ForEach-Object { "tcp/$($_.SyslogTcpPort)"; "udp/$($_.SyslogUdpPort)"; "tcp/$($_.TelemetryPort)"; "tcp/$($_.HealthPort)" }
$dupes = $ports | Group-Object | Where-Object Count -gt 1
if ($dupes) { throw "Port clash on $($g.Name): $($dupes.Name -join ', ')" }
}
foreach ($r in $rows) {
if ($r.SyslogTcpPort -notin $StandardSyslogPorts.tcp -or $r.SyslogUdpPort -notin $StandardSyslogPorts.udp) {
Write-Warning "$($r.CollectorName): non-standard syslog port. ESXi opens these automatically only from 8.0 U2b (and 7.0 P09); older hosts need a custom firewall rule."
}
}
#endregion
#region per-vCenter work ------------------------------------------------------
if (-not $SkipInventory) { Import-Module VMware.VimAutomation.Core -ErrorAction Stop }
$inventory = [System.Collections.Generic.List[object]]::new()
$fileSd = [System.Collections.Generic.List[object]]::new()
foreach ($r in $rows) {
$inv = [ordered]@{
VCenter = $r.VCenter; Site = $r.Site; Collector = $r.CollectorName; CollectorHost = $r.CollectorHost
VCenterVersion = ''; Hosts = ''; Esxi8Hosts = ''; Esxi7Hosts = ''; VMs = ''; Datastores = ''; NfsDatastores = ''
CollectionInterval = $r.CollectionInterval; SyslogTcpPort = $r.SyslogTcpPort; SyslogUdpPort = $r.SyslogUdpPort
}
$vi = $null
try {
if (-not $SkipInventory) {
$cred = Get-VCenterCredential -SecretName $r.CredentialSecret
$vi = Connect-VIServer -Server $r.VCenter -Credential $cred -NotDefault -ErrorAction Stop
$vmHosts = @(Get-VMHost -Server $vi)
$vmViews = @(Get-View -Server $vi -ViewType VirtualMachine -Property Name, Config.Template)
$ds = @(Get-Datastore -Server $vi)
$inv.VCenterVersion = "$($vi.Version) build $($vi.Build)"
$inv.Hosts = $vmHosts.Count
$inv.Esxi8Hosts = @($vmHosts | Where-Object { [version]$_.Version -ge [version]'8.0' }).Count
$inv.Esxi7Hosts = $inv.Hosts - $inv.Esxi8Hosts
$inv.VMs = @($vmViews | Where-Object { $_.Config -and -not $_.Config.Template }).Count
$inv.Datastores = $ds.Count
$inv.NfsDatastores = @($ds | Where-Object { $_.Type -in 'NFS', 'NFS41' }).Count
}
# A starting point only; see the sizing post before trusting it at scale.
if ([string]::IsNullOrWhiteSpace($r.CollectionInterval)) {
$inv.CollectionInterval = if ($inv.VMs -and [int]$inv.VMs -gt 2000) { '3m' } else { '2m' }
}
$caRemote = ''
$tlsBlock = switch ($r.TlsMode) {
'system' { '' }
'cafile' { " tls:`n ca_file: `${env:VCENTER_CA_FILE}`n"; $caRemote = "$RemoteConfigRoot/$($r.CollectorName)/vcenter-ca.pem" }
'skip' { " tls:`n insecure_skip_verify: true # lab only`n" }
}
$dir = Join-Path $OutputPath $r.CollectorName
$yaml = Expand-Template $CollectorTemplate @{
VCENTER = $r.VCenter; SITE = $r.Site; NAME = $r.CollectorName; INTERVAL = $inv.CollectionInterval
TLS_BLOCK = $tlsBlock.TrimEnd("`n"); TCP_PORT = $r.SyslogTcpPort; UDP_PORT = $r.SyslogUdpPort
HEALTH_PORT = $r.HealthPort; TELEMETRY_PORT = $r.TelemetryPort
PRW_URL = $MetricsRemoteWriteUrl; LOKI_URL = $LokiOtlpUrl
}
# An empty TLS block leaves a blank line; collapse it so reruns stay byte-identical.
$yaml = $yaml -replace "(?m)^\n(?= # ESXi 8)", ''
Write-GeneratedFile -Path (Join-Path $dir 'config.yaml') -Content $yaml
Write-GeneratedFile -Path (Join-Path $dir 'collector.env') -Content (Expand-Template $EnvTemplate @{
ROOT = $RemoteConfigRoot; NAME = $r.CollectorName; USER = $r.ServiceAccount; CA_PATH = $caRemote })
if ($r.TlsMode -eq 'cafile') {
Write-GeneratedFile -Path (Join-Path $dir 'vcenter-ca.pem') -Content (Get-Content -LiteralPath $r.CaFile -Raw)
}
$fileSd.Add([ordered]@{
targets = @("$($r.CollectorHost):$($r.TelemetryPort)")
labels = [ordered]@{ vcenter = $r.VCenter; site = $r.Site; collector = $r.CollectorName }
})
if ($ConfigureEsxiSyslog -and $vi) {
foreach ($h in $vmHosts) {
if ($h.ConnectionState -notin 'Connected', 'Maintenance') {
$script:Results.Add([pscustomobject]@{ Target = $h.Name; Action = 'Syslog'; Status = "Skipped ($($h.ConnectionState))" })
continue
}
$desired = Get-DesiredLogHost -Row $r -EsxiVersion ([version]$h.Version)
$setting = Get-AdvancedSetting -Entity $h -Name 'Syslog.global.logHost'
$current = @("$($setting.Value)".Split(',') | ForEach-Object Trim | Where-Object { $_ })
$keep = if ($ReplaceExistingLogHosts) { @() } else {
@($current | Where-Object { $_ -notmatch [regex]::Escape("://$($r.CollectorIp):") })
}
$newValue = (@($keep) + $desired) -join ','
$fw = Get-VMHostFirewallException -VMHost $h -Name 'syslog'
$status = 'Unchanged'
if ($newValue -ne ($current -join ',')) {
if ($PSCmdlet.ShouldProcess($h.Name, "Set Syslog.global.logHost = $newValue")) {
$setting | Set-AdvancedSetting -Value $newValue -Confirm:$false | Out-Null
$status = 'Updated'
} else { $status = 'WhatIf-Update' }
}
if (-not $fw.Enabled -and $PSCmdlet.ShouldProcess($h.Name, 'Enable syslog firewall ruleset')) {
$fw | Set-VMHostFirewallException -Enabled:$true -Confirm:$false | Out-Null
$status = "$status+Firewall"
}
if ($status -match 'Updated|Firewall' -and $PSCmdlet.ShouldProcess($h.Name, 'esxcli system syslog reload + mark')) {
$esxcli = Get-EsxCli -VMHost $h -V2
$esxcli.system.syslog.reload.Invoke() | Out-Null
$esxcli.system.syslog.mark.Invoke(@{ message = "otel-syslog-check collector=$($r.CollectorName)" }) | Out-Null
}
$script:Results.Add([pscustomobject]@{ Target = $h.Name; Action = 'Syslog'; Status = "$status ($desired)" })
}
}
} catch {
Write-Error "$($r.VCenter): $($_.Exception.Message)" -ErrorAction Continue
$script:Results.Add([pscustomobject]@{ Target = $r.VCenter; Action = 'vCenter'; Status = "Failed: $($_.Exception.Message)" })
} finally {
if ($vi) { Disconnect-VIServer -Server $vi -Confirm:$false -ErrorAction SilentlyContinue }
}
$inventory.Add([pscustomobject]$inv)
}
#endregion
#region shared outputs --------------------------------------------------------
Write-GeneratedFile -Path (Join-Path $OutputPath 'systemd/otelcol-contrib@.service') `
-Content (Expand-Template $UnitTemplate @{ ROOT = $RemoteConfigRoot })
Write-GeneratedFile -Path (Join-Path $OutputPath 'inventory/prometheus-file-sd.json') `
-Content (ConvertTo-Json -InputObject @($fileSd) -Depth 5)
Write-GeneratedFile -Path (Join-Path $OutputPath 'inventory/vcenter-inventory.csv') `
-Content (($inventory | ConvertTo-Csv -NoTypeInformation -UseQuotes AsNeeded) -join "`n")
if ($OtelcolPath) {
foreach ($r in $rows) {
$cfg = Join-Path (Join-Path $OutputPath $r.CollectorName) 'config.yaml'
if (-not (Test-Path -LiteralPath $cfg)) { continue } # -WhatIf run
$saved = @{ U = $env:VCENTER_USERNAME; P = $env:VCENTER_PASSWORD; C = $env:VCENTER_CA_FILE }
try {
# Dummy values: validate checks that they are non-empty, not that they are right.
$env:VCENTER_USERNAME = 'validate'; $env:VCENTER_PASSWORD = 'validate'
$env:VCENTER_CA_FILE = Join-Path (Join-Path $OutputPath $r.CollectorName) 'vcenter-ca.pem'
$out = & $OtelcolPath validate "--config=$cfg" 2>&1
$status = if ($LASTEXITCODE -eq 0) { 'Valid' } else { "Invalid: $($out | Select-Object -Last 1)" }
} finally {
$env:VCENTER_USERNAME = $saved.U; $env:VCENTER_PASSWORD = $saved.P; $env:VCENTER_CA_FILE = $saved.C
}
$script:Results.Add([pscustomobject]@{ Target = $cfg; Action = 'Validate'; Status = $status })
}
}
$script:Results
#endregion
A few implementation notes worth knowing before you change it:
$OutputPathis resolved to an absolute path at the start, because .NET file APIs resolve relative paths against the process working directory, not the PowerShell location. Skip that and-OutputPath ./outwrites somewhere surprising after aSet-Location.Connect-VIServer -NotDefaultkeeps each connection out of$global:DefaultVIServers, so a cmdlet without-Servercan never act on the wrong vCenter. Every inventory call passes-Server $viexplicitly, and thefinallyblock disconnects even after a failure.- The logHost merge removes only entries that point at this collector's IP and appends the desired one. Existing destinations, typically VCF Operations for logs (formerly Aria Operations for Logs) or a SIEM, survive.
-ReplaceExistingLogHostsis the explicit opt-in to drop them. - A host that is disconnected or not responding is skipped and reported, not retried. Rerun after it is back; the run is idempotent.
- VM count uses
Get-Viewwith onlyNameandConfig.Templaterequested, which is far lighter on a large vCenter thanGet-VM. - The collection interval heuristic (2m, or 3m above 2000 VMs) is a starting point, not sizing. It stays under Prometheus' default five-minute lookback, so instant queries never fall between two samples. Sizing properly is the subject of the sizing post.
06. What it generates
otel-generated/
├── vcenter01/
│ ├── config.yaml
│ ├── collector.env
│ └── vcenter-ca.pem # TlsMode = cafile only
├── vcenter02/
│ ├── config.yaml
│ └── collector.env
├── vcenter-lab/
│ ├── config.yaml
│ └── collector.env
├── systemd/
│ └── otelcol-contrib@.service
└── inventory/
├── prometheus-file-sd.json
└── vcenter-inventory.csv
Collector config for vcenter01
This is the unedited output for the first CSV row. The resource/vcenter processor runs in both pipelines, so metrics and logs from this vCenter carry the same service.namespace, vcenter.server and site. On the metrics side, resource_constant_labels promotes the vcenter.* resource attributes (host, VM, datastore, cluster names) to labels. Without it those attributes go only to target_info, and series from different VMs collapse into the same label set, which Mimir rejects as duplicates.
# Generated by New-OtelVCenterCollectorConfig.ps1. Do not edit by hand; edit the CSV and regenerate.
# vCenter: vcenter01.lab.local site: dc1 collector: vcenter01
extensions:
health_check:
endpoint: 0.0.0.0:13133
receivers:
vcenter:
endpoint: https://vcenter01.lab.local
username: ${env:VCENTER_USERNAME}
password: ${env:VCENTER_PASSWORD}
collection_interval: 2m
initial_delay: 10s
tls:
ca_file: ${env:VCENTER_CA_FILE}
# ESXi 8.x hosts: RFC 5424, TCP, octet counting
syslog/esxi_rfc5424:
tcp:
listen_address: 0.0.0.0:1514
protocol: rfc5424
enable_octet_counting: true
resource:
service.name: esxi
# ESXi 7.x hosts: RFC 3164, UDP
syslog/esxi_rfc3164:
udp:
listen_address: 0.0.0.0:514
protocol: rfc3164
location: UTC
resource:
service.name: esxi
processors:
memory_limiter:
check_interval: 1s
limit_percentage: 80
spike_limit_percentage: 20
resource/vcenter:
attributes:
- key: service.namespace
value: vcenter01
action: upsert
- key: vcenter.server
value: vcenter01.lab.local
action: upsert
- key: site
value: dc1
action: upsert
exporters:
prometheus_remote_write:
http:
endpoint: https://mimir.lab.local/api/v1/push
resource_constant_labels:
included: ["vcenter.*", "service.namespace", "site"]
otlp_http/loki:
endpoint: http://loki.lab.local:3100/otlp
sending_queue:
batch: {}
service:
extensions: [health_check]
telemetry:
metrics:
readers:
- pull:
exporter:
prometheus:
host: 0.0.0.0
port: 8888
pipelines:
metrics/vcenter:
receivers: [vcenter]
processors: [memory_limiter, resource/vcenter]
exporters: [prometheus_remote_write]
logs/esxi:
receivers: [syslog/esxi_rfc5424, syslog/esxi_rfc3164]
processors: [memory_limiter, resource/vcenter]
exporters: [otlp_http/loki]
For a row with TlsMode set to system the tls: block is omitted and the collector verifies against the OS trust store; with skip it becomes insecure_skip_verify: true with a comment saying lab only. Two notes on the processors: memory_limiter uses a percentage of the machine's memory, so if three instances share one VM, switch them to limit_mib with a third of the budget each. And there is no batch processor. The upstream collector has deprecated it in favour of exporter-level batching, which is the sending_queue: batch: {} on the Loki exporter.
Env file
# Generated. Contains no secrets. The password lives in /etc/otelcol-contrib/secrets/vcenter01.env (0600 root).
VCENTER_USERNAME=svc-otel-ro@vsphere.local
VCENTER_CA_FILE=/etc/otelcol-contrib/vcenter01/vcenter-ca.pem
systemd template unit
Based on the unit shipped in the official otelcol-contrib package, with three changes: %i selects the config folder, a second EnvironmentFile carries the secret, and ExecStartPre runs validate so a broken config fails the start cleanly instead of crash-looping under Restart=on-failure.
# Generated by New-OtelVCenterCollectorConfig.ps1
# One instance per vCenter: systemctl enable --now otelcol-contrib@<collector-name>
[Unit]
Description=OpenTelemetry Collector Contrib for %i
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=otelcol-contrib
Group=otelcol-contrib
EnvironmentFile=/etc/otelcol-contrib/%i/collector.env
EnvironmentFile=/etc/otelcol-contrib/secrets/%i.env
ExecStartPre=/usr/bin/otelcol-contrib validate --config=/etc/otelcol-contrib/%i/config.yaml
ExecStart=/usr/bin/otelcol-contrib --config=/etc/otelcol-contrib/%i/config.yaml
ExecReload=/bin/kill -HUP $MAINPID
KillMode=mixed
Restart=on-failure
RestartSec=10s
# Lets the non-root service bind UDP/TCP 514.
AmbientCapabilities=CAP_NET_BIND_SERVICE
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
NoNewPrivileges=true
LockPersonality=true
RestrictRealtime=true
RestrictSUIDSGID=true
ProtectControlGroups=true
ProtectKernelModules=true
ProtectKernelTunables=true
ProtectHostname=true
[Install]
WantedBy=multi-user.target
Prometheus targets and inventory
[
{
"targets": [
"otel01.lab.local:8888"
],
"labels": {
"vcenter": "vcenter01.lab.local",
"site": "dc1",
"collector": "vcenter01"
}
},
{
"targets": [
"otel02.lab.local:8888"
],
"labels": {
"vcenter": "vcenter02.lab.local",
"site": "dc2",
"collector": "vcenter02"
}
},
{
"targets": [
"otel01.lab.local:8889"
],
"labels": {
"vcenter": "vcenter-lab.lab.local",
"site": "lab",
"collector": "vcenter-lab"
}
}
]
Point a scrape job at the file. Prometheus reloads file_sd files on change, so a regenerated list is picked up without a restart.
# prometheus.yml
scrape_configs:
- job_name: otel-collectors
file_sd_configs:
- files: ['/etc/prometheus/file_sd/prometheus-file-sd.json']
refresh_interval: 5m
With those labels in place, otelcol_process_uptime, otelcol_receiver_accepted_metric_points and otelcol_exporter_send_failed_log_records arrive already tagged with vcenter and site, so one Grafana dashboard with a vcenter variable covers every collector. The internal telemetry docs note that the collector disables the Prometheus _total and unit suffixes on its own metrics by default, so those names are exact. The inventory CSV is a capacity snapshot; when run with inventory enabled it looks like this:
VCenter,Site,Collector,CollectorHost,VCenterVersion,Hosts,Esxi8Hosts,Esxi7Hosts,VMs,Datastores,NfsDatastores,CollectionInterval,SyslogTcpPort,SyslogUdpPort
vcenter01.lab.local,dc1,vcenter01,otel01.lab.local,8.0.3 build <BUILD>,24,24,0,1180,31,12,2m,1514,514
vcenter02.lab.local,dc2,vcenter02,otel02.lab.local,8.0.3 build <BUILD>,40,32,8,2650,48,20,3m,1514,514
vcenter-lab.lab.local,lab,vcenter-lab,otel01.lab.local,8.0.3 build <BUILD>,4,4,0,60,6,3,1m,1515,515
Commit it next to the CSV. A diff in that file between two runs is a change log for the estate: hosts added, a cluster still on ESXi 7, a new NFS datastore that needs to be on the storage dashboards.
07. Pointing ESXi at its collector
Step 5 is the only part that changes production, so it is opt-in, honours -WhatIf and -Confirm, and is idempotent per host. For each connected host (or host in maintenance mode) it does four things:
- Computes the desired destination from the host version:
tcp://<CollectorIp>:1514?formatter=RFC_5424&framing=octet_countingon 8.x,udp://<CollectorIp>:514on 7.x. - Reads
Syslog.global.logHost, which is a comma-separated list, drops any entry pointing at this collector's IP, appends the desired one, and callsSet-AdvancedSettingonly if the result differs. - Enables the
syslogfirewall exception if it is off. Broadcom notes the ruleset is still required on the standard ports even on builds that open custom ports dynamically. - If anything changed, runs
esxcli system syslog reloadthroughGet-EsxCli -V2and thenesxcli system syslog markwith the textotel-syslog-check collector=<name>, a marker you can search for in Loki to prove the path end to end.
Run it against one cluster first. The script has no cluster filter on purpose (fewer parameters, fewer surprises); copy the CSV, leave one row, and use -WhatIf to read exactly what it would set:
./New-OtelVCenterCollectorConfig.ps1 -InventoryCsv ./vcenter01-only.csv `
-MetricsRemoteWriteUrl 'https://<MIMIR_FQDN>/api/v1/push' `
-LokiOtlpUrl 'http://<LOKI_FQDN>:3100/otlp' `
-ConfigureEsxiSyslog -WhatIf
# What if: Performing the operation "Set Syslog.global.logHost = udp://10.0.99.9:514,tcp://10.0.10.51:1514?formatter=RFC_5424&framing=octet_counting" on target "esx01.lab.local".
Configuration profiles win. If a cluster is managed with vSphere Configuration Profiles, or hosts are remediated against a host profile, a logHost set directly on the host is drift and will be put back at the next remediation. In that case use the script with
-WhatIfto compute the value, then set it in the profile.
To check the result across a vCenter at any time, outside the script:
Get-VMHost -Server <VCENTER_FQDN> |
Select-Object Name, Version,
@{n='LogHost'; e={ (Get-AdvancedSetting -Entity $_ -Name Syslog.global.logHost).Value }},
@{n='Firewall'; e={ (Get-VMHostFirewallException -VMHost $_ -Name syslog).Enabled }} |
Format-Table -AutoSize
08. Validation before restart
The collector has a validate subcommand. In the core source (otelcol/command_validate.go) it is defined as “Validates the config without running the collector”: it builds the full collector from the config, resolves every ${env:...}, checks every component's settings, and exits non-zero on the first problem, without opening any port or connecting anywhere. That makes it safe to run on a build machine and again in ExecStartPre.
Two things make validation pass when it should not, or fail when it should not, so the script handles both. First, the vcenter receiver's own validation rejects an empty username or password. An unset environment variable expands to an empty string, so validating without the env loaded fails with “password not provided and is required”. The script sets dummy values for the duration of the check and restores the originals afterwards. Second, the receiver also loads its TLS config during validation, so a ca_file that does not exist fails. That is why ca_file is itself ${env:VCENTER_CA_FILE}: during local validation it points at the generated PEM, on the collector VM at /etc/otelcol-contrib/<name>/vcenter-ca.pem.
# On the build machine, with a matching otelcol-contrib binary
./New-OtelVCenterCollectorConfig.ps1 -InventoryCsv ./vcenters.csv `
-MetricsRemoteWriteUrl 'https://<MIMIR_FQDN>/api/v1/push' `
-LokiOtlpUrl 'http://<LOKI_FQDN>:3100/otlp' `
-SkipInventory -OtelcolPath /usr/local/bin/otelcol-contrib |
Where-Object Action -eq 'Validate'
# On the collector VM, against the real env files
sudo bash -c 'set -a; . /etc/otelcol-contrib/vcenter01/collector.env; . /etc/otelcol-contrib/secrets/vcenter01.env; set +a;
otelcol-contrib validate --config=/etc/otelcol-contrib/vcenter01/config.yaml && echo VALID'
Use the same collector version for validation that you run in production. A config that uses a component or key added in a later release is invalid on an older binary, and that is precisely the mismatch you want to catch before a rollout.
09. End-to-end workflow
From an empty automation host to a running collector for the first vCenter. Each step has a check and the output you should see before moving on.
| # | Step | Verify | Expected |
|---|---|---|---|
| 1 | Install PowerShell 7, VCF PowerCLI, SecretManagement and SecretStore (section 04) | Get-Module -ListAvailable VMware.VimAutomation.Core, Microsoft.PowerShell.SecretManagement | ft Name, Version | Both modules listed |
| 2 | Create the vault and one PSCredential per row | Get-SecretInfo -Vault OtelVault | Each CredentialSecret name, Type PSCredential |
| 3 | Create the read-only ServiceAccount in vCenter: Read Only role at the root, propagate to children | Connect-VIServer <VCENTER_FQDN> -Credential (Get-Credential) as that account, then (Get-VMHost).Count | Same host count as the vSphere Client |
| 4 | Fill vcenters.csv; export each vCenter root CA PEM if TlsMode is cafile | Import-Csv ./vcenters.csv | ft VCenter, CollectorName, CollectorIp, TlsMode | One line per vCenter, no blanks in required columns |
| 5 | Dry run | Run with -WhatIf | What if: Performing the operation "Created generated file" per file, nothing on disk |
| 6 | Generate for real | Run without -WhatIf | Results table, every file Created |
| 7 | Prove idempotency | Run the same command again | Every file Unchanged |
| 8 | Validate locally | Add -OtelcolPath | One Validate row per collector, Status Valid |
| 9 | Prepare the collector VM (script below) | systemctl cat otelcol-contrib@vcenter01 | The generated unit with %i expanded |
| 10 | Start the instance | systemctl is-active otelcol-contrib@vcenter01; curl -s localhost:13133 | active, then a JSON status of Server available |
| 11 | Confirm vCenter metrics flow | curl -s localhost:8888/metrics | grep accepted_metric_points | A non-zero counter with receiver="vcenter" after one collection interval |
| 12 | Push syslog to one cluster, then the rest | -ConfigureEsxiSyslog -WhatIf, then without | Syslog rows Updated, then Unchanged on rerun |
| 13 | Confirm logs end to end | In Grafana Explore on Loki: {service_name="esxi", service_namespace="vcenter01"} |= "otel-syslog-check" | One marker line per host |
| 14 | Wire Prometheus to the file_sd list | up{job="otel-collectors"} | 1 per collector, with vcenter and site labels |
Step 9 on the collector VM, as root. The official package creates the otelcol-contrib user and installs a default single-instance unit; disable that one so it does not fight the template for ports.
#!/usr/bin/env bash
# prepare-collector.sh <COLLECTOR_NAME> run as root on the collector VM
set -euo pipefail
NAME="$1"
SRC="./otel-generated" # copied here by scp, rsync or your CM tool
systemctl disable --now otelcol-contrib.service 2>/dev/null || true
install -d -m 0755 /etc/otelcol-contrib/"$NAME"
install -d -m 0700 -o root -g root /etc/otelcol-contrib/secrets
install -m 0644 "$SRC/$NAME/"* /etc/otelcol-contrib/"$NAME"/
install -m 0644 "$SRC/systemd/otelcol-contrib@.service" /etc/systemd/system/
if [ ! -s /etc/otelcol-contrib/secrets/"$NAME".env ]; then
umask 077
read -rsp "Password for the read-only vCenter account: " P; echo
# single quotes stop expansion; a password containing a single quote needs escaping
printf "VCENTER_PASSWORD='%s'\n" "$P" > /etc/otelcol-contrib/secrets/"$NAME".env
unset P
fi
systemctl daemon-reload
systemctl enable --now otelcol-contrib@"$NAME"
systemctl --no-pager status otelcol-contrib@"$NAME" | head -5
If the collector VM runs firewalld, open the ports for that instance as well (for the default row: firewall-cmd --permanent --add-port=1514/tcp --add-port=514/udp --add-port=8888/tcp and a reload). Keep 13133 local unless something outside needs the health endpoint.
After that, adding a vCenter is a CSV row, a generator run, one prepare-collector.sh call and a syslog push. Removing one is setting Enabled to false, stopping the instance and deleting its folder; the file_sd list drops the target on the next run.
10. Troubleshooting
| Symptom | Likely cause | Check | Fix |
|---|---|---|---|
validate: “password not provided and is required” | Env files not loaded in the shell that ran validate | env | grep VCENTER_ in the same shell | Source both env files (section 08), or rely on ExecStartPre, which gets them from systemd |
validate: “error loading tls configuration” | TlsMode=cafile but VCENTER_CA_FILE is empty or wrong | ls -l $VCENTER_CA_FILE | Copy vcenter-ca.pem into the instance folder; regenerate if the row changed mode |
unknown type: "prometheus_remote_write" | Collector older than the snake case rename | otelcol-contrib --version | Upgrade, or use prometheusremotewrite, otlphttp in the template |
Collector log: x509: certificate signed by unknown authority | TlsMode=system but the VMCA root is not in the OS trust store | openssl s_client -connect <VCENTER_FQDN>:443 -showcerts | Switch the row to cafile with the root CA from https://<VCENTER_FQDN>/certs/download.zip |
listen udp 0.0.0.0:514: bind: permission denied | Unit without CAP_NET_BIND_SERVICE, usually the stock unit | systemctl cat otelcol-contrib@<name> | grep Capab | Use the generated template unit |
bind: address already in use | rsyslog or another instance on the same port | ss -lntup | grep -E ':(514|1514)\b' | Stop the other listener, or offset the row and let the clash check confirm |
| Script: “No credential for secret” | SecretStore locked, or secret stored as a string | Get-SecretInfo -Vault OtelVault | Unlock-SecretStore; re-store with -Secret (Get-Credential) |
| logHost set but nothing reaches Loki | ESXi syslog ruleset off, non-standard port on an older build, or collector firewall | From the host: esxcli network firewall ruleset list --ruleset-id=syslog and nc -z <COLLECTOR_IP> 1514 | Enable the ruleset, use standard ports, open the collector firewall |
| ESXi 8 records split or failing to parse | RFC 5424 sent without octet counting, or to the UDP RFC 3164 port | esxcli system syslog config logger list and the logHost string | Use the exact ?formatter=RFC_5424&framing=octet_counting suffix to the TCP port |
| logHost reverts hours later | vSphere Configuration Profiles or host profile remediation | Profile compliance in the vSphere Client | Set the value in the profile, not on the host |
| Mimir rejects samples as duplicates | resource_constant_labels removed, so VM and host names never became labels | Compare target_info with a vcenter_vm_* series | Restore the included list in the template |
| Panels show gaps between points | Collection interval at or above the five-minute Prometheus lookback | CollectionInterval column | Keep it at 3m or below, or wrap panel queries in last_over_time(...[10m]) |
| Every run reports files as Updated | Someone edits generated files on disk, or the CSV row order or content changes each export | git diff otel-generated/ | Edit the CSV, not the output; keep the CSV in version control |
11. What’s next
The generator gives every vCenter a collector, a syslog path and an inventory row, which is the foundation for everything else in this batch. The next post uses exactly this syslog path to catch NFS All-Paths-Down from ESXi logs, and the NFS datastore counts in the inventory CSV tell you where to start. For the metrics side of the same datastores, see NFS datastore latency with OpenTelemetry; for how big each collector VM needs to be, sizing the collector for vSphere; and if you are deciding whether this replaces VCF Operations, VCF Operations vs OpenTelemetry and Grafana. The Grafana design choices behind the dashboards are in Wiring Grafana into vCenter.
Script tested offline with PowerShell 7 in -SkipInventory, -WhatIf and idempotent rerun modes, and the logHost merge logic unit-tested. All three generated configs pass otelcol-contrib validate on otelcol-contrib 0.166.0, and component names, config keys and stability levels were checked against that release. Run -WhatIf against a lab vCenter before your first real syslog push.
Leave a Reply