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

  1. What the generator does, and what it refuses to do
  2. Design decisions
  3. The CSV contract
  4. Credentials without plaintext
  5. The complete script
  6. What it generates
  7. Pointing ESXi at its collector
  8. Validation before restart
  9. End-to-end workflow
  10. Troubleshooting
  11. 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.

INPUTS GENERATOR GENERATED FILES (./otel-generated) vcenters.csv one row per vCenter Secret vault SecretManagement or OTELGEN_VC_* env Switches -WhatIf -SkipInventory -ConfigureEsxiSyslog New-OtelVCenterCollectorConfig.ps1 1 Validate CSV, port clashes 2 Connect-VIServer, inventory 3 Render templates per vCenter 4 Write a file only if changed 5 Push ESXi syslog (optional) 6 otelcol-contrib validate <name>/config.yaml receivers, processors, exporters <name>/collector.env username and CA path, never the password <name>/vcenter-ca.pem only when TlsMode is cafile systemd/otelcol-contrib@.service one template unit, one instance per vCenter inventory/prometheus-file-sd.json self-telemetry scrape targets with labels inventory/vcenter-inventory.csv hosts, VMs, NFS datastores per vCenter read-only inventory Syslog.global.logHost deploy (scp, Ansible) vCenter Servers Get-VMHost, Get-Datastore Get-View VirtualMachine admin credential, script only ESXi hosts 8.x: tcp 1514, RFC 5424 7.x: udp 514, RFC 3164 syslog firewall ruleset enabled Collector VMs otelcol-contrib@vcenter01, @vcenter02, … password from /etc/otelcol-contrib/secrets validate runs again in ExecStartPre
Figure 1. Generator workflow: the CSV and a secret vault go in, per-vCenter collector files come out, and the optional step 5 writes one advanced setting per ESXi host.
StepWhat happensTouches production?
1. ValidateRequired columns, TlsMode values, collector names, and every TCP and UDP port on a shared collector host checked for clashesNo
2. InventoryConnect-VIServer per vCenter, then host count split by ESXi major version, VM count without templates, datastore and NFS datastore countsRead only
3. RenderSingle-quoted templates with {{TOKENS}}, one collector config, env file and optional CA file per vCenterNo
4. Write if changedByte comparison against the file on disk; untouched files stay untouched so config management and git diff stay quietNo
5. ESXi syslogOnly with -ConfigureEsxiSyslog: sets Syslog.global.logHost, enables the syslog firewall ruleset, reloads vmsyslogd, writes a marker messageYes, honours -WhatIf and -Confirm
6. ValidateOnly with -OtelcolPath: runs otelcol-contrib validate against every generated configNo

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.namespace and vcenter.server on 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.
SITE dc1 vcenter01 /sdk on 443 ESXi hosts 8.x and 7.x otelcol-contrib@vcenter01 vcenter receiver (pull) syslog tcp 1514 / udp 514 self-metrics on 8888 HTTPS syslog SITE dc2 vcenter02 /sdk on 443 ESXi hosts 8.x only otelcol-contrib@vcenter02 vcenter receiver (pull) syslog tcp 1514 / udp 514 self-metrics on 8888 HTTPS syslog SITE lab vcenter-lab /sdk on 443 ESXi hosts 8.0 U2b or later otelcol-contrib@vcenter-lab shares VM otel01, own ports syslog tcp 1515 / udp 515 self-metrics on 8889 HTTPS syslog metrics: remote write · logs: OTLP/HTTP scrape 8888 (file_sd) Prometheus / Mimir vcenter_* and otelcol_* series Loki service_name=”esxi” Grafana dashboards keyed on vcenter label queries
Figure 2. Per-vCenter collector topology. Each collector pulls its own vCenter and receives syslog from that vCenter's hosts. Backends are shared. The lab collector shares a VM with vcenter01 on offset ports.

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 syslog firewall 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-contrib user needs CAP_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.

ColumnRequiredDefaultMeaning
VCenterYesFQDN used for Connect-VIServer and the receiver endpoint
SiteYesFree text, becomes the site label
CollectorNameYesLowercase DNS label; systemd instance name and output folder
CollectorHostYesCollector VM FQDN, used for scrape targets and port clash checks
CollectorIpYesAddress ESXi sends syslog to
SyslogTcpPortNo1514RFC 5424 listener for ESXi 8
SyslogUdpPortNo514RFC 3164 listener for ESXi 7
TelemetryPortNo8888Collector self-metrics, scraped by Prometheus
HealthPortNo13133health_check extension
CollectionIntervalNo2m, or 3m above 2000 VMsvcenter receiver interval
ServiceAccountYesRead-only account the collector uses
CredentialSecretYesVault secret name for the account the script uses
TlsModeYessystem (OS trust store), cafile (ship a PEM), skip (lab only)
CaFileIf cafileLocal path to the vCenter root CA PEM
EnabledNotruefalse 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. ServiceAccount is 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. CredentialSecret names 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:

  • $OutputPath is 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 ./out writes somewhere surprising after a Set-Location.
  • Connect-VIServer -NotDefault keeps each connection out of $global:DefaultVIServers, so a cmdlet without -Server can never act on the wrong vCenter. Every inventory call passes -Server $vi explicitly, and the finally block 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. -ReplaceExistingLogHosts is 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-View with only Name and Config.Template requested, which is far lighter on a large vCenter than Get-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:

  1. Computes the desired destination from the host version: tcp://<CollectorIp>:1514?formatter=RFC_5424&framing=octet_counting on 8.x, udp://<CollectorIp>:514 on 7.x.
  2. Reads Syslog.global.logHost, which is a comma-separated list, drops any entry pointing at this collector's IP, appends the desired one, and calls Set-AdvancedSetting only if the result differs.
  3. Enables the syslog firewall exception if it is off. Broadcom notes the ruleset is still required on the standard ports even on builds that open custom ports dynamically.
  4. If anything changed, runs esxcli system syslog reload through Get-EsxCli -V2 and then esxcli system syslog mark with the text otel-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 -WhatIf to 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.

#StepVerifyExpected
1Install PowerShell 7, VCF PowerCLI, SecretManagement and SecretStore (section 04)Get-Module -ListAvailable VMware.VimAutomation.Core, Microsoft.PowerShell.SecretManagement | ft Name, VersionBoth modules listed
2Create the vault and one PSCredential per rowGet-SecretInfo -Vault OtelVaultEach CredentialSecret name, Type PSCredential
3Create the read-only ServiceAccount in vCenter: Read Only role at the root, propagate to childrenConnect-VIServer <VCENTER_FQDN> -Credential (Get-Credential) as that account, then (Get-VMHost).CountSame host count as the vSphere Client
4Fill vcenters.csv; export each vCenter root CA PEM if TlsMode is cafileImport-Csv ./vcenters.csv | ft VCenter, CollectorName, CollectorIp, TlsModeOne line per vCenter, no blanks in required columns
5Dry runRun with -WhatIfWhat if: Performing the operation "Created generated file" per file, nothing on disk
6Generate for realRun without -WhatIfResults table, every file Created
7Prove idempotencyRun the same command againEvery file Unchanged
8Validate locallyAdd -OtelcolPathOne Validate row per collector, Status Valid
9Prepare the collector VM (script below)systemctl cat otelcol-contrib@vcenter01The generated unit with %i expanded
10Start the instancesystemctl is-active otelcol-contrib@vcenter01; curl -s localhost:13133active, then a JSON status of Server available
11Confirm vCenter metrics flowcurl -s localhost:8888/metrics | grep accepted_metric_pointsA non-zero counter with receiver="vcenter" after one collection interval
12Push syslog to one cluster, then the rest-ConfigureEsxiSyslog -WhatIf, then withoutSyslog rows Updated, then Unchanged on rerun
13Confirm logs end to endIn Grafana Explore on Loki: {service_name="esxi", service_namespace="vcenter01"} |= "otel-syslog-check"One marker line per host
14Wire Prometheus to the file_sd listup{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

SymptomLikely causeCheckFix
validate: “password not provided and is required”Env files not loaded in the shell that ran validateenv | grep VCENTER_ in the same shellSource 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 wrongls -l $VCENTER_CA_FILECopy vcenter-ca.pem into the instance folder; regenerate if the row changed mode
unknown type: "prometheus_remote_write"Collector older than the snake case renameotelcol-contrib --versionUpgrade, or use prometheusremotewrite, otlphttp in the template
Collector log: x509: certificate signed by unknown authorityTlsMode=system but the VMCA root is not in the OS trust storeopenssl s_client -connect <VCENTER_FQDN>:443 -showcertsSwitch the row to cafile with the root CA from https://<VCENTER_FQDN>/certs/download.zip
listen udp 0.0.0.0:514: bind: permission deniedUnit without CAP_NET_BIND_SERVICE, usually the stock unitsystemctl cat otelcol-contrib@<name> | grep CapabUse the generated template unit
bind: address already in usersyslog or another instance on the same portss -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 stringGet-SecretInfo -Vault OtelVaultUnlock-SecretStore; re-store with -Secret (Get-Credential)
logHost set but nothing reaches LokiESXi syslog ruleset off, non-standard port on an older build, or collector firewallFrom the host: esxcli network firewall ruleset list --ruleset-id=syslog and nc -z <COLLECTOR_IP> 1514Enable the ruleset, use standard ports, open the collector firewall
ESXi 8 records split or failing to parseRFC 5424 sent without octet counting, or to the UDP RFC 3164 portesxcli system syslog config logger list and the logHost stringUse the exact ?formatter=RFC_5424&framing=octet_counting suffix to the TCP port
logHost reverts hours latervSphere Configuration Profiles or host profile remediationProfile compliance in the vSphere ClientSet the value in the profile, not on the host
Mimir rejects samples as duplicatesresource_constant_labels removed, so VM and host names never became labelsCompare target_info with a vcenter_vm_* seriesRestore the included list in the template
Panels show gaps between pointsCollection interval at or above the five-minute Prometheus lookbackCollectionInterval columnKeep it at 3m or below, or wrap panel queries in last_over_time(...[10m])
Every run reports files as UpdatedSomeone edits generated files on disk, or the CSV row order or content changes each exportgit 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