<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>TechColumnist</title>
    <link>https://www.techcolumnist.com/</link>
    <description>Directives from a Director</description>
    <language>en-us</language>
    <lastBuildDate>Sat, 19 Sep 2026 16:11:56 GMT</lastBuildDate>
    <atom:link href="https://www.techcolumnist.com/feed.xml" rel="self" type="application/rss+xml" />
    <image>
      <url>https://www.techcolumnist.com/og-default.png</url>
      <title>TechColumnist</title>
      <link>https://www.techcolumnist.com/</link>
    </image>
    <item>
      <title>Hyper-V to Talos: Rethinking the Virtualization Stack</title>
      <link>https://www.techcolumnist.com/2026/09/16/hyper-v-to-talos-rethinking-the-virtualization-stack/</link>
      <guid isPermaLink="true">https://www.techcolumnist.com/2026/09/16/hyper-v-to-talos-rethinking-the-virtualization-stack/</guid>
      <pubDate>Wed, 16 Sep 2026 14:00:00 GMT</pubDate>
      <dc:creator>Tom Lasswell</dc:creator>
      <description>Why moving workloads off Hyper-V VMs onto a Talos Kubernetes cluster changed the whole stack, with an inventory script and a VM-to-manifest example.</description>
      <content:encoded><![CDATA[<p>Moving a fleet of Hyper-V virtual machines onto a Talos Kubernetes cluster sounds, on paper, like a hypervisor swap: fewer VMs, more containers, same general shape of infrastructure. In practice it changed how I think about the whole stack, because the unit of work stopped being &quot;a machine running an OS running an application&quot; and became &quot;an application, full stop,&quot; with everything underneath it treated as disposable. That&apos;s a bigger shift than it sounds, and it took longer to internalize than the migration itself.</p>
<p>This is the strategic half of a pair. <a href="https://www.techcolumnist.com/2026/07/08/kubernetes-running-talos-alongside-a-legacy-hyper-v-estate/">Kubernetes: Running Talos Alongside a Legacy Hyper-V Estate</a> covers the mechanics of running Talos nodes as Hyper-V guests; this post is about deciding what moves and what doesn&apos;t.</p>
<h2>The VM was never really the point</h2>
<p>A Hyper-V VM running a line-of-business application carries a lot of incidental complexity that has nothing to do with the application: a Windows Server license, a patch cadence, a local firewall configuration, a backup agent, sometimes local storage that needs its own maintenance window. None of that serves the application; it serves the fact that the application happens to live inside a general-purpose operating system. Once workloads moved to containers on Talos, most of that incidental surface stopped existing. There&apos;s no OS to patch inside the workload, because the container image carries only the application and its libraries, and the only operating system underneath is Talos: immutable, managed through an API, upgraded as a cluster-wide rolling operation rather than VM by VM.</p>
<p>That doesn&apos;t mean every VM is a container waiting to happen, and the first practical step was finding out which ones were. I ran an inventory across the hosts that turned the VM list into a migration conversation. It records what each VM consumes and flags the properties that change the answer: likely Windows guests, several disks, large memory footprints, existing checkpoints. It doesn&apos;t produce a verdict, because the verdict needs someone who knows the application.</p>
<pre><code class="language-powershell">#Requires -Modules Hyper-V
&lt;#
.SYNOPSIS
    Inventories Hyper-V VMs across hosts and flags what each one would need to become a container workload.

.DESCRIPTION
    Collects, per VM: host, state, generation, vCPU, memory, disk count and size,
    checkpoints, IP addresses and the VM&apos;s Notes field. It then adds flags that
    drive the migration conversation, not a verdict: likely Windows guests
    (Talos nodes are Linux, and Windows containers need Windows worker nodes),
    several disks (state that needs a PersistentVolume design), large memory
    footprints, and existing checkpoints. Output goes to the pipeline and,
    optionally, a CSV.

.PARAMETER ComputerName
    Hyper-V hosts to query. Defaults to the local host.

.PARAMETER CsvPath
    Optional path for a CSV export.

.PARAMETER LargeMemoryGB
    Startup memory at or above which a VM is flagged as large (default 16).

.PARAMETER WindowsPattern
    Regular expression matched against the VM name and Notes to flag Windows
    guests. Adjust it to your naming convention (default &apos;^(win|ws|srv)|windows&apos;).

.EXAMPLE
    .\Get-HyperVMigrationInventory.ps1 -ComputerName HV01, HV02, HV03 -CsvPath .\hyperv-inventory.csv

.EXAMPLE
    .\Get-HyperVMigrationInventory.ps1 -ComputerName HV01 | Where-Object -FilterScript { $_.Flags -eq &apos;&apos; } | Format-Table -Property Name, Host, MemoryGB, DiskGB
#&gt;
[CmdletBinding()]
param(
    [string[]] $ComputerName = @($env:COMPUTERNAME),
    [string] $CsvPath,
    [int] $LargeMemoryGB = 16,
    [string] $WindowsPattern = &apos;^(win|ws|srv)|windows&apos;
)

$ErrorActionPreference = &apos;Stop&apos;

$results = foreach ($hostName in $ComputerName) {
    foreach ($vm in (Get-VM -ComputerName $hostName)) {
        $drives = @(Get-VMHardDiskDrive -VM $vm)
        $diskBytes = 0
        foreach ($drive in $drives) {
            if ($drive.Path) {
                $diskBytes += (Get-VHD -Path $drive.Path -ComputerName $hostName).FileSize
            }
        }

        $adapters = @(Get-VMNetworkAdapter -VM $vm)
        $addresses = @($adapters.IPAddresses | Where-Object -FilterScript { $_ -match &apos;^\d{1,3}(\.\d{1,3}){3}$&apos; })
        $checkpoints = @(Get-VMSnapshot -VM $vm)
        $memoryGB = [math]::Round($vm.MemoryStartup / 1GB, 1)

        $flags = [System.Collections.Generic.List[string]]::new()
        if ($vm.Name -match $WindowsPattern -or $vm.Notes -match $WindowsPattern) {
            $flags.Add(&apos;windows-guest&apos;)
        }
        if ($drives.Count -gt 1) {
            $flags.Add(&apos;multiple-disks&apos;)
        }
        if ($memoryGB -ge $LargeMemoryGB) {
            $flags.Add(&apos;large-memory&apos;)
        }
        if ($checkpoints.Count -gt 0) {
            $flags.Add(&apos;has-checkpoints&apos;)
        }

        [pscustomobject]@{
            Name         = $vm.Name
            Host         = $hostName
            State        = $vm.State
            Generation   = $vm.Generation
            vCPU         = $vm.ProcessorCount
            MemoryGB     = $memoryGB
            DynamicMem   = $vm.DynamicMemoryEnabled
            Disks        = $drives.Count
            DiskGB       = [math]::Round($diskBytes / 1GB, 1)
            Checkpoints  = $checkpoints.Count
            IPv4         = $addresses -join &apos;;&apos;
            Switch       = ($adapters.SwitchName | Select-Object -Unique) -join &apos;;&apos;
            Flags        = $flags -join &apos;;&apos;
            Notes        = $vm.Notes
        }
    }
}

if ($CsvPath) {
    $results | Export-Csv -Path $CsvPath -NoTypeInformation -Encoding utf8
}

$results
</code></pre>
<pre><code class="language-text">Name        : app-reports01
Host        : HV02
State       : Running
Generation  : 2
vCPU        : 2
MemoryGB    : 4
DynamicMem  : True
Disks       : 1
DiskGB      : 38.2
Checkpoints : 0
IPv4        : 10.20.12.44
Switch      : vSwitch-Trunk
Flags       :
Notes       : Reporting web front end (Linux, nginx + Python)
</code></pre>
<p>An empty <code>Flags</code> column is the short list: a small Linux VM with one disk is usually a service whose state already lives in a database somewhere else. The IP column depends on Hyper-V integration services reporting guest addresses, so an empty value there usually means the guest isn&apos;t reporting through KVP rather than that it has no address.</p>
<p>The flag that ends the conversation fastest is <code>windows-guest</code>. Talos nodes are Linux, and Kubernetes runs Windows containers only on Windows worker nodes. The control plane is Linux-only, and Windows nodes join an existing Linux cluster. Talos doesn&apos;t provide Windows nodes, so a Windows service that can&apos;t be rebuilt for Linux stays a VM, and saying so early saves months of false hope.</p>
<h2>Talos removes the operational tax that made Hyper-V feel heavy</h2>
<p>The comparison that convinced skeptical stakeholders wasn&apos;t a performance benchmark, it was an operational one. A Hyper-V host needs Windows Update planning, cluster-aware updating coordination, and antivirus exclusions tuned correctly. A Talos node has none of that: no shell to secure, no package manager to patch, configuration applied through an API instead of accumulated through years of interactive changes. Upgrades use an A-B image scheme with automatic fallback if the new version doesn&apos;t boot, and Talos refuses to upgrade a control plane node when doing so would cost etcd quorum. The platform layer went from something that needed a dedicated maintenance calendar to something that mostly gets out of the way, and that freed up real time that used to go into hypervisor and guest OS care and feeding.</p>
<h2>What a VM becomes</h2>
<p>The unit of translation is worth making concrete, because &quot;containerize it&quot; hides most of the work. Take the reporting front end from the inventory: on Hyper-V it was a VM with the application under <code>/opt/reports</code>, its settings in a file on the local disk, generated exports written to a second folder, a local firewall rule for port 8080, and a backup agent. On the cluster it&apos;s this:</p>
<pre><code class="language-yaml">apiVersion: v1
kind: Namespace
metadata:
  name: reports
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: reports-config
  namespace: reports
data:
  settings.toml: |
    [database]
    host = &quot;sql-reports.example.internal&quot;
    port = 5432
    [exports]
    path = &quot;/var/lib/reports/exports&quot;
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: reports-exports
  namespace: reports
spec:
  accessModes:
    - ReadWriteOnce
  storageClassName: replicated-block
  resources:
    requests:
      storage: 20Gi
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: reports
  namespace: reports
spec:
  replicas: 1
  strategy:
    type: Recreate
  selector:
    matchLabels:
      app: reports
  template:
    metadata:
      labels:
        app: reports
    spec:
      containers:
        - name: reports
          image: registry.example.com/reports/web:3.2.0
          ports:
            - containerPort: 8080
          readinessProbe:
            httpGet:
              path: /healthz
              port: 8080
          resources:
            requests:
              cpu: 250m
              memory: 512Mi
            limits:
              memory: 1Gi
          volumeMounts:
            - name: config
              mountPath: /etc/reports
              readOnly: true
            - name: exports
              mountPath: /var/lib/reports/exports
      volumes:
        - name: config
          configMap:
            name: reports-config
        - name: exports
          persistentVolumeClaim:
            claimName: reports-exports
---
apiVersion: v1
kind: Service
metadata:
  name: reports
  namespace: reports
spec:
  selector:
    app: reports
  ports:
    - port: 80
      targetPort: 8080
</code></pre>
<p>Every line of that replaces something that used to be implicit in the VM. The settings file is a ConfigMap under version control instead of a file someone edited over RDP. The exports folder is a PersistentVolumeClaim against a CSI storage class, so it survives the pod moving to another node. The port the firewall rule opened is exposed by a Service (a NetworkPolicy takes over the allow/deny half, and an Ingress or Gateway route the outside access). The patch cadence is a new image tag. And the honest part: a <code>ReadWriteOnce</code> volume attaches to one node at a time, so this Deployment deliberately runs one replica with the <code>Recreate</code> strategy (a rolling update would start the new pod before the old one releases the volume), so a node drain still means a short outage for this app. Getting to more than one replica would mean moving the exports to object storage or a shared filesystem, which is application work, not platform work. The manifest makes that trade-off visible, where the VM hid it.</p>
<h2>What actually got harder</h2>
<p>None of this was free. Applications that assumed a persistent, stateful VM (a specific file written to a specific local path, a Windows service with baked-in configuration, licensing tied to a machine identity) needed real rework to run well as containers, and a few didn&apos;t make the trip at all. They stayed on a smaller, deliberately retained Hyper-V footprint, which is a legitimate outcome rather than a failure. <a href="https://www.techcolumnist.com/2026/06/10/hyper-v-migrating-vms-off-an-aging-cluster-without-downtime/">Hyper-V: Migrating VMs Off an Aging Cluster Without Downtime</a> covers keeping that footprint healthy.</p>
<p>Storage was the sharpest edge. A VM&apos;s virtual disk is a familiar, forgiving abstraction. Kubernetes persistent storage (we settled on a CSI-backed distributed storage layer) demands more upfront design about replication, failure domains and backup than most teams have previously had to think about for a &quot;just give it a disk&quot; VM workload. Talos&apos; storage guide is refreshingly blunt about it: most people shouldn&apos;t use mount-many (<code>ReadWriteMany</code>) semantics at all, NFS is pervasive &quot;because it is old and easy, not because it is a good idea,&quot; and Ceph can be slow and resource-hungry on small clusters. Backup changes shape too. There&apos;s no VM to snapshot; what needs protecting is the cluster&apos;s secrets bundle and machine config patches, regular etcd snapshots (<code>talosctl etcd snapshot</code>), and the application data in those persistent volumes.</p>
<h2>The strategic case outlasts the technical one</h2>
<p>The technical reasons to make this move are solid, but the argument that held up in front of leadership was different. A fleet of general-purpose VMs is a fleet of general-purpose maintenance obligations that grow with every VM: each new application on Hyper-V was a new VM with its own OS, patch cycle, agents and backup job. Each new application on the Talos cluster is a new set of manifests on infrastructure that is already being maintained anyway. The platform&apos;s own upkeep grows with the number of nodes, not the number of applications. That&apos;s the version of &quot;rethinking the stack&quot; that actually changes a budget conversation, not just an architecture diagram.</p>
<h2>References</h2>
<ul><li><a href="https://docs.siderolabs.com/talos/v1.14/learn-more/philosophy">Talos Philosophy</a> and <a href="https://docs.siderolabs.com/talos/v1.14/configure-your-talos-cluster/lifecycle-management/upgrading-talos">Upgrading Talos Linux</a></li>
<li><a href="https://docs.siderolabs.com/talos/v1.14/platform-specific-installations/virtualized-platforms/hyper-v">Hyper-V (Talos platform guide)</a></li>
<li><a href="https://docs.siderolabs.com/kubernetes-guides/csi/storage">Storage on Talos</a></li>
<li><a href="https://docs.siderolabs.com/talos/v1.14/build-and-extend-talos/cluster-operations-and-maintenance/disaster-recovery">Disaster Recovery</a></li>
<li><a href="https://kubernetes.io/docs/concepts/windows/intro/">Windows containers in Kubernetes</a></li>
<li><a href="https://kubernetes.io/docs/concepts/configuration/configmap/">Kubernetes: ConfigMaps</a>, <a href="https://kubernetes.io/docs/concepts/storage/persistent-volumes/">Persistent Volumes</a> and <a href="https://kubernetes.io/docs/concepts/workloads/controllers/deployment/">Deployments</a></li>
<li>Microsoft Hyper-V module: <a href="https://learn.microsoft.com/en-us/powershell/module/hyper-v/get-vm">Get-VM</a>, <a href="https://learn.microsoft.com/en-us/powershell/module/hyper-v/get-vmharddiskdrive">Get-VMHardDiskDrive</a>, <a href="https://learn.microsoft.com/en-us/powershell/module/hyper-v/get-vhd">Get-VHD</a>, <a href="https://learn.microsoft.com/en-us/powershell/module/hyper-v/get-vmnetworkadapter">Get-VMNetworkAdapter</a>, <a href="https://learn.microsoft.com/en-us/powershell/module/hyper-v/get-vmsnapshot">Get-VMSnapshot</a></li>
</ul>
]]></content:encoded>
      <category>Engineering</category>
      <category>Strategy</category>
    </item>
    <item>
      <title>Google Cloud: IAM Least Privilege in Practice, Not Just in Theory</title>
      <link>https://www.techcolumnist.com/2026/09/09/google-cloud-iam-least-privilege-in-practice-not-just-in-theory/</link>
      <guid isPermaLink="true">https://www.techcolumnist.com/2026/09/09/google-cloud-iam-least-privilege-in-practice-not-just-in-theory/</guid>
      <pubDate>Wed, 09 Sep 2026 14:00:00 GMT</pubDate>
      <dc:creator>Tom Lasswell</dc:creator>
      <description>Running least privilege in a real Google Cloud org: finding basic roles, working the IAM recommender, custom roles, temporary access, and service account risk.</description>
      <content:encoded><![CDATA[<p>Least privilege is easy to agree with and hard to actually run. Every engineer nods along with the principle right up until their own access gets tightened and something they used to do without thinking now throws a permission error. Getting a Google Cloud organization to genuinely operate on least privilege, not just have it written into a policy document, has been less about picking the right roles and more about building the process that keeps them right after the initial cleanup. This is that process, with the commands and scripts behind each step.</p>
<h2>Where least privilege breaks down in practice</h2>
<p>The gap almost never shows up at the design stage. It shows up months later, after the original access grants have drifted from whatever was documented, because someone needed a permission urgently, got a broad role to unblock them, and nobody came back to narrow it. Least privilege isn&apos;t a state you reach once. It&apos;s a maintenance discipline, and the organizations that struggle with it are the ones treating an access review as a one-time project instead of a recurring one.</p>
<p>The first recurring question is always the same: where are the basic roles? Google&apos;s own guidance is that basic roles &quot;include thousands of permissions across all Google Cloud services,&quot; and that in production you shouldn&apos;t grant them unless there&apos;s no alternative. Cloud Asset Inventory answers it for the whole organization in one call (you need <code>roles/cloudasset.viewer</code> on the organization):</p>
<pre><code class="language-bash">gcloud asset search-all-iam-policies \
  --scope=organizations/123456789012 \
  --query=&apos;roles:roles/owner OR roles:roles/editor&apos; \
  --flatten=&apos;policy.bindings[].members[]&apos; \
  --format=&apos;table(resource.basename(),policy.bindings.role,policy.bindings.members)&apos;
</code></pre>
<p>That search returns bindings attached directly to each resource. It doesn&apos;t return access inherited from a folder or the organization. For a full CSV with flags for public, external, and deleted principals, I use the <a href="https://www.techcolumnist.com/2026/01/14/python-gcloud-audit-iam-bindings-across-a-gcp-organization/">organization-wide IAM audit script</a>. For &quot;who can actually do this one dangerous thing here,&quot; inheritance and group membership included, Policy Analyzer is the right tool:</p>
<pre><code class="language-bash">gcloud asset analyze-iam-policy \
  --organization=123456789012 \
  --full-resource-name=//cloudresourcemanager.googleapis.com/projects/payments-prod \
  --permissions=&apos;resourcemanager.projects.setIamPolicy&apos; \
  --expand-groups
</code></pre>
<p>Budget for that one: more than 20 Policy Analyzer queries per organization per day needs the Premium or Enterprise tier of Security Command Center.</p>
<h2>Predefined roles are a starting point, not a destination</h2>
<p>Predefined roles are a huge improvement over granting Editor or Owner out of convenience, but most of them are still built for a category of user, not a specific job. A role like <code>roles/compute.admin</code> grants far more than most engineers assigned to it use day to day.</p>
<p>Custom roles solve the precision problem but introduce a maintenance one. Google maintains predefined roles and adds permissions to them as services grow. It doesn&apos;t touch your custom roles, so a custom role nobody has updated in two years is quietly falling behind what the underlying service can do. Some permissions also can&apos;t go into custom roles at all, and others are only at <code>TESTING</code> support level. Check before you build one:</p>
<pre><code class="language-bash">gcloud iam list-testable-permissions \
  //cloudresourcemanager.googleapis.com/projects/payments-prod \
  --filter=&apos;customRolesSupportLevel!=NOT_SUPPORTED AND name:compute.instances.&apos;
</code></pre>
<p>When a custom role is worth it, keep it as a file in version control with a named owner, so the review has something to diff:</p>
<pre><code class="language-yaml"># roles/vm-operator.yaml
title: VM Operator
description: Start, stop, reset and view VMs. Owner platform-team@example.com.
stage: GA
includedPermissions:
- compute.instances.get
- compute.instances.list
- compute.instances.reset
- compute.instances.start
- compute.instances.stop
- compute.zoneOperations.get
</code></pre>
<pre><code class="language-bash">gcloud iam roles create vmOperator --organization=123456789012 --file=roles/vm-operator.yaml
# later changes
gcloud iam roles update vmOperator --organization=123456789012 --file=roles/vm-operator.yaml
</code></pre>
<p>The middle ground we&apos;ve landed on: predefined roles at the project or folder level for anything broad and low-risk, and custom roles reserved for the handful of high-privilege paths worth the ongoing upkeep. (The hard limit is 3,000 permissions per custom role; if you&apos;re anywhere near it, a predefined role was probably the better answer.)</p>
<h2>The IAM recommender is only as good as its lookback window</h2>
<p>The IAM recommender (<code>google.iam.policy.Recommender</code>) is the fastest way to find over-provisioned bindings. It compares what a principal was granted with what it used over up to 90 days (or since the grant, if that&apos;s more recent), and it proposes one of two things: <code>REMOVE_ROLE</code>, or <code>REPLACE_ROLE</code> with something less permissive. There&apos;s also <code>REPLACE_ROLE_CUSTOMIZABLE</code>, a suggested custom role. It also uses an ML model to keep permissions a principal is likely to need even if it hasn&apos;t used them yet. Recommendations for basic roles are free at the project, folder, and organization level. Recommendations for other predefined roles and custom-role suggestions need Security Command Center Premium or Enterprise. It also doesn&apos;t produce insights for conditional bindings.</p>
<p>What it can&apos;t tell you is whether an unused permission is unused because it&apos;s unnecessary, or because the one task that needs it only runs quarterly and didn&apos;t fall inside the window. Accepting every recommendation blind is how you find out, at the worst possible time, that someone&apos;s quarter-end batch job needed a permission the recommender flagged as safe to remove. We treat recommendations as a prioritized list to investigate, not a queue to auto-apply.</p>
<p>This script builds that list across every project the caller can see, together with the related list of service accounts that haven&apos;t authenticated in 90 days. It needs <code>roles/recommender.iamViewer</code> and <code>roles/iam.roleViewer</code> wherever it runs (granting them at the organization covers every project), plus the Recommender API (<code>recommender.googleapis.com</code>) enabled.</p>
<pre><code class="language-bash">#!/usr/bin/env bash
# iam-review.sh
# Collects active IAM role recommendations and unused-service-account insights
# for every visible project into two CSV files for a periodic access review.
# Usage: ./iam-review.sh [PROJECT_FILTER]
#   PROJECT_FILTER is an optional gcloud --filter, default &quot;lifecycleState=ACTIVE&quot;
set -euo pipefail

FILTER=&quot;${1:-lifecycleState=ACTIVE}&quot;
REC_CSV=&quot;iam-recommendations-$(date +%F).csv&quot;
SA_CSV=&quot;unused-service-accounts-$(date +%F).csv&quot;

echo &quot;project,recommendation_id,subtype,priority,etag,description&quot; &gt; &quot;$REC_CSV&quot;
echo &quot;project,service_account,subtype,severity,description&quot; &gt; &quot;$SA_CSV&quot;

for project in $(gcloud projects list --filter=&quot;$FILTER&quot; --format=&apos;value(projectId)&apos;); do
  echo &quot;Reviewing $project&quot; &gt;&amp;2

  if ! recs=$(gcloud recommender recommendations list \
      --project=&quot;$project&quot; --location=global \
      --recommender=google.iam.policy.Recommender \
      --filter=&apos;stateInfo.state=ACTIVE&apos; \
      --format=&apos;csv[no-heading](name.basename(),recommenderSubtype,priority,etag,description)&apos; 2&gt;/dev/null); then
    echo &quot;  skipped recommendations (API disabled or no access)&quot; &gt;&amp;2
    recs=&quot;&quot;
  fi
  [[ -n &quot;$recs&quot; ]] &amp;&amp; sed &quot;s|^|${project},|&quot; &lt;&lt;&lt; &quot;$recs&quot; &gt;&gt; &quot;$REC_CSV&quot;

  if ! sas=$(gcloud recommender insights list \
      --project=&quot;$project&quot; --location=global \
      --insight-type=google.iam.serviceAccount.Insight \
      --filter=&apos;stateInfo.state=ACTIVE&apos; \
      --format=&apos;csv[no-heading](targetResources[0].basename(),insightSubtype,severity,description)&apos; 2&gt;/dev/null); then
    echo &quot;  skipped service account insights&quot; &gt;&amp;2
    sas=&quot;&quot;
  fi
  [[ -n &quot;$sas&quot; ]] &amp;&amp; sed &quot;s|^|${project},|&quot; &lt;&lt;&lt; &quot;$sas&quot; &gt;&gt; &quot;$SA_CSV&quot;
done

echo &quot;Wrote $REC_CSV ($(($(wc -l &lt; &quot;$REC_CSV&quot;) - 1)) rows) and $SA_CSV ($(($(wc -l &lt; &quot;$SA_CSV&quot;) - 1)) rows)&quot; &gt;&amp;2
</code></pre>
<p>Working a row from that file looks like this. Claiming the recommendation stops the Recommender API from rewriting it while you act, and marking it succeeded closes the loop in the console:</p>
<pre><code class="language-bash">PROJECT=payments-prod
REC_ID=0f1e2d3c-example
ETAG=$(gcloud recommender recommendations describe &quot;$REC_ID&quot; --project=&quot;$PROJECT&quot; \
  --location=global --recommender=google.iam.policy.Recommender --format=&apos;value(etag)&apos;)

gcloud recommender recommendations mark-claimed &quot;$REC_ID&quot; --project=&quot;$PROJECT&quot; \
  --location=global --recommender=google.iam.policy.Recommender --etag=&quot;$ETAG&quot; \
  --state-metadata=reviewer=platform-team,ticket=SEC-1234

# Apply the change the recommendation describes, for example:
gcloud projects remove-iam-policy-binding &quot;$PROJECT&quot; \
  --member=&apos;user:jane@example.com&apos; --role=&apos;roles/editor&apos;

ETAG=$(gcloud recommender recommendations describe &quot;$REC_ID&quot; --project=&quot;$PROJECT&quot; \
  --location=global --recommender=google.iam.policy.Recommender --format=&apos;value(etag)&apos;)
gcloud recommender recommendations mark-succeeded &quot;$REC_ID&quot; --project=&quot;$PROJECT&quot; \
  --location=global --recommender=google.iam.policy.Recommender --etag=&quot;$ETAG&quot;
</code></pre>
<p>Applying a recommendation needs <code>roles/recommender.iamAdmin</code> plus the right to change the resource&apos;s allow policy. Some project-level recommendations propose a new custom role, which also needs <code>iam.roles.create</code>.</p>
<h2>Make broad access temporary instead of permanent</h2>
<p>Most &quot;just give me Editor&quot; requests are really &quot;give me more access for this afternoon.&quot; IAM conditions make that expire on its own. A binding with a <code>request.time</code> condition stops granting access at the timestamp, and nobody has to remember to remove it:</p>
<pre><code class="language-bash">gcloud projects add-iam-policy-binding payments-prod \
  --member=&apos;user:jane@example.com&apos; \
  --role=&apos;roles/compute.instanceAdmin.v1&apos; \
  --condition=&apos;expression=request.time &lt; timestamp(&quot;2026-09-12T00:00:00Z&quot;),title=incident-4711,description=Temporary access for incident 4711&apos;
</code></pre>
<p>One limitation pushes you toward predefined roles here anyway: IAM refuses conditions on the basic roles (Owner, Editor, Viewer). For requests that need approval and an audit trail, Privileged Access Manager formalizes the same idea with entitlements that principals request and approvers grant for a bounded duration.</p>
<h2>Service accounts are the real risk</h2>
<p>Human access gets reviewed because humans are visible: they&apos;re in the org chart, they leave the company, someone notices. Service accounts have none of that natural pressure. A service account with a long-lived downloaded key and a broad role is a far bigger blast radius than any single over-permissioned engineer, because it&apos;s usually forgotten faster than it&apos;s found.</p>
<p>Google&apos;s key-management guidance is to use an alternative &quot;whenever possible&quot;: an attached service account for workloads on Google Cloud, and Workload Identity Federation for workloads elsewhere (GitHub Actions, AWS, Azure, any OIDC or SAML provider), which authenticates without a downloaded key at all. The organization policy <code>iam.managed.disableServiceAccountKeyCreation</code> enforces that. It&apos;s already on by default for organizations created on or after May 3, 2024, and the <a href="https://www.techcolumnist.com/2026/05/13/google-cloud-organization-policy-constraints-that-actually-matter/">organization policy post</a> covers rolling it out on older ones.</p>
<p>For the keys that remain, two checks come before any deletion:</p>
<pre><code class="language-bash"># When was each key last used? (roles/policyanalyzer.activityAnalysisViewer)
gcloud policy-intelligence query-activity \
  --activity-type=serviceAccountKeyLastAuthentication \
  --project=payments-prod

# Which service accounts haven&apos;t authenticated in 90 days?
gcloud recommender insights list \
  --insight-type=google.iam.serviceAccount.Insight \
  --project=payments-prod --location=global
</code></pre>
<p>The service account insight has blind spots Google documents: requests authenticated with API keys bound to a service account aren&apos;t counted, and neither is authentication to Google APIs outside Google Cloud, such as Workspace domain-wide delegation. Cross-check with Cloud Monitoring&apos;s service account usage metrics before you disable anything. Every remaining downloaded key is a flag for &quot;why does this still need to exist,&quot; not a fact of life; the <a href="https://www.techcolumnist.com/2026/03/04/node-js-gcloud-rotating-service-account-keys-before-they-expire/">key rotation script</a> is what I use for the ones that really do.</p>
<h2>Making it stick</h2>
<p>None of this holds without the boring part: a recurring review cadence (the two CSVs above, every month, diffed against last month), an owner for every custom role, and enough cultural buy-in that a tightened permission gets reported as friction to investigate rather than quietly worked around with a personal access grant. The technical controls are the easy half. The discipline to keep re-applying them as the organization changes is the part that actually determines whether least privilege is real or just written down.</p>
<h2>References</h2>
<ul><li><a href="https://docs.cloud.google.com/iam/docs/roles-overview">Roles and permissions overview</a></li>
<li><a href="https://docs.cloud.google.com/policy-intelligence/docs/role-recommendations-overview">Role recommendations overview</a></li>
<li><a href="https://docs.cloud.google.com/policy-intelligence/docs/review-apply-role-recommendations">Review and apply role recommendations</a></li>
<li><a href="https://docs.cloud.google.com/policy-intelligence/docs/service-account-insights">Find unused service accounts (service account insights)</a></li>
<li><a href="https://docs.cloud.google.com/policy-intelligence/docs/activity-analyzer-service-account-authentication">Activity Analyzer: service account key authentication</a></li>
<li><a href="https://docs.cloud.google.com/policy-intelligence/docs/analyze-iam-policies">Analyze IAM policies (Policy Analyzer)</a></li>
<li><a href="https://docs.cloud.google.com/asset-inventory/docs/searching-iam-policies">Search IAM allow policies</a></li>
<li><a href="https://docs.cloud.google.com/iam/docs/creating-custom-roles">Create and manage custom roles</a></li>
<li><a href="https://docs.cloud.google.com/iam/docs/configuring-temporary-access">Configure temporary access with IAM conditions</a></li>
<li><a href="https://docs.cloud.google.com/iam/docs/best-practices-for-managing-service-account-keys">Best practices for managing service account keys</a></li>
</ul>
]]></content:encoded>
      <category>Engineering</category>
    </item>
    <item>
      <title>Windows Management: A Discovery Inventory Nobody Maintains by Hand</title>
      <link>https://www.techcolumnist.com/2026/09/02/windows-management-building-a-discovery-inventory-nobody-has-to-maintain-by-hand/</link>
      <guid isPermaLink="true">https://www.techcolumnist.com/2026/09/02/windows-management-building-a-discovery-inventory-nobody-has-to-maintain-by-hand/</guid>
      <pubDate>Wed, 02 Sep 2026 14:00:00 GMT</pubDate>
      <dc:creator>Tom Lasswell</dc:creator>
      <description>Why a self-refreshing Windows inventory built from AD and CIM discovery outlasts a spreadsheet, with the sweep script, staleness report and schedule.</description>
      <content:encoded><![CDATA[<p>Every Windows shop I have worked in has had at least one asset spreadsheet that was accurate for about a month after someone built it and has been slowly lying ever since. The problem was never a lack of effort, it was that the inventory depended on a human remembering to update it every time a machine was imaged, retired, or moved to a different subnet. The inventories that have actually stayed useful for me are the ones nobody has to remember to touch.</p>
<p>This post is the design and the scripts I use to get there: a scheduled sweep that asks Active Directory what should exist, asks each machine over CIM what it actually is, merges the answers into a file that remembers when each machine was last seen, and reports on the ones that have gone quiet.</p>
<h2>The spreadsheet fails the moment it requires a human step</h2>
<p>A manually maintained inventory has exactly one job and one failure mode: someone forgets to add a row, or forgets to remove one, and from that moment the document is actively wrong rather than merely incomplete. Wrong is worse than incomplete, because an incomplete inventory gets treated with appropriate suspicion while a wrong one gets trusted right up until it causes a bad decision, like decommissioning a server the spreadsheet says is unused. Any inventory design that depends on someone remembering a manual step will eventually fail exactly that way, no matter how well-intentioned the team maintaining it is.</p>
<h2>Query the machines instead of asking people to report them</h2>
<p>The fix is to make discovery something the machines answer, not something a person types. There are two sources, and they answer different questions:</p>
<ul><li><strong>Active Directory</strong> says what <em>should</em> exist. <code>Get-ADComputer</code> returns every enabled computer account, and with <code>-Properties</code> it adds <code>OperatingSystem</code>, <code>OperatingSystemVersion</code>, <code>LastLogonDate</code> and <code>IPv4Address</code> (resolved from DNS) without touching the machine.</li>
<li><strong>CIM</strong> says what the machine actually <em>is</em>. <code>Win32_OperatingSystem</code> has <code>Caption</code>, <code>BuildNumber</code> and <code>LastBootUpTime</code>; <code>Win32_ComputerSystem</code> has manufacturer, model and memory; <code>Win32_BIOS</code> has the serial number your hardware vendor and your warranty lookups want.</li>
</ul>
<p><code>New-CimSession</code> uses WSMan by default when you give it a computer name, so the same WinRM configuration you already need for PowerShell remoting covers it. For the handful of old servers where WinRM isn&apos;t available, <code>New-CimSessionOption -Protocol Dcom</code> gets you a DCOM session instead. Pass an array of sessions to <code>Get-CimInstance</code> and it queries them all at once, tagging each result with <code>PSComputerName</code>.</p>
<p>One thing AD can&apos;t tell you is whether a machine is alive <em>right now</em>. <code>LastLogonDate</code> is derived from <code>lastLogonTimestamp</code>, and Microsoft documents that by default that attribute is only updated when its current value is 9 to 14 days older than the logon, to keep replication load down. It&apos;s fine for &quot;hasn&apos;t been seen in 90 days&quot; and useless for &quot;is it on this week&quot;. That&apos;s why the sweep keeps its own <code>LastSeen</code>.</p>
<p>Here is the sweep. It needs the Active Directory module (RSAT), WinRM reachable on the targets, and an account with admin rights on them (the default WinRM endpoint only admits Administrators and, if you configure it, Remote Management Users):</p>
<pre><code class="language-powershell">&lt;#
.SYNOPSIS
    Discovers Windows computers from Active Directory, collects OS and hardware facts
    over CIM, and merges them into an inventory CSV that tracks when each was last seen.
.DESCRIPTION
    Reads enabled computer accounts from AD, opens CIM sessions (WSMan) in bulk, queries
    Win32_OperatingSystem, Win32_ComputerSystem and Win32_BIOS, and merges the results
    into the existing inventory. Reachable machines get fresh facts and a new LastSeen;
    unreachable ones keep their last known facts and their old LastSeen, so they age
    into the staleness report instead of disappearing.
.PARAMETER SearchBase
    Distinguished name of the OU to discover. Defaults to the whole domain.
.PARAMETER InventoryPath
    Inventory CSV to read and rewrite.
.PARAMETER TimeoutSec
    CIM operation timeout per computer, in seconds.
.EXAMPLE
    .\Invoke-DiscoverySweep.ps1 -SearchBase &quot;OU=Workstations,DC=corp,DC=example,DC=com&quot; -InventoryPath D:\Inventory\inventory.csv
.NOTES
    Author  : Thomas Lasswell (https://www.techcolumnist.com)
    Version : 1.0 (2026-09-02)
    Requires: ActiveDirectory module (RSAT); WinRM on targets; admin rights on targets
#&gt;
[CmdletBinding()]
param (
    [string]$SearchBase,

    [string]$InventoryPath = &quot;.\inventory.csv&quot;,

    [int]$TimeoutSec = 30
)

Import-Module -Name ActiveDirectory -ErrorAction Stop

$now = Get-Date
$adParams = @{
    Filter     = &apos;Enabled -eq $true&apos;
    Properties = &quot;OperatingSystem&quot;, &quot;OperatingSystemVersion&quot;, &quot;LastLogonDate&quot;, &quot;IPv4Address&quot;
}
if ($SearchBase) {
    $adParams.SearchBase = $SearchBase
}

$adComputers = @(Get-ADComputer @adParams)
Write-Host &quot;AD returned $($adComputers.Count) enabled computer account(s).&quot;

# Load the previous inventory so unreachable machines keep their last known facts.
$inventory = @{}
if (Test-Path -Path $InventoryPath) {
    foreach ($row in Import-Csv -Path $InventoryPath) {
        $inventory[$row.Name] = $row
    }
}

# Open CIM sessions in bulk; failures land in $sessionErrors instead of stopping the run.
$sessionOption = New-CimSessionOption -Protocol Wsman
$targets = @($adComputers | Where-Object { $_.DNSHostName } | Select-Object -ExpandProperty DNSHostName)
$sessions = @(New-CimSession -ComputerName $targets -SessionOption $sessionOption -OperationTimeoutSec $TimeoutSec -ErrorAction SilentlyContinue -ErrorVariable sessionErrors)
Write-Host &quot;Opened $($sessions.Count) CIM session(s); $(@($sessionErrors).Count) computer(s) unreachable.&quot;

$facts = @{}
if ($sessions.Count -gt 0) {
    $cimParams = @{ CimSession = $sessions; OperationTimeoutSec = $TimeoutSec; ErrorAction = &quot;SilentlyContinue&quot; }

    foreach ($os in Get-CimInstance @cimParams -ClassName Win32_OperatingSystem -Property Caption, BuildNumber, LastBootUpTime) {
        $facts[$os.PSComputerName] = @{ OS = $os }
    }
    foreach ($cs in Get-CimInstance @cimParams -ClassName Win32_ComputerSystem -Property Manufacturer, Model, TotalPhysicalMemory) {
        if ($facts.ContainsKey($cs.PSComputerName)) { $facts[$cs.PSComputerName].CS = $cs }
    }
    foreach ($bios in Get-CimInstance @cimParams -ClassName Win32_BIOS -Property SerialNumber) {
        if ($facts.ContainsKey($bios.PSComputerName)) { $facts[$bios.PSComputerName].BIOS = $bios }
    }

    $sessions | Remove-CimSession
}

foreach ($computer in $adComputers) {
    $previous = $inventory[$computer.Name]
    $live = if ($computer.DNSHostName) { $facts[$computer.DNSHostName] } else { $null }

    if ($live) {
        $inventory[$computer.Name] = [pscustomobject]@{
            Name           = $computer.Name
            DNSHostName    = $computer.DNSHostName
            IPv4Address    = $computer.IPv4Address
            OSCaption      = $live.OS.Caption
            OSBuild        = $live.OS.BuildNumber
            LastBoot       = $live.OS.LastBootUpTime.ToString(&quot;s&quot;)
            Manufacturer   = $live.CS.Manufacturer
            Model          = $live.CS.Model
            MemoryGB       = [math]::Round($live.CS.TotalPhysicalMemory / 1GB, 1)
            SerialNumber   = $live.BIOS.SerialNumber
            ADLastLogon    = if ($computer.LastLogonDate) { $computer.LastLogonDate.ToString(&quot;s&quot;) } else { &quot;&quot; }
            LastSeen       = $now.ToString(&quot;s&quot;)
            InAD           = $true
        }
    } elseif ($previous) {
        # Unreachable this run: keep the old facts and the old LastSeen, refresh the AD fields.
        $previous.IPv4Address = $computer.IPv4Address
        $previous.ADLastLogon = if ($computer.LastLogonDate) { $computer.LastLogonDate.ToString(&quot;s&quot;) } else { &quot;&quot; }
        $previous.InAD = $true
    } else {
        # Known to AD but never reached: record it so it shows up as never seen.
        $inventory[$computer.Name] = [pscustomobject]@{
            Name           = $computer.Name
            DNSHostName    = $computer.DNSHostName
            IPv4Address    = $computer.IPv4Address
            OSCaption      = $computer.OperatingSystem
            OSBuild        = $computer.OperatingSystemVersion
            LastBoot       = &quot;&quot;
            Manufacturer   = &quot;&quot;
            Model          = &quot;&quot;
            MemoryGB       = &quot;&quot;
            SerialNumber   = &quot;&quot;
            ADLastLogon    = if ($computer.LastLogonDate) { $computer.LastLogonDate.ToString(&quot;s&quot;) } else { &quot;&quot; }
            LastSeen       = &quot;&quot;
            InAD           = $true
        }
    }
}

# Rows whose computer account is gone or disabled stay in the file, flagged.
$adNames = @($adComputers.Name)
foreach ($name in @($inventory.Keys)) {
    if ($adNames -notcontains $name) {
        $inventory[$name].InAD = $false
    }
}

$inventory.Values | Sort-Object -Property Name | Export-Csv -Path $InventoryPath -NoTypeInformation
Write-Host &quot;Inventory written to $InventoryPath ($($inventory.Count) rows, $($facts.Count) refreshed this run).&quot;
</code></pre>
<p>Sample console output from a run against a workstation OU:</p>
<pre><code class="language-text">AD returned 412 enabled computer account(s).
Opened 377 CIM session(s); 35 computer(s) unreachable.
Inventory written to D:\Inventory\inventory.csv (419 rows, 377 refreshed this run).
</code></pre>
<p>Notice the row count is higher than the AD count. The extra rows are computers whose accounts were disabled or deleted since the last sweep. They stay in the file with <code>InAD = False</code> until someone confirms the hardware is really gone, which is exactly the conversation a spreadsheet never forces.</p>
<h2>Staleness is a feature, not a bug, if you surface it</h2>
<p>An automated inventory should record when each entry was last refreshed, and that timestamp is more valuable than most of the other fields combined. A machine that has not reported in three weeks is telling you something: it is off the network, decommissioned without the paperwork catching up, or broken in a way worth investigating. I treat &quot;last seen&quot; as the primary health signal of the whole inventory system, and the stale-entries report has turned up orphaned assets that no human review of a spreadsheet ever caught.</p>
<p>The report is deliberately small. It reads the inventory and sorts machines into the buckets that need different follow-ups:</p>
<pre><code class="language-powershell">&lt;#
.SYNOPSIS
    Reports inventory rows that have not been seen recently.
.PARAMETER InventoryPath
    Inventory CSV written by Invoke-DiscoverySweep.ps1.
.PARAMETER StaleDays
    Days since LastSeen after which a machine counts as stale.
.EXAMPLE
    .\Get-StaleInventory.ps1 -InventoryPath D:\Inventory\inventory.csv -StaleDays 21
.NOTES
    Author  : Thomas Lasswell (https://www.techcolumnist.com)
    Version : 1.0 (2026-09-02)
#&gt;
[CmdletBinding()]
param (
    [string]$InventoryPath = &quot;.\inventory.csv&quot;,

    [int]$StaleDays = 21
)

$cutoff = (Get-Date).AddDays(-$StaleDays)

Import-Csv -Path $InventoryPath | ForEach-Object {
    $lastSeen = if ($_.LastSeen) { [datetime]$_.LastSeen } else { $null }

    $bucket = if ($_.InAD -eq &quot;False&quot;) {
        &quot;Removed from AD: confirm disposal&quot;
    } elseif (-not $lastSeen) {
        &quot;Never reached: check WinRM, firewall or whether it exists&quot;
    } elseif ($lastSeen -lt $cutoff) {
        &quot;Stale: not seen in $StaleDays+ days&quot;
    } else {
        $null
    }

    if ($bucket) {
        [pscustomobject]@{
            Name        = $_.Name
            Bucket      = $bucket
            LastSeen    = $_.LastSeen
            ADLastLogon = $_.ADLastLogon
            Model       = $_.Model
            Serial      = $_.SerialNumber
        }
    }
} | Sort-Object -Property Bucket, LastSeen | Format-Table -AutoSize
</code></pre>
<pre><code class="language-text">Name      Bucket                                                   LastSeen            ADLastLogon         Model        Serial
----      ------                                                   --------            -----------         -----        ------
WKS-0091  Never reached: check WinRM, firewall or whether it exists                    2026-05-02T08:14:51
WKS-0310  Removed from AD: confirm disposal                        2026-07-28T02:00:12 2026-07-21T09:33:02 Latitude 5440 &lt;serial&gt;
WKS-0142  Stale: not seen in 21+ days                              2026-08-03T02:00:09 2026-08-01T16:20:45 OptiPlex 7010 &lt;serial&gt;
</code></pre>
<p>Reading <code>ADLastLogon</code> next to <code>LastSeen</code> is where the insight is. Stale in the sweep but recently logged on in AD usually means the machine is alive and the sweep can&apos;t reach it (a firewall rule, a VPN-only laptop). Stale in both is a machine that&apos;s genuinely gone somewhere.</p>
<h2>Store it somewhere that answers questions, not just holds rows</h2>
<p>A spreadsheet is a poor home for this kind of data past a few hundred rows, because nobody can ask it a real question without exporting it somewhere else first. Landing the discovery data somewhere Power BI (or an equivalent) can query directly, even a CSV on a file share to start with, turns the inventory into something that answers &quot;which machines are still running an unsupported OS build&quot; in seconds instead of a manual filter-and-scroll exercise:</p>
<pre><code class="language-powershell">Import-Csv -Path D:\Inventory\inventory.csv |
    Where-Object { $_.OSCaption -like &quot;*Windows 11*&quot; } |
    Group-Object -Property OSBuild |
    Sort-Object -Property Name |
    Format-Table Name, Count -AutoSize
</code></pre>
<p>The format matters less than the principle: the inventory should be queryable by the people who need answers, not just readable by the person who happens to have it open. The same file joins cleanly with the per-machine CSVs from the <a href="https://www.techcolumnist.com/2025/08/27/powershell-windows-inventory-installed-software-across-a-domain/">software inventory script</a> and the <a href="https://www.techcolumnist.com/2025/10/08/powershell-windows-discover-local-admins-across-every-workstation/">local admin audit</a>, because all three are keyed by computer name.</p>
<h2>Schedule it, or it&apos;s just another spreadsheet</h2>
<p>The last step is the one that makes it maintenance-free: run the sweep on a schedule from a management server, as a service account that has admin rights on the targets, so nobody has to remember to run it either.</p>
<pre><code class="language-powershell">$credential = Get-Credential -Message &quot;Discovery service account (for example CORP\svc-discovery)&quot;

$action = New-ScheduledTaskAction -Execute &quot;powershell.exe&quot; -Argument &apos;-NoProfile -ExecutionPolicy Bypass -File &quot;D:\Inventory\Invoke-DiscoverySweep.ps1&quot; -InventoryPath &quot;D:\Inventory\inventory.csv&quot;&apos;
$trigger = New-ScheduledTaskTrigger -Daily -At &quot;02:00&quot;

Register-ScheduledTask -TaskName &quot;Discovery Sweep&quot; -TaskPath &quot;\Inventory\&quot; -Action $action -Trigger $trigger -User $credential.UserName -Password $credential.GetNetworkCredential().Password -RunLevel Highest
</code></pre>
<h2>Keep the collection script simpler than the reporting layer</h2>
<p>The temptation once this is running is to keep adding fields to the collection step until it is fetching everything CIM can possibly return. I have found the opposite discipline pays off better: keep what each sweep collects narrow and fast so the collection never becomes fragile or slow enough that people start disabling it, and push the complexity into the reporting queries instead, where it can change without touching a thousand endpoints. The sweep above asks three CIM classes for eight properties, and uses <code>-Property</code> so the remote side only returns those. An inventory that nobody has to maintain by hand only stays that way if the thing collecting it stays simple enough that it never needs hand maintenance either.</p>
<h2>References</h2>
<ul><li><a href="https://learn.microsoft.com/en-us/powershell/module/activedirectory/get-adcomputer">Get-ADComputer</a></li>
<li><a href="https://learn.microsoft.com/en-us/powershell/module/cimcmdlets/new-cimsession">New-CimSession</a> and <a href="https://learn.microsoft.com/en-us/powershell/module/cimcmdlets/get-ciminstance">Get-CimInstance</a></li>
<li><a href="https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-operatingsystem">Win32_OperatingSystem class</a></li>
<li><a href="https://learn.microsoft.com/en-us/troubleshoot/mem/configmgr/discovery/lastlogontimestamp-not-accurate">lastLogonTimestamp is not accurate (9 to 14 day update behavior)</a></li>
<li><a href="https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_remote_requirements">about_Remote_Requirements</a></li>
<li><a href="https://learn.microsoft.com/en-us/powershell/module/scheduledtasks/new-scheduledtasktrigger">New-ScheduledTaskTrigger</a> and <a href="https://learn.microsoft.com/en-us/powershell/module/scheduledtasks/register-scheduledtask">Register-ScheduledTask</a></li>
</ul>
]]></content:encoded>
      <category>Engineering</category>
      <category>Strategy</category>
    </item>
    <item>
      <title>Talos Linux: Upgrading a Cluster Without a Maintenance Window</title>
      <link>https://www.techcolumnist.com/2026/08/26/talos-linux-upgrading-a-cluster-without-a-maintenance-window/</link>
      <guid isPermaLink="true">https://www.techcolumnist.com/2026/08/26/talos-linux-upgrading-a-cluster-without-a-maintenance-window/</guid>
      <pubDate>Wed, 26 Aug 2026 14:00:00 GMT</pubDate>
      <dc:creator>Tom Lasswell</dc:creator>
      <description>Rolling Talos and Kubernetes upgrades through a cluster one node at a time: preflight checks, etcd snapshots, Image Factory installers, and scripts.</description>
      <content:encoded><![CDATA[<p>Asking for a maintenance window used to be the normal cost of doing an OS or Kubernetes upgrade. Talos Linux, combined with a cluster that&apos;s actually built to tolerate a node disappearing, changes that math enough that I no longer schedule downtime for routine version upgrades. I schedule a rolling operation that happens during business hours, with nobody outside the platform team aware it&apos;s happening. That took some deliberate groundwork, not just trusting the upgrade command.</p>
<p>The commands below are current as of Talos 1.14, which changed one thing every existing upgrade runbook needs to pick up: the <code>ghcr.io/siderolabs/installer</code> image is no longer published, and installer images come from the Image Factory instead.</p>
<h2>What <code>talosctl upgrade</code> does, and what it doesn&apos;t</h2>
<p>When a node receives an upgrade request, it cordons itself, drains its pods, stops its services, unmounts its filesystems, writes the new image, and sets the bootloader to boot the new version once. After it comes back and verifies itself, it makes that permanent, rejoins the cluster, and uncordons. Upgrades use an A-B scheme that keeps the previous kernel and OS image, so a node that fails to boot the new version falls back on its own. A node that boots fine but runs your workloads badly needs a manual <code>talosctl rollback</code>.</p>
<p>On control plane nodes Talos adds a guard that matters a lot for no-downtime work: it refuses to upgrade a control plane node if doing so would cost etcd quorum, and if several control plane nodes are asked to upgrade at once it only lets one proceed at a time. The docs are equally clear about what that guard doesn&apos;t cover. Nothing stops you from sending near-simultaneous upgrades to every node, and software that keeps its own quorum (their example is Rook/Ceph) may not recover from more than one node rebooting at a time.</p>
<p>Two flag changes trip up older runbooks:</p>
<ul><li><strong><code>--preserve</code> is gone.</strong> Since Talos 1.8 the installer never wipes the system disk on upgrade, so the release notes describe <code>--preserve</code> as always set, and current <code>talosctl upgrade</code> doesn&apos;t have the flag.</li>
<li><strong><code>--image</code> should always be explicit.</strong> It defaults to the installer for the <code>talosctl</code> version in use, with the empty schematic. Omit it on a node built from a schematic with system extensions and the node upgrades without them. Look up the node&apos;s schematic first; Image Factory appends it to the extension list:</li>
</ul>
<pre><code class="language-bash">talosctl get extensions --nodes 10.10.20.11
</code></pre>
<pre><code class="language-text">NODE          NAMESPACE   TYPE              ID   VERSION   NAME        VERSION
10.10.20.11   runtime     ExtensionStatus   0    1         schematic   376567988ad370138ad8b2698212367b8edcb69b5fd68c80be1f2ec7d603b4ba
</code></pre>
<p>That ID (the &quot;vanilla&quot; schematic, in this example) becomes <code>factory.talos.dev/metal-installer/&lt;schematic-id&gt;:&lt;version&gt;</code>.</p>
<h2>The precondition is workload placement, not the upgrade tool</h2>
<p>Both <code>talosctl upgrade</code> (which cordons and drains a node before touching it) and <code>talosctl upgrade-k8s</code> are built to be run safely against a live cluster. None of that matters if the cluster&apos;s workloads can&apos;t survive a node leaving. A drain goes through the Kubernetes Eviction API, which honours PodDisruptionBudgets, so an upgrade tool that drains correctly is necessary but not sufficient: if three replicas of a service all sit on the node being drained, the graceful drain just makes the outage orderly instead of preventing it.</p>
<p>For anything customer-facing, that means more than one replica, a PDB that reflects real availability requirements, and a spread constraint that keeps replicas on different nodes:</p>
<pre><code class="language-yaml">apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: invoice-api
  namespace: billing
spec:
  maxUnavailable: 1
  selector:
    matchLabels:
      app: invoice-api
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: invoice-api
  namespace: billing
spec:
  replicas: 3
  selector:
    matchLabels:
      app: invoice-api
  template:
    metadata:
      labels:
        app: invoice-api
    spec:
      topologySpreadConstraints:
        - maxSkew: 1
          topologyKey: kubernetes.io/hostname
          whenUnsatisfiable: DoNotSchedule
          labelSelector:
            matchLabels:
              app: invoice-api
      containers:
        - name: api
          image: registry.example.com/billing/invoice-api:2.4.1
</code></pre>
<p>The mirror-image mistake is a PDB that can never be satisfied, such as <code>minAvailable: 1</code> on a single-replica Deployment. That PDB permanently allows zero disruptions, and the drain waits on it until <code>--drain-timeout</code> (five minutes by default) runs out. So before every rolling operation I run a preflight that answers one question: can this cluster lose one node right now?</p>
<pre><code class="language-python">#!/usr/bin/env python3
&quot;&quot;&quot;
upgrade_preflight.py

Answers &quot;can this cluster lose one node right now?&quot; before a rolling Talos or
Kubernetes upgrade. Blocks (exit 1) on:
  - nodes that are not Ready or are already cordoned
  - PodDisruptionBudgets that currently allow zero disruptions (a drain will stall)
  - Deployments/StatefulSets outside the ignored namespaces with fewer than 2 replicas
  - multi-replica Deployments whose Ready pods all sit on one node

Requires: Python 3.10+, `pip install kubernetes`, a kubeconfig that can list
nodes, pods, deployments, statefulsets and poddisruptionbudgets.
&quot;&quot;&quot;

import argparse
import sys
from collections import defaultdict

from kubernetes import client, config


def main():
    parser = argparse.ArgumentParser(description=&quot;Pre-flight checks before a rolling node upgrade.&quot;)
    parser.add_argument(&quot;--kubeconfig&quot;, default=None, help=&quot;Path to kubeconfig (default: standard lookup)&quot;)
    parser.add_argument(&quot;--ignore-namespace&quot;, action=&quot;append&quot;, default=[&quot;kube-system&quot;],
                        help=&quot;Namespace to skip in the workload checks (repeatable; kube-system is skipped by default)&quot;)
    args = parser.parse_args()

    config.load_kube_config(config_file=args.kubeconfig)
    core, apps, policy = client.CoreV1Api(), client.AppsV1Api(), client.PolicyV1Api()
    ignored = set(args.ignore_namespace)
    blockers = []

    for node in core.list_node().items:
        ready = next((c for c in node.status.conditions or [] if c.type == &quot;Ready&quot;), None)
        if ready is None or ready.status != &quot;True&quot;:
            blockers.append(f&quot;node {node.metadata.name} is not Ready&quot;)
        if node.spec.unschedulable:
            blockers.append(f&quot;node {node.metadata.name} is already cordoned&quot;)

    for pdb in policy.list_pod_disruption_budget_for_all_namespaces().items:
        if pdb.metadata.namespace in ignored:
            continue
        if (pdb.status.disruptions_allowed or 0) &lt; 1:
            blockers.append(
                f&quot;PDB {pdb.metadata.namespace}/{pdb.metadata.name} allows 0 disruptions &quot;
                f&quot;(healthy {pdb.status.current_healthy}/{pdb.status.desired_healthy} desired)&quot;
            )

    workloads = [(&quot;Deployment&quot;, d) for d in apps.list_deployment_for_all_namespaces().items]
    workloads += [(&quot;StatefulSet&quot;, s) for s in apps.list_stateful_set_for_all_namespaces().items]
    for kind, obj in workloads:
        ns, name = obj.metadata.namespace, obj.metadata.name
        replicas = obj.spec.replicas if obj.spec.replicas is not None else 1
        if ns not in ignored and 0 &lt; replicas &lt; 2:
            blockers.append(f&quot;{kind} {ns}/{name} has {replicas} replica: it will go down while its node drains&quot;)

    # Ready pods per ReplicaSet owner, grouped by node: catches &quot;3 replicas, 1 node&quot;.
    placement = defaultdict(set)
    for pod in core.list_pod_for_all_namespaces(field_selector=&quot;status.phase=Running&quot;).items:
        if pod.metadata.namespace in ignored or not pod.spec.node_name:
            continue
        for owner in pod.metadata.owner_references or []:
            if owner.kind == &quot;ReplicaSet&quot;:
                placement[(pod.metadata.namespace, owner.name)].add(pod.spec.node_name)
    for (ns, rs), nodes in placement.items():
        replica_set = apps.read_namespaced_replica_set(rs, ns)
        if (replica_set.spec.replicas or 0) &gt;= 2 and len(nodes) == 1:
            blockers.append(f&quot;ReplicaSet {ns}/{rs}: all {replica_set.spec.replicas} replicas run on {next(iter(nodes))}&quot;)

    if blockers:
        print(&quot;NOT SAFE to take a node out:&quot;)
        for item in blockers:
            print(f&quot;  - {item}&quot;)
        sys.exit(1)

    print(&quot;OK: every node Ready, no PDB at zero, no single-replica or single-node workloads.&quot;)
    sys.exit(0)


if __name__ == &quot;__main__&quot;:
    main()
</code></pre>
<pre><code class="language-text">NOT SAFE to take a node out:
  - PDB billing/invoice-worker allows 0 disruptions (healthy 1/1 desired)
  - Deployment billing/invoice-worker has 1 replica: it will go down while its node drains
</code></pre>
<h2>Etcd is the part that actually requires care</h2>
<p>Worker nodes are the easy case; losing one briefly is exactly what the scheduler and PodDisruptionBudgets exist to absorb. Control plane nodes running etcd are where I slow down, because etcd&apos;s quorum math is unforgiving. Talos&apos; disaster recovery guide states it plainly: a three-node control plane tolerates the failure of any single node, and losing more than one at the same time is a complete loss of service. Upgrading a control plane node takes its etcd member away for the reboot, so the cluster runs with no margin until it&apos;s back.</p>
<p>Talos&apos; quorum guard stops the worst mistake, but I still gate each control plane node on a clean etcd status across all members before moving to the next:</p>
<pre><code class="language-bash">talosctl etcd status --nodes 10.10.20.11,10.10.20.12,10.10.20.13
</code></pre>
<pre><code class="language-text">NODE          MEMBER             DB SIZE   IN USE            LEADER             RAFT INDEX   RAFT TERM   RAFT APPLIED INDEX   LEARNER   ERRORS
10.10.20.11   a49c021e76e707db   48 MB     21 MB (43.75%)    ecebb05b59a776f1   1982231      7           1982231              false
10.10.20.12   ecebb05b59a776f1   47 MB     21 MB (44.68%)    ecebb05b59a776f1   1982231      7           1982231              false
10.10.20.13   eb47fb33e59bf0e2   48 MB     21 MB (43.75%)    ecebb05b59a776f1   1982231      7           1982231              false
</code></pre>
<p>All three members present, one agreed leader, matching raft indexes, nothing in <code>ERRORS</code>. And before the first node is touched, I take an etcd snapshot. <code>talosctl etcd snapshot</code> produces a consistent snapshot from any healthy control plane node, and it&apos;s the file <code>talosctl bootstrap --recover-from</code> needs if everything goes wrong. A snapshot taken five minutes before the upgrade is worth far more than last night&apos;s.</p>
<h2>The rolling upgrade as a script</h2>
<p>This is the script, with the health gate between every node. <code>talosctl health</code> confirms etcd, the control plane components, node readiness and schedulability; the etcd status and alarm checks catch anything subtler. It stops at the first failure and leaves the remaining nodes on the old version, which is a perfectly supportable state for as long as it takes to investigate.</p>
<pre><code class="language-bash">#!/usr/bin/env bash
# rolling-talos-upgrade.sh
#
# Upgrades Talos one node at a time: etcd snapshot first, then each control
# plane node, then each worker, with a full health gate and an etcd check
# between nodes. Stops at the first failure and leaves the rest untouched.
#
# Needs: talosctl matching the version the cluster runs now, an os:admin
# talosconfig with the node IPs as endpoints, kubectl, and
# upgrade_preflight.py next to this script.
set -euo pipefail

TARGET_VERSION=&quot;v1.14.0&quot;   # the latest patch of the next minor release; never skip a minor
SCHEMATIC=&quot;&lt;schematic-id&gt;&quot; # from: talosctl get extensions --nodes &lt;ip&gt;
IMAGE=&quot;factory.talos.dev/metal-installer/${SCHEMATIC}:${TARGET_VERSION}&quot;
CONTROL_PLANE=(10.10.20.11 10.10.20.12 10.10.20.13)
WORKERS=(10.10.20.21 10.10.20.22)
SNAPSHOT_DIR=&quot;/var/backups/etcd&quot;

CP_CSV=&quot;$(IFS=,; echo &quot;${CONTROL_PLANE[*]}&quot;)&quot;
WORKER_CSV=&quot;$(IFS=,; echo &quot;${WORKERS[*]}&quot;)&quot;

health_gate() {
    local args=(--nodes &quot;${CONTROL_PLANE[0]}&quot; --control-plane-nodes &quot;$CP_CSV&quot; --wait-timeout 10m)
    if [[ ${#WORKERS[@]} -gt 0 ]]; then
        args+=(--worker-nodes &quot;$WORKER_CSV&quot;)
    fi
    talosctl health &quot;${args[@]}&quot;
    talosctl etcd status --nodes &quot;$CP_CSV&quot;
    if talosctl etcd alarm list --nodes &quot;$CP_CSV&quot; | grep -v &apos;^NODE&apos; | grep -q .; then
        echo &quot;etcd has active alarms; stopping&quot; &gt;&amp;2
        exit 1
    fi
}

upgrade_node() {
    local ip=&quot;$1&quot;
    echo &quot;=== $(date -u +%FT%TZ) upgrading $ip to $TARGET_VERSION&quot;
    python3 &quot;$(dirname &quot;$0&quot;)/upgrade_preflight.py&quot;
    talosctl upgrade --nodes &quot;$ip&quot; --image &quot;$IMAGE&quot; --wait --drain-timeout 10m
    health_gate
    talosctl version --nodes &quot;$ip&quot; | grep -A2 &apos;^Server&apos;
}

echo &quot;=== pre-upgrade health and etcd snapshot&quot;
health_gate
mkdir -p &quot;$SNAPSHOT_DIR&quot;
talosctl etcd snapshot &quot;$SNAPSHOT_DIR/etcd-$(date -u +%Y%m%dT%H%M%SZ)-pre-${TARGET_VERSION}.snapshot&quot; \
    --nodes &quot;${CONTROL_PLANE[0]}&quot;

for ip in &quot;${CONTROL_PLANE[@]}&quot;; do
    upgrade_node &quot;$ip&quot;
done

for ip in &quot;${WORKERS[@]}&quot;; do
    upgrade_node &quot;$ip&quot;
done

echo &quot;=== all nodes on $TARGET_VERSION&quot;
kubectl get nodes -o wide
</code></pre>
<p>Upgrade to the latest patch of each intermediate minor release rather than jumping: Talos only tests config migrations between adjacent minors. Going from 1.12 to 1.14 means two passes of this script, 1.12 to the latest 1.13 patch and then 1.13 to 1.14. Sidero also recommends running the <code>talosctl</code> version that matches the version the cluster currently runs.</p>
<h2>Sequence the OS and Kubernetes upgrades separately</h2>
<p>It&apos;s tempting to bump the Talos version and the Kubernetes version in the same pass, but I treat them as two rolling operations with a validation gap in between. Talos made that the default years ago: since 1.0, a Talos OS upgrade doesn&apos;t upgrade Kubernetes. <code>talosctl upgrade</code> handles the OS, and <code>talosctl upgrade-k8s</code> handles the control plane components, kube-proxy, the kubelet on every node, and the bootstrap manifests. When both changes land in the same pass and something breaks, the first question is always &quot;which of the two things I changed caused this,&quot; and separating them removes that question entirely.</p>
<p>The Kubernetes step has a dry run that I always read first. It lists resources using APIs that are being deprecated in the target version and shows every component it would update:</p>
<pre><code class="language-bash">talosctl --nodes 10.10.20.11 upgrade-k8s --to 1.37.0 --dry-run
talosctl --nodes 10.10.20.11 upgrade-k8s --to 1.37.0
</code></pre>
<p><code>--nodes</code> names the control plane node that receives the API call, but every node in the cluster gets upgraded. The command pre-pulls images, patches each control plane node&apos;s config with the new component versions, updates kube-proxy, then upgrades and verifies the kubelet node by node. If it fails partway, you can rerun it and it continues from where it stopped. Go one Kubernetes minor at a time: the version skew policy doesn&apos;t allow <code>kube-apiserver</code> to skip minor versions. Check the target against the Talos support matrix, too; Talos 1.14 supports Kubernetes 1.33 through 1.37.</p>
<p>One follow-up belongs in the change ticket. <code>upgrade-k8s</code> rewrites component versions in each node&apos;s live config, so any full <code>controlplane.yaml</code> you kept in Git is now stale and would downgrade components if re-applied. That&apos;s the drift Sidero&apos;s reproducible-configuration guide is written around: keep <code>secrets.yaml</code> and patches, and regenerate full configs with the Kubernetes version the cluster now runs.</p>
<h2>What actually made this boring</h2>
<p>The upgrades that go well are the ones where I&apos;ve already tested the exact upgrade path, not just &quot;some Talos upgrade&quot; but the specific current-version-to-target-version jump, on a non-production cluster running comparable workloads. Every release&apos;s upgrade guide has a &quot;before upgrade&quot; section, and it&apos;s not boilerplate: the 1.14 guide, for example, requires migrating the <code>multipath-tools</code> extension&apos;s configuration from an <code>ExtensionServiceConfig</code> document to an <code>EtcFileConfig</code> document <em>before</em> upgrading, or <code>multipathd</code> waits forever after the reboot. Finding that in a test cluster costs nothing. Finding it mid-rollout on a production control plane costs the calm that makes a no-downtime upgrade worth attempting in the first place. Once the workload placement is right and the upgrade path is proven, the rolling upgrade itself really is close to a non-event, which is the whole point.</p>
<p>The cron health check in <a href="https://www.techcolumnist.com/2026/02/04/python-talos-health-checking-a-kubernetes-cluster-from-a-cron-job/">Python: Talos – Health-Checking a Kubernetes Cluster from a Cron Job</a> is what tells me, the morning after, that nothing was left cordoned or crash-looping.</p>
<h2>References</h2>
<ul><li><a href="https://docs.siderolabs.com/talos/v1.14/configure-your-talos-cluster/lifecycle-management/upgrading-talos">Upgrading Talos Linux</a> (sequence, A-B rollback, quorum guard, supported paths, Factory installer images)</li>
<li><a href="https://docs.siderolabs.com/kubernetes-guides/advanced-guides/upgrading-kubernetes">Upgrading Kubernetes</a> (<code>upgrade-k8s</code>, dry run, phases, config drift)</li>
<li><a href="https://github.com/siderolabs/talos/discussions/9359">Talos v1.8.0 release notes</a> (installer never wipes the system disk; <code>--preserve</code> always set)</li>
<li><a href="https://docs.siderolabs.com/talos/v1.14/build-and-extend-talos/cluster-operations-and-maintenance/disaster-recovery">Disaster Recovery</a> and <a href="https://docs.siderolabs.com/talos/v1.14/build-and-extend-talos/cluster-operations-and-maintenance/etcd-maintenance">etcd Maintenance</a></li>
<li><a href="https://docs.siderolabs.com/talos/v1.14/learn-more/image-factory">Image Factory</a> (schematic IDs, <code>talosctl get extensions</code>)</li>
<li><a href="https://docs.siderolabs.com/talos/v1.14/getting-started/support-matrix">Support Matrix</a></li>
<li><a href="https://kubernetes.io/docs/concepts/workloads/pods/disruptions/">Kubernetes: Disruptions</a>, <a href="https://kubernetes.io/docs/tasks/run-application/configure-pdb/">Specifying a Disruption Budget</a> and <a href="https://kubernetes.io/docs/concepts/scheduling-eviction/topology-spread-constraints/">Pod Topology Spread Constraints</a></li>
<li><a href="https://kubernetes.io/releases/version-skew-policy/">Kubernetes Version Skew Policy</a></li>
</ul>
]]></content:encoded>
      <category>Engineering</category>
    </item>
    <item>
      <title>Data Warehouse: Reusable SQL Models for IT Operations Metrics</title>
      <link>https://www.techcolumnist.com/2026/08/19/data-warehouse-reusable-sql-models-for-it-operations-metrics/</link>
      <guid isPermaLink="true">https://www.techcolumnist.com/2026/08/19/data-warehouse-reusable-sql-models-for-it-operations-metrics/</guid>
      <pubDate>Wed, 19 Aug 2026 14:00:00 GMT</pubDate>
      <dc:creator>Tom Lasswell</dc:creator>
      <description>Layered, version-controlled SQL models for MTTR, ticket aging, SLA compliance, and patch compliance, with plain-SQL tests and the dbt equivalent.</description>
      <content:encoded><![CDATA[<p>The first version of most IT operations reporting is a folder of <code>.sql</code> files, each written for a specific dashboard or a question someone asked once and needed answered by Friday. That works right up until two dashboards report different numbers for the same metric. Mean time to resolution, say, because one query counted a reopened ticket once and the other counted it twice, and nobody remembers which is &quot;correct&quot; because both were written under deadline pressure by different people six months apart. Reusable models exist to prevent exactly that drift, and they&apos;re worth building well before the pile of one-off queries gets large enough to hurt.</p>
<p>Below is the model set I&apos;d start with for a service desk: MTTR, ticket aging, SLA compliance, and patch compliance. It&apos;s plain PostgreSQL views, a function, a deploy script, and SQL tests, followed by the same thing in dbt for teams that want it. It builds on the <code>raw</code> / <code>staging</code> / <code>marts</code> layout from <a href="https://www.techcolumnist.com/2026/05/20/data-warehouse-building-a-reporting-layer-without-a-bi-team/">building a reporting layer without a BI team</a>. Source field names are placeholders for whatever your PSA and RMM actually return.</p>
<h2>A metric should have exactly one definition</h2>
<p>The core idea is unglamorous: every metric that gets reported more than once gets one model that defines it, and every dashboard or downstream query references that model instead of recalculating the metric from raw tables. Mean time to resolution gets defined once, in a single view: what counts as &quot;resolved,&quot; how reopens are handled, which ticket types are excluded. Every report pulls from it. When someone (rightly) asks to change the definition, there&apos;s one place to change it, and every consumer updates together instead of drifting apart one query at a time.</p>
<p>Write the definition into the database itself, not only a wiki page. <code>COMMENT ON VIEW</code> shows up in <code>psql</code>&apos;s <code>\dv+</code> listing and in most SQL clients, right where someone is about to use the view.</p>
<h2>Build in layers, not one wide query</h2>
<p>The models that have held up best in practice follow a staging-then-mart pattern, even at small scale. A staging layer cleans and normalizes each source (deduplicating records, standardizing status values, converting types) without imposing business logic yet. A mart layer built on clean staging applies the actual metric definitions. Skip the staging layer and write metric logic directly against a raw ticketing export, and every model reimplements the same cleanup. A source schema change then breaks every downstream model separately instead of in one traceable place.</p>
<p>Here&apos;s the chain for resolution time. Staging exposes the ticket and its status history as typed columns:</p>
<pre><code class="language-sql">-- models/010_stg_ticket_status_changes.sql
CREATE OR REPLACE VIEW staging.stg_ticket_status_changes AS
SELECT payload -&gt;&gt; &apos;ticketId&apos;                 AS ticket_id,
       (payload -&gt;&gt; &apos;changedAt&apos;)::timestamptz AS changed_at,
       lower(trim(payload -&gt;&gt; &apos;fromStatus&apos;))  AS from_status,
       lower(trim(payload -&gt;&gt; &apos;toStatus&apos;))    AS to_status
FROM raw.psa_ticket_status_changes;
</code></pre>
<p>An intermediate model does the one hard part, reopens, exactly once. A reopen is any transition <em>out of</em> a resolved state:</p>
<pre><code class="language-sql">-- models/020_int_ticket_lifecycle.sql
CREATE OR REPLACE VIEW staging.int_ticket_lifecycle AS
WITH changes AS (
    SELECT ticket_id,
           changed_at,
           to_status   IN (&apos;resolved&apos;, &apos;closed&apos;) AS enters_resolved,
           from_status IN (&apos;resolved&apos;, &apos;closed&apos;) AS leaves_resolved
    FROM staging.stg_ticket_status_changes
)
SELECT ticket_id,
       min(changed_at) FILTER (WHERE enters_resolved)                     AS first_resolved_at,
       max(changed_at) FILTER (WHERE enters_resolved)                     AS last_resolved_at,
       count(*)        FILTER (WHERE leaves_resolved AND NOT enters_resolved) AS reopen_count
FROM changes
GROUP BY ticket_id;
</code></pre>
<p>The fact model applies the business definition and documents it:</p>
<pre><code class="language-sql">-- models/030_fct_ticket_resolution.sql
CREATE OR REPLACE VIEW marts.fct_ticket_resolution AS
SELECT t.ticket_id,
       t.client_id,
       t.priority,
       t.queue,
       t.created_at,
       l.first_resolved_at,
       l.last_resolved_at,
       l.reopen_count,
       l.last_resolved_at - t.created_at   AS time_to_resolve,
       t.first_response_at - t.created_at  AS time_to_first_response
FROM staging.stg_tickets t
JOIN staging.int_ticket_lifecycle l USING (ticket_id)
WHERE t.status IN (&apos;resolved&apos;, &apos;closed&apos;)
  AND t.queue NOT IN (&apos;spam&apos;, &apos;merged&apos;, &apos;internal-project&apos;);

COMMENT ON VIEW marts.fct_ticket_resolution IS
  &apos;One row per resolved ticket. Resolution time runs from creation to the FINAL resolution, &apos;
  &apos;so a reopened ticket counts once with its full elapsed time. Excludes spam, merged, and &apos;
  &apos;internal project queues. Wall-clock time, not business hours. Owner: service desk lead.&apos;;
</code></pre>
<p>Everything else reads from that one model. MTTR by month and priority, with the median next to the mean because a few tickets left open for weeks drag the average far from what a typical customer sees:</p>
<pre><code class="language-sql">-- models/040_mttr_monthly.sql
CREATE OR REPLACE VIEW marts.mttr_monthly AS
SELECT date_trunc(&apos;month&apos;, last_resolved_at)::date AS month,
       priority,
       count(*)                                      AS tickets_resolved,
       round((avg(extract(epoch FROM time_to_resolve)) / 3600)::numeric, 1) AS mttr_hours,
       round((percentile_cont(0.5) WITHIN GROUP (
                 ORDER BY extract(epoch FROM time_to_resolve)::float8) / 3600)::numeric, 1) AS median_hours,
       count(*) FILTER (WHERE reopen_count &gt; 0)      AS reopened_tickets
FROM marts.fct_ticket_resolution
GROUP BY 1, 2;
</code></pre>
<p>SLA compliance joins against a small, version-controlled targets table instead of hardcoding hours in the query. A ticket with no first response yet counts as a miss, because a null comparison never satisfies the <code>FILTER</code>:</p>
<pre><code class="language-sql">-- models/050_sla_compliance_monthly.sql
CREATE TABLE IF NOT EXISTS staging.sla_targets (
    priority        text PRIMARY KEY,
    first_response  interval NOT NULL,
    resolution      interval NOT NULL
);

INSERT INTO staging.sla_targets VALUES
    (&apos;p1&apos;, interval &apos;15 minutes&apos;, interval &apos;4 hours&apos;),
    (&apos;p2&apos;, interval &apos;1 hour&apos;,     interval &apos;8 hours&apos;),
    (&apos;p3&apos;, interval &apos;4 hours&apos;,    interval &apos;3 days&apos;),
    (&apos;p4&apos;, interval &apos;1 day&apos;,      interval &apos;10 days&apos;)
ON CONFLICT (priority) DO UPDATE
    SET first_response = EXCLUDED.first_response, resolution = EXCLUDED.resolution;

CREATE OR REPLACE VIEW marts.sla_compliance_monthly AS
SELECT date_trunc(&apos;month&apos;, f.created_at)::date AS month,
       f.priority,
       count(*) AS tickets,
       round(100.0 * count(*) FILTER (WHERE f.time_to_first_response &lt;= s.first_response) / count(*), 1) AS first_response_pct,
       round(100.0 * count(*) FILTER (WHERE f.time_to_resolve &lt;= s.resolution) / count(*), 1)            AS resolution_pct
FROM marts.fct_ticket_resolution f
JOIN staging.sla_targets s USING (priority)
GROUP BY 1, 2;
</code></pre>
<p>The targets above are example values. Use the ones in your actual contracts.</p>
<p>Ticket aging answers &quot;how bad is the backlog right now,&quot; so it reads open tickets from staging rather than the resolved-ticket fact:</p>
<pre><code class="language-sql">-- models/060_ticket_aging.sql
CREATE OR REPLACE VIEW marts.ticket_aging AS
SELECT client_id,
       priority,
       CASE
           WHEN age &lt; interval &apos;1 day&apos;   THEN &apos;1: under 1 day&apos;
           WHEN age &lt; interval &apos;3 days&apos;  THEN &apos;2: 1-3 days&apos;
           WHEN age &lt; interval &apos;7 days&apos;  THEN &apos;3: 3-7 days&apos;
           WHEN age &lt; interval &apos;30 days&apos; THEN &apos;4: 7-30 days&apos;
           ELSE &apos;5: over 30 days&apos;
       END      AS age_bucket,
       count(*) AS open_tickets
FROM (
    SELECT client_id, priority, now() - created_at AS age
    FROM staging.stg_tickets
    WHERE status NOT IN (&apos;resolved&apos;, &apos;closed&apos;, &apos;cancelled&apos;)
) AS open_tickets
GROUP BY 1, 2, 3;
</code></pre>
<p>Patch compliance follows the same shape against RMM data. The definition, written in one place, is that a device is compliant when it has no missing critical updates <em>and</em> has checked in recently. That second condition matters: a laptop that hasn&apos;t reported in a month shows zero missing updates only because nobody has asked it.</p>
<pre><code class="language-sql">-- models/070_patch_compliance.sql
CREATE OR REPLACE VIEW marts.patch_compliance AS
SELECT client_id,
       os_family,
       count(*)                                    AS active_devices,
       count(*) FILTER (WHERE is_compliant)        AS compliant_devices,
       round(100.0 * count(*) FILTER (WHERE is_compliant) / nullif(count(*), 0), 1) AS compliance_pct,
       count(*) FILTER (WHERE NOT reported_recently) AS not_reporting_devices
FROM (
    SELECT client_id,
           os_family,
           last_seen_at &gt;= now() - interval &apos;14 days&apos; AS reported_recently,
           missing_critical_updates = 0
             AND last_seen_at &gt;= now() - interval &apos;14 days&apos; AS is_compliant
    FROM staging.stg_device_patch_status
    WHERE NOT is_retired
) AS devices
GROUP BY 1, 2;

COMMENT ON VIEW marts.patch_compliance IS
  &apos;Compliant = zero missing critical updates AND checked in within 14 days. &apos;
  &apos;Retired devices excluded. Not-reporting devices count as non-compliant.&apos;;
</code></pre>
<h2>Parameterize the model, not the copy</h2>
<p>The second most common failure after duplicated logic is a model that only serves one dashboard&apos;s filters (one date range, one client, one team) hardcoded into the query. The fix isn&apos;t a new copy of the query for every variant. It&apos;s a model that exposes the varying pieces as columns or parameters and keeps the metric logic itself in one place. Every view above already does the first half: <code>month</code>, <code>client_id</code>, and <code>priority</code> are columns, so a dashboard filters them instead of editing SQL. When a caller needs an arbitrary date range, a set-returning SQL function wraps the same fact model:</p>
<pre><code class="language-sql">-- models/080_fn_mttr.sql
CREATE OR REPLACE FUNCTION marts.mttr(p_from date, p_to date, p_client_id bigint DEFAULT NULL)
RETURNS TABLE (priority text, tickets_resolved bigint, mttr_hours numeric, median_hours numeric)
LANGUAGE sql
STABLE
AS $$
    SELECT f.priority,
           count(*),
           round((avg(extract(epoch FROM f.time_to_resolve)) / 3600)::numeric, 1),
           round((percentile_cont(0.5) WITHIN GROUP (
                     ORDER BY extract(epoch FROM f.time_to_resolve)::float8) / 3600)::numeric, 1)
    FROM marts.fct_ticket_resolution f
    WHERE f.last_resolved_at &gt;= p_from
      AND f.last_resolved_at &lt;  p_to + 1
      AND (p_client_id IS NULL OR f.client_id = p_client_id)
    GROUP BY f.priority
    ORDER BY f.priority
$$;

-- Q3 for every client, then Q3 for one client
SELECT * FROM marts.mttr(&apos;2026-07-01&apos;, &apos;2026-09-30&apos;);
SELECT * FROM marts.mttr(&apos;2026-07-01&apos;, &apos;2026-09-30&apos;, 1042);
</code></pre>
<p>A tool like dbt makes this natural with its templating, but plain SQL views with a consistent set of filter columns get most of the same benefit without adopting a new toolchain. That matters when there&apos;s no dedicated team to own that toolchain.</p>
<h2>Materialize only when a view gets slow</h2>
<p>Every model above is a plain view, which means every dashboard load re-runs the whole chain down to <code>raw</code>. That&apos;s fine as long as the whole chain re-runs faster than people will wait for a dashboard tile, which at service desk volumes it usually does, and views have one big advantage: they&apos;re never stale. It stops being fine when a tile&apos;s query takes longer than that and <code>EXPLAIN ANALYZE</code> shows the time going into re-deriving the chain, typically once the raw status-change history has grown or several tiles hit the same model at once. When one does get slow, materialize that model alone and keep its name, so nothing downstream has to change. Replace the contents of <code>030</code> with:</p>
<pre><code class="language-sql">-- models/030_fct_ticket_resolution.sql, materialized version
DROP MATERIALIZED VIEW IF EXISTS marts.fct_ticket_resolution CASCADE;
CREATE MATERIALIZED VIEW marts.fct_ticket_resolution AS
SELECT t.ticket_id, t.client_id, t.priority, t.queue, t.created_at,
       l.first_resolved_at, l.last_resolved_at, l.reopen_count,
       l.last_resolved_at - t.created_at  AS time_to_resolve,
       t.first_response_at - t.created_at AS time_to_first_response
FROM staging.stg_tickets t
JOIN staging.int_ticket_lifecycle l USING (ticket_id)
WHERE t.status IN (&apos;resolved&apos;, &apos;closed&apos;)
  AND t.queue NOT IN (&apos;spam&apos;, &apos;merged&apos;, &apos;internal-project&apos;);

CREATE UNIQUE INDEX fct_ticket_resolution_ticket_id ON marts.fct_ticket_resolution (ticket_id);

-- run after each load, outside deploy.sh
REFRESH MATERIALIZED VIEW CONCURRENTLY marts.fct_ticket_resolution;
</code></pre>
<p><code>CONCURRENTLY</code> lets dashboards keep reading during the refresh. PostgreSQL only allows it when the materialized view has at least one unique index on plain column names, with no expression and no <code>WHERE</code> clause, which is what the <code>ticket_id</code> index is for. The first time, drop the old plain view by hand (<code>DROP VIEW marts.fct_ticket_resolution CASCADE;</code>), since the materialized drop won&apos;t touch a plain view. After that, every deploy rebuilds the fact, and <code>CASCADE</code> drops the views built on it, which files 040 onward recreate in the same transaction. The numbered layout makes that a normal deploy, not a special procedure.</p>
<h2>Version control the models like application code</h2>
<p>SQL models for metrics that leadership makes decisions from deserve the same discipline as production code: checked into source control, reviewed before a definition changes, with a history someone can point to when a number moves and a stakeholder asks why. I&apos;ve seen too many &quot;why did our SLA compliance number jump overnight&quot; conversations resolve to an undocumented <code>WHERE</code> clause edit made directly against a production view, with no record of who changed it or when. A pull request with a one-line description would have made that a five-minute answer instead of a half-day investigation.</p>
<p>The repository needs nothing more than numbered model files, test files, and a deploy script:</p>
<pre><code class="language-text">reporting-models/
  models/010_stg_ticket_status_changes.sql
  models/020_int_ticket_lifecycle.sql
  models/030_fct_ticket_resolution.sql
  ...
  tests/assert_fct_ticket_unique.sql
  tests/assert_resolution_not_negative.sql
  tests/assert_priorities_have_sla.sql
  deploy.sh
</code></pre>
<p>Tests follow the convention dbt uses for singular data tests: each file is a query that returns the rows that break an assertion, and zero rows means pass.</p>
<pre><code class="language-sql">-- tests/assert_fct_ticket_unique.sql
SELECT ticket_id, count(*) FROM marts.fct_ticket_resolution GROUP BY ticket_id HAVING count(*) &gt; 1;

-- tests/assert_resolution_not_negative.sql
SELECT ticket_id, time_to_resolve FROM marts.fct_ticket_resolution WHERE time_to_resolve &lt; interval &apos;0&apos;;

-- tests/assert_priorities_have_sla.sql
SELECT DISTINCT t.priority FROM staging.stg_tickets t
LEFT JOIN staging.sla_targets s USING (priority)
WHERE s.priority IS NULL;
</code></pre>
<p>The deploy script applies every model in one transaction, so a broken model (one that fails to apply) leaves the previous versions in place, then runs the tests. The tests run after that transaction has committed, so a failing test doesn&apos;t roll anything back: the new views are already live, and the non-zero exit is a signal to fix forward or revert the commit and redeploy:</p>
<pre><code class="language-bash">#!/usr/bin/env bash
# deploy.sh: apply models in order in one transaction, then run SQL tests.
# Needs psql and MODELS_DSN for the transformer role. Exits non-zero on any failure.
set -euo pipefail
cd &quot;$(dirname &quot;$0&quot;)&quot;

args=()
for model in models/*.sql; do
  args+=(--file &quot;$model&quot;)
done
psql &quot;$MODELS_DSN&quot; --set ON_ERROR_STOP=1 --single-transaction --quiet &quot;${args[@]}&quot;
echo &quot;Applied ${#args[@]} model file(s).&quot;

failed=0
for test in tests/*.sql; do
  # A psql error stops the script here (set -e); only grep&apos;s no-match status is tolerated.
  output=$(psql &quot;$MODELS_DSN&quot; --set ON_ERROR_STOP=1 --no-align --tuples-only --file &quot;$test&quot;)
  rows=$(grep -c . &lt;&lt;&lt;&quot;$output&quot; || true)
  if [[ &quot;$rows&quot; -gt 0 ]]; then
    echo &quot;FAIL $test ($rows row(s))&quot;
    failed=1
  else
    echo &quot;pass $test&quot;
  fi
done
exit &quot;$failed&quot;
</code></pre>
<p>Run it from CI on every merge to the main branch. The pull request becomes the changelog.</p>
<h3>The same models in dbt</h3>
<p>If the model count grows, or someone on the team already knows dbt, the move is mostly mechanical. Each view becomes a <code>select</code> in its own file, table names become <code>ref()</code> calls so dbt can work out the build order, and the test files become YAML:</p>
<pre><code class="language-sql">-- models/marts/fct_ticket_resolution.sql
{{ config(materialized=&apos;view&apos;) }}

select t.ticket_id,
       t.client_id,
       t.priority,
       t.queue,
       t.created_at,
       l.last_resolved_at,
       l.reopen_count,
       l.last_resolved_at - t.created_at as time_to_resolve,
       t.first_response_at - t.created_at as time_to_first_response
from {{ ref(&apos;stg_tickets&apos;) }} t
join {{ ref(&apos;int_ticket_lifecycle&apos;) }} l using (ticket_id)
where t.status in (&apos;resolved&apos;, &apos;closed&apos;)
  and t.queue not in (&apos;spam&apos;, &apos;merged&apos;, &apos;internal-project&apos;)
</code></pre>
<pre><code class="language-yaml"># models/marts/schema.yml
models:
  - name: fct_ticket_resolution
    description: &gt;
      One row per resolved ticket. Resolution time runs to the final resolution,
      so reopened tickets count once. Excludes spam, merged, and internal project queues.
    columns:
      - name: ticket_id
        data_tests:
          - unique
          - not_null
      - name: priority
        data_tests:
          - accepted_values:
              arguments:
                values: [&apos;p1&apos;, &apos;p2&apos;, &apos;p3&apos;, &apos;p4&apos;]
</code></pre>
<p><code>data_tests:</code> is the current key (<code>tests:</code> still works as an alias), and nesting inputs under <code>arguments:</code> applies from dbt 1.10.5. On older versions, put <code>values</code> directly under the test name. <code>dbt build</code> then runs models and tests in dependency order, which replaces <code>deploy.sh</code>.</p>
<h2>Reusable doesn&apos;t mean over-engineered</h2>
<p>The temptation once this pattern clicks is to model everything, including metrics nobody has asked for twice. My rule of thumb: a query becomes a model the second time it&apos;s needed, not before. The first time, a one-off is fine. That keeps the model library focused on metrics that have proven they&apos;ll be asked about again, instead of piling up unused abstraction that&apos;s harder to maintain than the duplicated queries it was meant to replace.</p>
<h2>References</h2>
<ul><li><a href="https://www.postgresql.org/docs/current/functions-aggregate.html">PostgreSQL: aggregate functions, including percentile_cont</a></li>
<li><a href="https://www.postgresql.org/docs/current/sql-expressions.html">PostgreSQL: aggregate expressions and the FILTER clause</a></li>
<li><a href="https://www.postgresql.org/docs/current/xfunc-sql.html">PostgreSQL: SQL functions returning sets (RETURNS TABLE)</a></li>
<li><a href="https://www.postgresql.org/docs/current/sql-refreshmaterializedview.html">PostgreSQL: REFRESH MATERIALIZED VIEW</a></li>
<li><a href="https://www.postgresql.org/docs/current/sql-comment.html">PostgreSQL: COMMENT</a></li>
<li><a href="https://www.postgresql.org/docs/current/app-psql.html">PostgreSQL: psql (--single-transaction, ON_ERROR_STOP)</a></li>
<li><a href="https://docs.getdbt.com/docs/build/data-tests">dbt: data tests</a></li>
<li><a href="https://docs.getdbt.com/docs/build/materializations">dbt: materializations</a></li>
</ul>
]]></content:encoded>
      <category>Engineering</category>
    </item>
    <item>
      <title>Azure: Cost Governance Without Killing Developer Velocity</title>
      <link>https://www.techcolumnist.com/2026/08/12/azure-cost-governance-without-killing-developer-velocity/</link>
      <guid isPermaLink="true">https://www.techcolumnist.com/2026/08/12/azure-cost-governance-without-killing-developer-velocity/</guid>
      <pubDate>Wed, 12 Aug 2026 14:00:00 GMT</pubDate>
      <dc:creator>Tom Lasswell</dc:creator>
      <description>Azure cost governance that catches waste without approval gates: built-in policy guardrails, budget alerts as code, and scheduled cleanup, with the scripts.</description>
      <content:encoded><![CDATA[<p>The first instinct after a surprise Azure bill is almost always to add an approval gate: someone has to sign off before a new resource gets created, or before a resource above some size gets provisioned. It works, in the narrow sense that it stops the specific mistake that triggered it, and it fails in the broader sense that every developer who wasn&apos;t the cause of that mistake now waits on a human for something that used to be self-service. I&apos;ve watched this pattern play out enough times to trust a different order of operations: guardrails before gates, visibility before restriction, and automation before either. Below is each piece with the code I actually deploy.</p>
<h2>Guardrails instead of gates</h2>
<p>A gate asks permission before the fact; a guardrail makes the expensive mistake structurally hard to make in the first place. Azure Policy is the right tool for guardrails, and the built-in definitions cover the cost-relevant ones without writing custom JSON:</p>
<table><thead><tr><th>Built-in policy</th><th>Definition ID</th><th>Parameter</th><th>Use</th></tr>
</thead><tbody><tr><td>Allowed virtual machine size SKUs</td><td><code>cccc23c7-8427-4f53-ad12-b6a63eb452b3</code></td><td><code>listOfAllowedSKUs</code></td><td>Cap VM sizes in non-production</td></tr>
<tr><td>Allowed locations</td><td><code>e56962a6-4747-49cd-b67b-bf8b01975c4c</code></td><td><code>listOfAllowedLocations</code></td><td>No accidental deployments to pricier or unapproved regions</td></tr>
<tr><td>Not allowed resource types</td><td><code>6c112d4e-5bc7-47ae-a041-ea2d9dccd749</code></td><td><code>listOfResourceTypesNotAllowed</code></td><td>Block specific expensive services in sandboxes</td></tr>
<tr><td>Require a tag on resource groups</td><td><code>96670d01-0a4d-4649-9c89-2d3abc0a5025</code></td><td><code>tagName</code></td><td>No resource group without a cost owner</td></tr>
<tr><td>Inherit a tag from the resource group if missing</td><td><code>ea3f2387-9b95-492a-a190-fcdc54f7b070</code></td><td><code>tagName</code></td><td>Copy the cost tag down to every resource</td></tr>
</tbody></table>
<p>None of these asks a human to approve anything. They make the unintentional expensive path unavailable, while leaving the deliberate one open through an explicit exception process. The distinction that matters is that a guardrail fails fast, at deployment time, with a clear reason, where a gate fails slow, days later, with a queue. Azure Policy supports the &quot;clear reason&quot; part directly: an assignment&apos;s non-compliance message is shown in the deny error the developer sees, so it can say what to do instead.</p>
<p>This script assigns the non-production guardrails to a management group that holds dev/test subscriptions. The allowed-SKU list is an example; pick sizes from your own usage.</p>
<pre><code class="language-bash">#!/usr/bin/env bash
# assign-nonprod-guardrails.sh: cost guardrails on a non-production management group.
set -euo pipefail

MG=&quot;&lt;nonprod-management-group-id&gt;&quot;
SCOPE=&quot;/providers/Microsoft.Management/managementGroups/$MG&quot;
LOCATION=&quot;eastus&quot;   # required for the modify assignment&apos;s managed identity

# Deny VM sizes outside an approved list.
az policy assignment create \
  --name &quot;nonprod-vm-skus&quot; \
  --display-name &quot;Non-prod: allowed VM sizes&quot; \
  --scope &quot;$SCOPE&quot; \
  --policy &quot;cccc23c7-8427-4f53-ad12-b6a63eb452b3&quot; \
  --params &apos;{ &quot;listOfAllowedSKUs&quot;: { &quot;value&quot;: [ &quot;Standard_B2s&quot;, &quot;Standard_B2ms&quot;, &quot;Standard_D2s_v5&quot;, &quot;Standard_D4s_v5&quot; ] } }&apos; \
  --non-compliance-messages &apos;[{ &quot;message&quot;: &quot;Non-production VMs are limited to B-series and small D-series. Ask the platform team for an exemption if you need more.&quot; }]&apos;

# Every resource group needs a costCenter tag.
az policy assignment create \
  --name &quot;nonprod-rg-costcenter&quot; \
  --display-name &quot;Non-prod: require costCenter on resource groups&quot; \
  --scope &quot;$SCOPE&quot; \
  --policy &quot;96670d01-0a4d-4649-9c89-2d3abc0a5025&quot; \
  --params &apos;{ &quot;tagName&quot;: { &quot;value&quot;: &quot;costCenter&quot; } }&apos; \
  --non-compliance-messages &apos;[{ &quot;message&quot;: &quot;Add a costCenter tag to the resource group.&quot; }]&apos;

# Resources inherit costCenter from their resource group (modify effect, needs an identity with Contributor).
az policy assignment create \
  --name &quot;nonprod-inherit-cc&quot; \
  --display-name &quot;Non-prod: inherit costCenter from resource group&quot; \
  --scope &quot;$SCOPE&quot; \
  --policy &quot;ea3f2387-9b95-492a-a190-fcdc54f7b070&quot; \
  --params &apos;{ &quot;tagName&quot;: { &quot;value&quot;: &quot;costCenter&quot; } }&apos; \
  --mi-system-assigned \
  --identity-scope &quot;$SCOPE&quot; \
  --role Contributor \
  --location &quot;$LOCATION&quot;
</code></pre>
<p>Assignment names at management group scope are limited to 24 characters, which is why they&apos;re terse. The modify assignment only tags resources as they&apos;re created or updated; existing ones show as non-compliant until you run a remediation task.</p>
<p>The exception process is a policy exemption with an expiry date, so it can&apos;t quietly become permanent:</p>
<pre><code class="language-bash"># Waive the VM size guardrail for one resource group until the end of the quarter.
az policy exemption create \
  --name &quot;loadtest-large-vms&quot; \
  --display-name &quot;Load test: large VMs until 2026-09-30&quot; \
  --policy-assignment &quot;/providers/Microsoft.Management/managementGroups/&lt;nonprod-management-group-id&gt;/providers/Microsoft.Authorization/policyAssignments/nonprod-vm-skus&quot; \
  --exemption-category Waiver \
  --expires-on &quot;2026-09-30T23:59:59Z&quot; \
  --resource-group &quot;&lt;resource-group&gt;&quot; \
  --description &quot;Approved in &lt;ticket-id&gt;&quot;
</code></pre>
<p>A tag-based guardrail also pays off in reporting. If you&apos;re on an EA, MCA or MPA with an Azure plan, Cost Management&apos;s tag inheritance setting applies subscription and resource group tags to child resource usage records (not to the resources themselves), within 24 hours for the current month. Between that and the modify policy, the <code>costCenter</code> split in cost analysis stops having a big &quot;untagged&quot; bucket.</p>
<h2>Where a gate is still worth the friction</h2>
<p>I&apos;m not against approval workflows entirely. They&apos;re the right tool for the small number of decisions that are genuinely expensive to reverse: reservation and savings plan purchases, anything else with a multi-year commitment, and cross-region data transfer architecture decisions. Undoing those costs real money or real rework. The mistake is applying that same friction to routine, reversible actions like spinning up a dev VM or a test database, where the cost of a wrong decision is measured in dollars per day and the cost of the gate is measured in developer-hours per week across the whole team.</p>
<p>Commitments deserve the gate because they&apos;re easy to get wrong in both directions. Microsoft&apos;s own guidance frames the choice: a reservation commits to a specific instance type or family in a specific region and gives the greatest savings when fully used; a savings plan commits to an hourly spend across eligible compute services in any region and suits workloads that change. The recommended order is to right-size first (&quot;Discounts reduce rates, not waste&quot;), exchange or trade in underused reservations, and only then buy new reservations for stable workloads and savings plans for the flexible remainder. That sequence is a checklist a reviewer can hold a purchase request against.</p>
<p>The other structural lever is the subscription offer itself. Subscription vending in the Cloud Adoption Framework asks at request time whether a workload is production or DevTest, because the DevTest offer has lower resource charges under its own terms (and isn&apos;t available under an MPA). Getting non-production onto the right offer is a one-time decision at vending, not an ongoing approval.</p>
<h2>Visibility changes behavior faster than restriction does</h2>
<p>The governance move with the best ratio of effort to result, by a wide margin, has been making cost visible to the people actually creating resources, not just to whoever reads the monthly report. A budget alert that reaches a finance inbox a week after the spend happened changes nothing about next month&apos;s behavior. A per-subscription or per-tag cost view that a team can see themselves changes behavior almost immediately; teams that can see their own trend line stop leaving test environments running over the weekend without anyone telling them to.</p>
<p>Budgets are the cheapest way to push that signal to the team instead of to finance. Know their limits: budgets alert, they don&apos;t stop anything (&quot;Resources aren&apos;t affected, and your consumption isn&apos;t stopped&quot;). Cost data typically lands within 8 to 24 hours and budgets are evaluated every 24 hours, so an alert is a next-day signal, not a real-time one. Forecasted thresholds help with that lag by warning when the month&apos;s projection crosses a line. At subscription and resource group scope a budget can also call an action group, which is how you route it to a team channel. This is the budget I deploy into every vended subscription, based on Microsoft&apos;s Bicep quickstart with a forecast threshold and role-based recipients added:</p>
<pre><code class="language-bicep">// budget.bicep: monthly subscription budget with actual and forecast alerts.
targetScope = &apos;subscription&apos;

param budgetName string = &apos;monthly-subscription-budget&apos;
param amount int

@description(&apos;First day of the current month, YYYY-MM-DD.&apos;)
param startDate string

param contactEmails array = []

@description(&apos;Optional action group resource IDs, for example one that posts to the team channel.&apos;)
param actionGroupIds array = []

resource budget &apos;Microsoft.Consumption/budgets@2023-11-01&apos; = {
  name: budgetName
  properties: {
    category: &apos;Cost&apos;
    amount: amount
    timeGrain: &apos;Monthly&apos;
    timePeriod: {
      startDate: startDate
    }
    notifications: {
      forecast100: {
        enabled: true
        operator: &apos;GreaterThan&apos;
        threshold: 100
        thresholdType: &apos;Forecasted&apos;
        contactEmails: contactEmails
        contactRoles: [
          &apos;Owner&apos;
          &apos;Contributor&apos;
        ]
        contactGroups: actionGroupIds
      }
      actual80: {
        enabled: true
        operator: &apos;GreaterThan&apos;
        threshold: 80
        thresholdType: &apos;Actual&apos;
        contactEmails: contactEmails
        contactRoles: [
          &apos;Owner&apos;
        ]
        contactGroups: actionGroupIds
      }
      actual100: {
        enabled: true
        operator: &apos;GreaterThan&apos;
        threshold: 100
        thresholdType: &apos;Actual&apos;
        contactEmails: contactEmails
        contactRoles: [
          &apos;Owner&apos;
          &apos;Contributor&apos;
        ]
        contactGroups: actionGroupIds
      }
    }
  }
}
</code></pre>
<pre><code class="language-bash"># Deploy into one subscription. The start date must be the first of a month.
az account set --subscription &quot;&lt;subscription-id&gt;&quot;
az deployment sub create \
  --name budget-deploy \
  --location eastus \
  --template-file budget.bicep \
  --parameters amount=1500 startDate=&quot;$(date -u +%Y-%m-01)&quot; \
               contactEmails=&apos;[&quot;&lt;team-dl&gt;@example.com&quot;]&apos;
</code></pre>
<p>Routing roles like Owner and Contributor means the alert reaches whoever actually runs the subscription, which is the point. If you want budget alerts in Slack rather than email, the <a href="https://www.techcolumnist.com/2026/02/18/node-js-azure-a-slack-bot-for-resource-group-budget-alerts/">Node.js Slack bot for resource group budget alerts</a> does that, and <a href="https://www.techcolumnist.com/2025/12/24/python-azure-automate-cost-anomaly-alerts-with-the-cost-management-api/">Cost Anomaly Alerts from the Cost Management API</a> covers the spikes a monthly budget is too coarse to catch.</p>
<h2>Automating the boring cleanup</h2>
<p>The remaining category, the one guardrails and dashboards don&apos;t fully solve, is idle resource decay: dev environments nobody remembered to tear down, orphaned disks left behind after a VM was deleted, public IPs reserved and never attached. That&apos;s not a governance problem so much as a garbage collection problem, and it belongs in automation, not policy.</p>
<p>For VMs, the built-in auto-shutdown schedule is enough for most non-production machines. The time is UTC in <code>hhmm</code> format:</p>
<pre><code class="language-bash"># Put a 23:00 UTC auto-shutdown on every VM tagged environment=dev in the current subscription.
az vm list --query &quot;[?tags.environment==&apos;dev&apos;].id&quot; --output tsv |
while read -r vmId; do
  az vm auto-shutdown --ids &quot;$vmId&quot; --time 2300 --output none
  echo &quot;auto-shutdown set: $vmId&quot;
done
</code></pre>
<p>For orphans, this weekly sweep flags unattached managed disks (<code>managedBy</code> is null, the same test Microsoft&apos;s own cleanup script uses) and public IPs with no IP configuration or NAT gateway. The first run tags them with the date they were found; later runs report anything flagged longer than the grace period, and delete it only when you pass <code>--delete</code>.</p>
<pre><code class="language-bash">#!/usr/bin/env bash
# orphan-sweep.sh [--delete]: flag, then after a grace period remove, orphaned disks and public IPs.
set -euo pipefail

GRACE_DAYS=14
TAG=&quot;orphanFlaggedOn&quot;
DELETE=false
[[ &quot;${1:-}&quot; == &quot;--delete&quot; ]] &amp;&amp; DELETE=true
TODAY=$(date -u +%F)
CUTOFF=$(date -u -d &quot;-${GRACE_DAYS} days&quot; +%F)

sweep() {
  local kind=&quot;$1&quot; query=&quot;$2&quot;
  az $kind list --query &quot;$query&quot; --output tsv |
  while IFS=$&apos;\t&apos; read -r id flagged; do
    if [[ -z &quot;$flagged&quot; || &quot;$flagged&quot; == &quot;None&quot; ]]; then
      az resource tag --ids &quot;$id&quot; --tags &quot;$TAG=$TODAY&quot; --is-incremental --output none
      echo &quot;flagged   $id&quot;
    elif [[ &quot;$flagged&quot; &lt; &quot;$CUTOFF&quot; || &quot;$flagged&quot; == &quot;$CUTOFF&quot; ]]; then
      if $DELETE; then
        az resource delete --ids &quot;$id&quot; --output none
        echo &quot;deleted   $id (flagged $flagged)&quot;
      else
        echo &quot;expired   $id (flagged $flagged, rerun with --delete)&quot;
      fi
    else
      echo &quot;waiting   $id (flagged $flagged)&quot;
    fi
  done
}

for sub in $(az account list --query &quot;[?state==&apos;Enabled&apos;].id&quot; --output tsv); do
  az account set --subscription &quot;$sub&quot;
  echo &quot;== subscription $sub&quot;
  sweep &quot;disk&quot; &quot;[?managedBy==null].[id, tags.${TAG}]&quot;
  sweep &quot;network public-ip&quot; &quot;[?ipConfiguration==null &amp;&amp; natGateway==null].[id, tags.${TAG}]&quot;
done
</code></pre>
<p>Run it from a pipeline with an identity that has Contributor on the subscriptions in scope, and send the output wherever the teams will see it. The grace period and the tag are what make deletion safe: anyone who still needs a disk has two weeks to remove the tag or attach it, and the tag shows in the portal next to the resource. Before trusting the delete path, run it for a few weeks in report-only mode and check what it would have removed. Automating the cleanup means the governance conversation with developers is only ever about the decisions that actually need a decision, not about nagging people to remember chores a script should be doing anyway.</p>
<p>The throughline across all of it is that governance earns developer trust by being fast and legible, not by being strict. A rule that&apos;s instant, explainable, and has a documented exception path gets followed. A rule that&apos;s slow and opaque gets worked around, quietly, the first time it&apos;s in someone&apos;s way, and a worked-around control is worse than no control at all, because it looks like coverage on paper that isn&apos;t there in practice.</p>
<h2>References</h2>
<ul><li><a href="https://learn.microsoft.com/en-us/azure/governance/policy/samples/built-in-policies">Azure Policy built-in policy definitions</a></li>
<li><a href="https://learn.microsoft.com/en-us/cli/azure/policy/assignment">az policy assignment (Azure CLI)</a></li>
<li><a href="https://learn.microsoft.com/en-us/cli/azure/policy/exemption">az policy exemption (Azure CLI)</a></li>
<li><a href="https://learn.microsoft.com/en-us/azure/governance/policy/concepts/effect-modify">Azure Policy modify effect</a></li>
<li><a href="https://learn.microsoft.com/en-us/azure/cost-management-billing/costs/enable-tag-inheritance">Group and allocate costs using tag inheritance</a></li>
<li><a href="https://learn.microsoft.com/en-us/azure/cost-management-billing/costs/tutorial-acm-create-budgets">Create and manage budgets</a></li>
<li><a href="https://learn.microsoft.com/en-us/azure/cost-management-billing/costs/quick-create-budget-bicep">Quickstart: Create a budget with Bicep</a></li>
<li><a href="https://learn.microsoft.com/en-us/azure/cost-management-billing/savings-plan/decide-between-savings-plan-reservation">Decide between a savings plan and a reservation</a></li>
<li><a href="https://learn.microsoft.com/en-us/azure/cloud-adoption-framework/ready/landing-zone/design-area/subscription-vending">Subscription vending (Cloud Adoption Framework)</a></li>
<li><a href="https://learn.microsoft.com/en-us/azure/virtual-machines/linux/find-unattached-disks">Find and delete unattached Azure managed disks (Azure CLI)</a></li>
</ul>
]]></content:encoded>
      <category>Engineering</category>
      <category>Strategy</category>
    </item>
    <item>
      <title>Intune: Conditional Access Policies That Don&apos;t Lock Out Your Help Desk</title>
      <link>https://www.techcolumnist.com/2026/08/05/intune-conditional-access-policies-that-don-t-lock-out-your-help-desk/</link>
      <guid isPermaLink="true">https://www.techcolumnist.com/2026/08/05/intune-conditional-access-policies-that-don-t-lock-out-your-help-desk/</guid>
      <pubDate>Wed, 05 Aug 2026 14:00:00 GMT</pubDate>
      <dc:creator>Tom Lasswell</dc:creator>
      <description>Seven concrete Entra ID Conditional Access policies, the Graph JSON and PowerShell to create them in report-only, and the roles and queries your help desk needs.</description>
      <content:encoded><![CDATA[<p>The scariest Conditional Access policy I&apos;ve ever reviewed wasn&apos;t scary because it was too weak. It was scary because it was strong enough to lock out the account that would have fixed it. Requiring compliant devices for every application, for every user, with no break-glass path and no staged rollout, is the kind of policy that reads perfectly in a design document and fails the first time a device compliance signal lags behind reality. Microsoft&apos;s own troubleshooting guide lists &quot;all users, all resources, require device to be marked as compliant&quot; as a configuration not to use, because an admin without an enrolled device is blocked from getting back in to change it.</p>
<p>Building Conditional Access and Intune compliance policies that hold up means designing for the failure mode from the start. Below is the baseline I&apos;d put in front of any tenant: seven actual policies modeled on Microsoft&apos;s documented templates, the Graph JSON and PowerShell to create them in report-only mode, the queries to read the results, and the access your help desk needs so a block becomes a ticket they can close.</p>
<h2>Emergency access accounts come first</h2>
<p>Microsoft&apos;s current guidance on emergency access accounts is more specific than &quot;two accounts with long passwords in a safe,&quot; and it changed in ways that matter:</p>
<ul><li><strong>At least two cloud-only accounts</strong> on the <code>*.onmicrosoft.com</code> domain, not federated or synced from on-premises, with Global Administrator assigned <strong>active permanent</strong> (not PIM-eligible).</li>
<li><strong>Passwordless, phishing-resistant authentication</strong>: a FIDO2 passkey (recommended) or certificate-based authentication. These satisfy the mandatory MFA requirement for Azure and admin portals, and they should be a different method from the one your everyday admins use.</li>
<li><strong>Exclude them from Conditional Access policies that block or restrict sign-in.</strong> Report-only policies don&apos;t block access and don&apos;t need the exclusion. Microsoft recommends a dedicated group (for example <code>EmergencyAccess</code>) and excluding that group.</li>
<li><strong>Alert on every sign-in</strong> and <strong>test them at least every 90 days</strong>.</li>
</ul>
<p>The mistake I see most often isn&apos;t skipping this. Most tenants have break-glass accounts. It&apos;s excluding them from the wrong policies. An account excluded from the MFA requirement but still caught by a device compliance policy is not a break-glass account; it&apos;s an account that fails at exactly the moment Intune is the thing that&apos;s broken. Exclude the group from every enforced policy, then audit that it stays excluded (the drift script linked at the end checks this).</p>
<p>The alert Microsoft documents is a Log Analytics query on <code>SigninLogs</code> that fires on any result, wired to an Azure Monitor alert rule with a threshold of 0:</p>
<pre><code class="language-kusto">// Any sign-in by an emergency access account (replace with your accounts&apos; object IDs)
SigninLogs
| where UserId == &quot;&lt;emergency-account-1-object-id&gt;&quot; or UserId == &quot;&lt;emergency-account-2-object-id&gt;&quot;
| project TimeGenerated, UserPrincipalName, UserId, IPAddress, ResultType, ResultDescription
</code></pre>
<p>One more thing belongs in the break-glass plan now: <strong>Microsoft-managed policies</strong>. Microsoft creates policies such as &quot;Block legacy authentication,&quot; &quot;Multifactor authentication for all users,&quot; and &quot;Multifactor authentication for admins accessing Microsoft Admin Portals&quot; in your tenant in report-only, and enables them no less than 30 days later if you leave them there (with email and Message center notice two weeks ahead). You can&apos;t rename or delete them, but you can exclude identities and set them to Off. Exclude your emergency access group from them like any other policy, and decide deliberately whether they or your own policies own each control.</p>
<h2>Seven baseline policies, all starting in report-only</h2>
<p>Every policy below starts in report-only, excludes the emergency access group, and uses a numbered naming convention so sign-in logs, scripts, and conversations can refer to &quot;CA003&quot; without ambiguity. Each one maps to a Microsoft template article (listed in the references).</p>
<h3>CA001: Admins require phishing-resistant MFA</h3>
<table><thead><tr><th>Setting</th><th>Value</th></tr>
</thead><tbody><tr><td>Users: include</td><td>Directory roles: Global, Application, Authentication, Billing, Cloud Application, Conditional Access, Exchange, Helpdesk, Password, Privileged Authentication, Privileged Role, Security, SharePoint, and User Administrator</td></tr>
<tr><td>Users: exclude</td><td><code>EmergencyAccess</code> group</td></tr>
<tr><td>Target resources</td><td>All resources</td></tr>
<tr><td>Conditions</td><td>None</td></tr>
<tr><td>Grant</td><td>Require authentication strength: Phishing-resistant MFA</td></tr>
<tr><td>Initial state</td><td>Report-only</td></tr>
</tbody></table>
<p>Note <strong>Helpdesk Administrator</strong> and <strong>Password Administrator</strong> on that list: your help desk is in scope. Microsoft&apos;s caution is blunt: enabling this before administrators register phishing-resistant methods &quot;risks locking you out of your tenant.&quot; Issue a Temporary Access Pass so each tech can register a passkey or Windows Hello for Business, and watch report-only results until every admin shows success. Conditional Access only targets built-in role assignments; administrative-unit-scoped and custom roles aren&apos;t enforced, so a help desk built on a custom role needs a group-based policy instead.</p>
<h3>CA002: Block legacy authentication</h3>
<table><thead><tr><th>Setting</th><th>Value</th></tr>
</thead><tbody><tr><td>Users: include</td><td>All users</td></tr>
<tr><td>Users: exclude</td><td><code>EmergencyAccess</code> group, plus any account that must keep legacy auth for now</td></tr>
<tr><td>Target resources</td><td>All resources</td></tr>
<tr><td>Conditions</td><td>Client apps: Exchange ActiveSync clients and Other clients only</td></tr>
<tr><td>Grant</td><td>Block access</td></tr>
<tr><td>Initial state</td><td>Report-only</td></tr>
</tbody></table>
<p>Before enforcing, filter the sign-in logs (interactive and non-interactive tabs) on <strong>Client app</strong> for the legacy protocols to find the multifunction printers and old scripts still using them.</p>
<h3>CA003: All users require MFA</h3>
<table><thead><tr><th>Setting</th><th>Value</th></tr>
</thead><tbody><tr><td>Users: include</td><td>All users</td></tr>
<tr><td>Users: exclude</td><td><code>EmergencyAccess</code> group; Directory Synchronization Accounts role if you run Entra Connect or Cloud Sync</td></tr>
<tr><td>Target resources</td><td>All resources, with no exclusions</td></tr>
<tr><td>Conditions</td><td>None</td></tr>
<tr><td>Grant</td><td>Require authentication strength: Multifactor authentication</td></tr>
<tr><td>Initial state</td><td>Report-only</td></tr>
</tbody></table>
<p>Microsoft recommends this exact baseline (all users, all resources, no app exclusions). Don&apos;t combine <strong>Require multifactor authentication</strong> and <strong>Require authentication strength</strong> in one policy; that combination isn&apos;t supported. If you use external authentication methods, use the plain MFA grant instead, because they aren&apos;t compatible with authentication strengths.</p>
<h3>CA004: Require MFA for Azure management</h3>
<table><thead><tr><th>Setting</th><th>Value</th></tr>
</thead><tbody><tr><td>Users: include</td><td>All users</td></tr>
<tr><td>Users: exclude</td><td><code>EmergencyAccess</code> group</td></tr>
<tr><td>Target resources</td><td>Windows Azure Service Management API</td></tr>
<tr><td>Conditions</td><td>None</td></tr>
<tr><td>Grant</td><td>Require multifactor authentication</td></tr>
<tr><td>Initial state</td><td>Report-only</td></tr>
</tbody></table>
<p>The resource is still called <strong>Windows Azure Service Management API</strong> in the picker (Azure Government Cloud Management API in Azure Government). It covers Azure Resource Manager and the Azure portal, which includes the Microsoft Entra admin center, and it indirectly affects Azure CLI and Azure PowerShell. It does not apply to Microsoft Graph PowerShell, and it no longer covers Azure DevOps.</p>
<h3>CA005: Secure security info registration</h3>
<table><thead><tr><th>Setting</th><th>Value</th></tr>
</thead><tbody><tr><td>Users: include</td><td>All users</td></tr>
<tr><td>Users: exclude</td><td>All guest and external users; <code>EmergencyAccess</code> group</td></tr>
<tr><td>Target resources</td><td>User actions: Register security information</td></tr>
<tr><td>Conditions</td><td>Locations: include any location, exclude all trusted locations</td></tr>
<tr><td>Grant</td><td>Require authentication strength: Multifactor authentication</td></tr>
<tr><td>Initial state</td><td>Report-only</td></tr>
</tbody></table>
<p>New hires can&apos;t satisfy MFA before they&apos;ve registered anything, so this policy assumes the help desk issues <strong>Temporary Access Pass</strong> credentials, which satisfy MFA requirements. Microsoft&apos;s docs also flag a date to plan around: starting July 6, 2026, policies targeting Register security information also apply to Windows Hello for Business and macOS Platform SSO credential registration, so a grant control that a new Windows user can&apos;t meet now blocks Windows Hello enrollment too. Test those flows with a pilot group.</p>
<h3>CA006: Windows devices must be compliant or hybrid joined</h3>
<table><thead><tr><th>Setting</th><th>Value</th></tr>
</thead><tbody><tr><td>Users: include</td><td>All users</td></tr>
<tr><td>Users: exclude</td><td><code>EmergencyAccess</code> group; Directory Synchronization Accounts role</td></tr>
<tr><td>Target resources</td><td>All resources</td></tr>
<tr><td>Conditions</td><td>Device platforms: Windows</td></tr>
<tr><td>Grant</td><td>Require device to be marked as compliant <strong>or</strong> Require Microsoft Entra hybrid joined device (require one of the selected controls)</td></tr>
<tr><td>Initial state</td><td>Report-only</td></tr>
</tbody></table>
<p>This is modeled on Microsoft&apos;s &quot;compliant or hybrid joined&quot; template, scoped to Windows while it runs in report-only. That scoping is deliberate: Microsoft warns that report-only policies requiring a compliant device can prompt macOS, iOS, and Android users to pick a device certificate on every sign-in, and recommends excluding those platforms from report-only compliance policies. Add them with their own policy once you&apos;re ready to enforce. The compliant-device control doesn&apos;t block Intune enrollment itself, so new devices can still enroll.</p>
<h3>CA007: MFA and reauthentication for risky sign-ins</h3>
<table><thead><tr><th>Setting</th><th>Value</th></tr>
</thead><tbody><tr><td>Users: include</td><td>All users</td></tr>
<tr><td>Users: exclude</td><td><code>EmergencyAccess</code> group</td></tr>
<tr><td>Target resources</td><td>All resources</td></tr>
<tr><td>Conditions</td><td>Sign-in risk: High and Medium</td></tr>
<tr><td>Grant</td><td>Require authentication strength: Multifactor authentication</td></tr>
<tr><td>Session</td><td>Sign-in frequency: Every time</td></tr>
<tr><td>Initial state</td><td>Report-only</td></tr>
</tbody></table>
<p>This one needs Microsoft Entra ID P2. Users who aren&apos;t registered for MFA get blocked on a risky sign-in with <code>AADSTS53004</code>, because the policy prevents registering MFA during a risky session. That&apos;s a help desk call you can predict: CA005 plus TAP is how the user gets registered before it happens.</p>
<h2>One policy as Microsoft Graph JSON</h2>
<p>A Conditional Access policy is a <code>conditionalAccessPolicy</code> resource with <code>displayName</code>, <code>state</code>, <code>conditions</code>, <code>grantControls</code>, and <code>sessionControls</code>. The <code>state</code> values are <code>enabled</code>, <code>disabled</code>, and <code>enabledForReportingButNotEnforced</code> (report-only). This is CA002 as a <code>POST</code> to <code>https://graph.microsoft.com/v1.0/identity/conditionalAccess/policies</code>:</p>
<pre><code class="language-json">{
  &quot;displayName&quot;: &quot;CA002 - All users - Block legacy authentication&quot;,
  &quot;state&quot;: &quot;enabledForReportingButNotEnforced&quot;,
  &quot;conditions&quot;: {
    &quot;users&quot;: {
      &quot;includeUsers&quot;: [&quot;All&quot;],
      &quot;excludeGroups&quot;: [&quot;&lt;emergency-access-group-object-id&gt;&quot;]
    },
    &quot;applications&quot;: {
      &quot;includeApplications&quot;: [&quot;All&quot;]
    },
    &quot;clientAppTypes&quot;: [&quot;exchangeActiveSync&quot;, &quot;other&quot;]
  },
  &quot;grantControls&quot;: {
    &quot;operator&quot;: &quot;OR&quot;,
    &quot;builtInControls&quot;: [&quot;block&quot;]
  }
}
</code></pre>
<p>CA001 swaps the users block for built-in role template IDs and the grant for an authentication strength reference:</p>
<pre><code class="language-json">{
  &quot;displayName&quot;: &quot;CA001 - Admins - Require phishing-resistant MFA&quot;,
  &quot;state&quot;: &quot;enabledForReportingButNotEnforced&quot;,
  &quot;conditions&quot;: {
    &quot;users&quot;: {
      &quot;includeRoles&quot;: [
        &quot;62e90394-69f5-4237-9190-012177145e10&quot;,
        &quot;729827e3-9c14-49f7-bb1b-9608f156bbb8&quot;,
        &quot;966707d0-3269-4727-9be2-8c3a10f19b9d&quot;
      ],
      &quot;excludeGroups&quot;: [&quot;&lt;emergency-access-group-object-id&gt;&quot;]
    },
    &quot;applications&quot;: { &quot;includeApplications&quot;: [&quot;All&quot;] },
    &quot;clientAppTypes&quot;: [&quot;all&quot;]
  },
  &quot;grantControls&quot;: {
    &quot;operator&quot;: &quot;OR&quot;,
    &quot;builtInControls&quot;: [],
    &quot;authenticationStrength&quot;: { &quot;id&quot;: &quot;&lt;phishing-resistant-strength-id&gt;&quot; }
  }
}
</code></pre>
<p>Those three role IDs are Global Administrator, Helpdesk Administrator, and Password Administrator; the script below carries all fourteen. Look up the strength ID rather than hard-coding it: <code>Get-MgPolicyAuthenticationStrengthPolicy -Filter &quot;policyType eq &apos;builtIn&apos;&quot;</code> lists the three built-in strengths.</p>
<h2>Create the whole set in report-only with PowerShell</h2>
<p>This script creates all seven policies with <code>state</code> set to <code>enabledForReportingButNotEnforced</code>. It resolves the built-in authentication strengths and the Windows Azure Service Management API service principal at run time, skips any policy whose name already exists, and supports <code>-WhatIf</code>. It needs the Microsoft.Graph PowerShell SDK (<code>Microsoft.Graph.Authentication</code>, <code>Microsoft.Graph.Identity.SignIns</code>, <code>Microsoft.Graph.Applications</code>) and a Conditional Access Administrator or Security Administrator. The Graph create API requires <code>Policy.Read.All</code> plus <code>Policy.ReadWrite.ConditionalAccess</code>, and Microsoft documents a known issue where it can ask for consent to more than that; <code>Application.Read.All</code> covers the service principal lookup.</p>
<pre><code class="language-powershell">&lt;#
.SYNOPSIS
    Creates a baseline set of Entra ID Conditional Access policies in report-only mode.
.DESCRIPTION
    Resolves the built-in authentication strengths and the Windows Azure Service Management API
    service principal, then creates seven Conditional Access policies (CA001-CA007) with state
    enabledForReportingButNotEnforced. Every policy excludes the emergency access group. Policies
    whose display name already exists are skipped, so the script is safe to rerun.
.PARAMETER EmergencyAccessGroupId
    Object ID of the security group that holds the emergency access (break-glass) accounts.
.PARAMETER ExcludeDirectorySyncRole
    Also exclude the Directory Synchronization Accounts role from the all-users policies. Use it
    when Microsoft Entra Connect or Cloud Sync is in place.
.EXAMPLE
    .\New-CaReportOnlyBaseline.ps1 -EmergencyAccessGroupId &quot;&lt;group-object-id&gt;&quot; -ExcludeDirectorySyncRole -WhatIf
.NOTES
    Author  : Thomas Lasswell (https://www.techcolumnist.com)
    Version : 1.0 (2026-08-05)
    Requires: PowerShell 7+, Microsoft.Graph.Identity.SignIns, Microsoft.Graph.Applications,
              Conditional Access Administrator or Security Administrator
#&gt;
[CmdletBinding(SupportsShouldProcess = $true)]
param (
    [Parameter(Mandatory = $true)]
    [string]$EmergencyAccessGroupId,

    [switch]$ExcludeDirectorySyncRole
)

$ErrorActionPreference = &apos;Stop&apos;
Import-Module Microsoft.Graph.Identity.SignIns
Import-Module Microsoft.Graph.Applications

Connect-MgGraph -Scopes &apos;Policy.Read.All&apos;, &apos;Policy.ReadWrite.ConditionalAccess&apos;, &apos;Application.Read.All&apos; -NoWelcome

$reportOnly = &apos;enabledForReportingButNotEnforced&apos;

# Built-in role template IDs for the 14 roles in Microsoft&apos;s admin MFA templates.
$adminRoles = @(
    &apos;62e90394-69f5-4237-9190-012177145e10&apos;,
    &apos;9b895d92-2cd3-44c7-9d02-a6ac2d5ea5c3&apos;,
    &apos;c4e39bd9-1100-46d3-8c65-fb160da0071f&apos;,
    &apos;b0f54661-2d74-4c50-afa3-1ec803f12efe&apos;,
    &apos;158c047a-c907-4556-b7ef-446551a6b5f7&apos;,
    &apos;b1be1c3e-b65d-4f19-8427-f6fa0d97feb9&apos;,
    &apos;29232cdf-9323-42fd-ade2-1d097af3e4de&apos;,
    &apos;729827e3-9c14-49f7-bb1b-9608f156bbb8&apos;,
    &apos;966707d0-3269-4727-9be2-8c3a10f19b9d&apos;,
    &apos;7be44c8a-adaf-4e2a-84d6-ab2649e08a13&apos;,
    &apos;e8611ab8-c189-46e8-94e1-60213ab1f814&apos;,
    &apos;194ae4cb-b126-40b2-bd5b-6091b380977d&apos;,
    &apos;f28a1f50-f6e7-4571-818b-6a12f2af6b6c&apos;,
    &apos;fe930be7-5e62-47db-91af-98c3a49a38b1&apos;
)

# Directory Synchronization Accounts role template ID.
$syncRole = &apos;d29b2b05-8046-44ba-8758-1e26182fcf32&apos;

# Resolve the built-in authentication strengths instead of hard-coding their IDs.
$strengths = Get-MgPolicyAuthenticationStrengthPolicy -Filter &quot;policyType eq &apos;builtIn&apos;&quot; -All
$mfaStrength = $strengths | Where-Object { $_.DisplayName -eq &apos;Multifactor authentication&apos; } | Select-Object -First 1
$phishStrength = $strengths | Where-Object { $_.DisplayName -like &apos;*phishing*&apos; } | Select-Object -First 1
if (-not $mfaStrength -or -not $phishStrength) {
    throw &apos;Could not resolve the built-in authentication strengths.&apos;
}

$azureMgmt = Get-MgServicePrincipal -Filter &quot;displayName eq &apos;Windows Azure Service Management API&apos;&quot; -Property &apos;appId&apos; |
    Select-Object -First 1

# Scope shared by the all-users policies.
$allUsers = @{
    includeUsers  = @(&apos;All&apos;)
    excludeGroups = @($EmergencyAccessGroupId)
}
if ($ExcludeDirectorySyncRole) {
    $allUsers.excludeRoles = @($syncRole)
}

$policies = [System.Collections.Generic.List[hashtable]]::new()

$policies.Add(@{
    displayName   = &apos;CA001 - Admins - Require phishing-resistant MFA&apos;
    state         = $reportOnly
    conditions    = @{
        users          = @{ includeRoles = $adminRoles; excludeGroups = @($EmergencyAccessGroupId) }
        applications   = @{ includeApplications = @(&apos;All&apos;) }
        clientAppTypes = @(&apos;all&apos;)
    }
    grantControls = @{ operator = &apos;OR&apos;; builtInControls = @(); authenticationStrength = @{ id = $phishStrength.Id } }
})

$policies.Add(@{
    displayName   = &apos;CA002 - All users - Block legacy authentication&apos;
    state         = $reportOnly
    conditions    = @{
        users          = $allUsers
        applications   = @{ includeApplications = @(&apos;All&apos;) }
        clientAppTypes = @(&apos;exchangeActiveSync&apos;, &apos;other&apos;)
    }
    grantControls = @{ operator = &apos;OR&apos;; builtInControls = @(&apos;block&apos;) }
})

$policies.Add(@{
    displayName   = &apos;CA003 - All users - Require MFA strength&apos;
    state         = $reportOnly
    conditions    = @{
        users          = $allUsers
        applications   = @{ includeApplications = @(&apos;All&apos;) }
        clientAppTypes = @(&apos;all&apos;)
    }
    grantControls = @{ operator = &apos;OR&apos;; builtInControls = @(); authenticationStrength = @{ id = $mfaStrength.Id } }
})

if ($azureMgmt) {
    $policies.Add(@{
        displayName   = &apos;CA004 - All users - Require MFA for Azure management&apos;
        state         = $reportOnly
        conditions    = @{
            users          = @{ includeUsers = @(&apos;All&apos;); excludeGroups = @($EmergencyAccessGroupId) }
            applications   = @{ includeApplications = @($azureMgmt.AppId) }
            clientAppTypes = @(&apos;all&apos;)
        }
        grantControls = @{ operator = &apos;OR&apos;; builtInControls = @(&apos;mfa&apos;) }
    })
} else {
    Write-Warning &apos;Windows Azure Service Management API service principal not found; skipping CA004.&apos;
}

$policies.Add(@{
    displayName   = &apos;CA005 - All users - Secure security info registration&apos;
    state         = $reportOnly
    conditions    = @{
        users          = @{
            includeUsers  = @(&apos;All&apos;)
            excludeUsers  = @(&apos;GuestsOrExternalUsers&apos;)
            excludeGroups = @($EmergencyAccessGroupId)
        }
        applications   = @{ includeUserActions = @(&apos;urn:user:registersecurityinfo&apos;) }
        locations      = @{ includeLocations = @(&apos;All&apos;); excludeLocations = @(&apos;AllTrusted&apos;) }
        clientAppTypes = @(&apos;all&apos;)
    }
    grantControls = @{ operator = &apos;OR&apos;; builtInControls = @(); authenticationStrength = @{ id = $mfaStrength.Id } }
})

$policies.Add(@{
    displayName   = &apos;CA006 - All users - Windows compliant or hybrid joined&apos;
    state         = $reportOnly
    conditions    = @{
        users          = $allUsers
        applications   = @{ includeApplications = @(&apos;All&apos;) }
        platforms      = @{ includePlatforms = @(&apos;windows&apos;) }
        clientAppTypes = @(&apos;all&apos;)
    }
    grantControls = @{ operator = &apos;OR&apos;; builtInControls = @(&apos;compliantDevice&apos;, &apos;domainJoinedDevice&apos;) }
})

$policies.Add(@{
    displayName     = &apos;CA007 - All users - MFA for medium and high sign-in risk&apos;
    state           = $reportOnly
    conditions      = @{
        users            = @{ includeUsers = @(&apos;All&apos;); excludeGroups = @($EmergencyAccessGroupId) }
        applications     = @{ includeApplications = @(&apos;All&apos;) }
        signInRiskLevels = @(&apos;high&apos;, &apos;medium&apos;)
        clientAppTypes   = @(&apos;all&apos;)
    }
    grantControls   = @{ operator = &apos;OR&apos;; builtInControls = @(); authenticationStrength = @{ id = $mfaStrength.Id } }
    sessionControls = @{
        signInFrequency = @{
            isEnabled          = $true
            frequencyInterval  = &apos;everyTime&apos;
            authenticationType = &apos;primaryAndSecondaryAuthentication&apos;
        }
    }
})

$existing = @(Get-MgIdentityConditionalAccessPolicy -All | ForEach-Object { $_.DisplayName })

foreach ($policy in $policies) {
    if ($existing -contains $policy.displayName) {
        Write-Warning &quot;Skipping &apos;$($policy.displayName)&apos;: a policy with that name already exists.&quot;
        continue
    }

    if ($PSCmdlet.ShouldProcess($policy.displayName, &apos;Create Conditional Access policy in report-only mode&apos;)) {
        $created = New-MgIdentityConditionalAccessPolicy -BodyParameter $policy
        [PSCustomObject]@{
            DisplayName = $created.DisplayName
            State       = $created.State
            Id          = $created.Id
        }
    }
}
</code></pre>
<p>Run it with <code>-WhatIf</code> first, then for real:</p>
<pre><code class="language-text">DisplayName                                              State                             Id
-----------                                              -----                             --
CA001 - Admins - Require phishing-resistant MFA          enabledForReportingButNotEnforced 00000000-0000-0000-0000-000000000101
CA002 - All users - Block legacy authentication          enabledForReportingButNotEnforced 00000000-0000-0000-0000-000000000102
CA003 - All users - Require MFA strength                 enabledForReportingButNotEnforced 00000000-0000-0000-0000-000000000103
...
</code></pre>
<h2>Read report-only results before you flip anything</h2>
<p>Report-only means Entra evaluates the policy at every sign-in and logs what it would have done, without prompting or blocking. Each policy lands in one of four report-only results in the sign-in log&apos;s <strong>Report-only</strong> tab: <strong>Success</strong>, <strong>Failure</strong> (a block, or a device that failed a compliance check), <strong>User action required</strong> (the user would have been prompted, for MFA for example), and <strong>Not applied</strong>. &quot;User action required&quot; is the category people skip, and it&apos;s the one that turns into Monday-morning tickets: every sign-in there would have been an MFA prompt someone may not be registered for.</p>
<p>Report-only has limits. Microsoft&apos;s report-only article lists items in the <strong>User actions</strong> scope as the exception to what it can evaluate, so don&apos;t rely on report-only data alone for CA005; confirm it with a pilot group.</p>
<p>My staged sequence: report-only for at least a full business cycle including whatever shift pattern the affected users work, then review near-misses (users who would have failed, not just users who did), fix the gaps, and enforce for a pilot group before the full population. Three tools help:</p>
<ul><li><strong>Policy impact</strong> on each policy&apos;s page shows potential impact on interactive sign-ins over 24 hours, 7 days, or a month. It needs at least Security Reader.</li>
<li><strong>Conditional Access insights and reporting workbook</strong> (Entra ID &gt; Conditional Access &gt; Insights and reporting) shows report-only and enforced results side by side for up to 90 days. It needs Entra ID P1, sign-in logs streaming to a Log Analytics workspace, Security Reader, and permissions on that workspace.</li>
<li><strong>Log Analytics directly.</strong> <code>SigninLogs.ConditionalAccessPolicies</code> is a dynamic array with each policy&apos;s <code>displayName</code> and <code>result</code>, using values like <code>reportOnlySuccess</code>, <code>reportOnlyFailure</code>, and <code>reportOnlyNotApplied</code>. I also include <code>reportOnlyInterrupted</code>, which is in Graph&apos;s result enum; filtering on it costs nothing.</li>
</ul>
<pre><code class="language-kusto">// Sign-ins that a report-only CA policy would have blocked or challenged, last 7 days
SigninLogs
| where TimeGenerated &gt; ago(7d)
| mv-expand Policy = ConditionalAccessPolicies
| extend PolicyName = tostring(Policy.displayName), PolicyResult = tostring(Policy.result)
| where PolicyName startswith &quot;CA0&quot;
| where PolicyResult in (&quot;reportOnlyFailure&quot;, &quot;reportOnlyInterrupted&quot;)
| summarize SignIns = count(), Users = dcount(UserPrincipalName), Apps = make_set(AppDisplayName, 10) by PolicyName, PolicyResult
| order by SignIns desc
</code></pre>
<p>Swap the <code>summarize</code> for <code>project TimeGenerated, UserPrincipalName, AppDisplayName, ClientAppUsed, tostring(DeviceDetail.operatingSystem)</code> to get the list of people to contact before you enforce.</p>
<h2>Give the help desk a way to see what the user sees</h2>
<p>A technician troubleshooting &quot;I can&apos;t get into my email&quot; has almost no chance of diagnosing a Conditional Access block without the sign-in log&apos;s <strong>Conditional Access</strong> tab. The common shortcut is to hand tier 1 Reports Reader and point them at the What If tool. That isn&apos;t enough, and the permissions reference shows why:</p>
<table><thead><tr><th>Role</th><th>Reads sign-in logs</th><th>Reads Conditional Access policies</th></tr>
</thead><tbody><tr><td>Reports Reader</td><td>Yes</td><td>No</td></tr>
<tr><td>Security Reader</td><td>Yes</td><td>Yes (standard properties)</td></tr>
<tr><td>Global Reader</td><td>Yes</td><td>Yes (all properties), but it&apos;s flagged as a privileged role</td></tr>
<tr><td>Helpdesk Administrator</td><td>No</td><td>No</td></tr>
</tbody></table>
<p>Reports Reader can open the sign-in logs, which is why Microsoft&apos;s troubleshooting steps start with it. But Graph documents that the applied Conditional Access policies on a sign-in are only returned to roles that can read Conditional Access data (Global Reader, Security Administrator, Security Reader, Conditional Access Administrator); without one, that property is simply left out. The What If page doesn&apos;t name a required role, but it evaluates your policy set through the <code>conditionalAccess/evaluate</code> API, which needs <code>Policy.Read.ConditionalAccess</code>, so give tier 1 a role that can read policies. <strong>Security Reader</strong> is the least-privileged built-in role that covers both halves. It also unlocks Policy impact and, with access to the Log Analytics workspace, the workbook.</p>
<p>Teach the error codes Microsoft lists for Conditional Access: <code>53000</code> DeviceNotCompliant, <code>53001</code> DeviceNotDomainJoined, <code>53002</code> ApplicationUsedIsNotAnApprovedApp, <code>53003</code> BlockedByConditionalAccess, <code>53004</code> ProofUpBlockedDueToRisk. The user sees them prefixed as <code>AADSTS53003</code> and so on, and <strong>More details</strong> on the error page gives the correlation ID to search for.</p>
<p>For techs who&apos;d rather not click through the portal, this script lists one user&apos;s recent sign-ins that a policy blocked, or that a report-only policy would have blocked. It uses only <code>Microsoft.Graph.Authentication</code>, needs delegated <code>AuditLog.Read.All</code> and <code>Policy.Read.All</code> (an admin consents once), and a Security Reader role. It sends the <code>Prefer: include-unknown-enum-members</code> header, because without it Graph doesn&apos;t return the report-only result values.</p>
<pre><code class="language-powershell">&lt;#
.SYNOPSIS
    Lists a user&apos;s recent sign-ins that Conditional Access blocked or that a report-only policy would have blocked.
.DESCRIPTION
    Queries the Microsoft Graph sign-in logs for one user over a recent window and returns one row per
    failing Conditional Access policy result: time, app, error code, failure reason, device OS,
    compliance flag, policy, result, and correlation ID. Sends Prefer: include-unknown-enum-members so
    report-only results (reportOnlyFailure, reportOnlyInterrupted) are returned.
.PARAMETER UserPrincipalName
    UPN of the user who reported the problem.
.PARAMETER Hours
    How many hours back to look. Default 24.
.EXAMPLE
    .\Get-CaSignInFailure.ps1 -UserPrincipalName &quot;user@example.com&quot; -Hours 8
.NOTES
    Author  : Thomas Lasswell (https://www.techcolumnist.com)
    Version : 1.0 (2026-08-05)
    Requires: PowerShell 7+, Microsoft.Graph.Authentication, AuditLog.Read.All and Policy.Read.All,
              Security Reader (or another role that reads sign-in logs and Conditional Access data)
#&gt;
[CmdletBinding()]
param (
    [Parameter(Mandatory = $true)]
    [string]$UserPrincipalName,

    [ValidateRange(1, 720)]
    [int]$Hours = 24
)

$ErrorActionPreference = &apos;Stop&apos;
Import-Module Microsoft.Graph.Authentication
Connect-MgGraph -Scopes &apos;AuditLog.Read.All&apos;, &apos;Policy.Read.All&apos; -NoWelcome

$since = (Get-Date).ToUniversalTime().AddHours(-$Hours).ToString(&apos;yyyy-MM-ddTHH:mm:ssZ&apos;)
$upn = $UserPrincipalName.ToLower().Replace(&quot;&apos;&quot;, &quot;&apos;&apos;&quot;)
$filter = &quot;userPrincipalName eq &apos;$upn&apos; and createdDateTime ge $since&quot;
$uri = &quot;https://graph.microsoft.com/v1.0/auditLogs/signIns?`$filter=$([uri]::EscapeDataString($filter))&amp;`$top=100&quot;
$headers = @{ Prefer = &apos;include-unknown-enum-members&apos; }
$interesting = @(&apos;failure&apos;, &apos;reportOnlyFailure&apos;, &apos;reportOnlyInterrupted&apos;)

while ($uri) {
    $page = Invoke-MgGraphRequest -Method GET -Uri $uri -Headers $headers
    foreach ($signIn in $page[&apos;value&apos;]) {
        foreach ($policy in $signIn[&apos;appliedConditionalAccessPolicies&apos;]) {
            if ($interesting -contains $policy[&apos;result&apos;]) {
                [PSCustomObject]@{
                    Time          = $signIn[&apos;createdDateTime&apos;]
                    App           = $signIn[&apos;appDisplayName&apos;]
                    ErrorCode     = $signIn[&apos;status&apos;][&apos;errorCode&apos;]
                    FailureReason = $signIn[&apos;status&apos;][&apos;failureReason&apos;]
                    OS            = $signIn[&apos;deviceDetail&apos;][&apos;operatingSystem&apos;]
                    IsCompliant   = $signIn[&apos;deviceDetail&apos;][&apos;isCompliant&apos;]
                    Policy        = $policy[&apos;displayName&apos;]
                    Result        = $policy[&apos;result&apos;]
                    CorrelationId = $signIn[&apos;correlationId&apos;]
                }
            }
        }
    }
    $uri = $page[&apos;@odata.nextLink&apos;]
}
</code></pre>
<p>If the <code>Policy</code> column comes back empty on every row, the signed-in tech has a role that reads sign-in logs but not Conditional Access data. That&apos;s the Reports Reader gap from the table, showing up in practice.</p>
<h2>Intune compliance: the grace period is a setting, not a hope</h2>
<p>Most &quot;compliance lag&quot; lockouts come from Intune defaults nobody revisited:</p>
<ul><li>Every compliance policy includes <strong>Mark device noncompliant</strong> at <strong>0 days</strong>, so a device that fails a rule is noncompliant, and blocked by CA006, immediately. Raising that schedule is the documented way to give users a grace period; the admin center accepts values in 0.25-day steps (0.25 is six hours). Pair it with a <strong>Send email to end user</strong> action at 0 days so the user hears about it before the block.</li>
<li><strong>Mark devices with no compliance policy assigned as</strong> defaults to <strong>Compliant</strong>. Microsoft recommends <strong>Not compliant</strong> when you use Conditional Access, but flipping it before every device has an assigned policy is its own lockout. Check assignments first.</li>
<li><strong>Compliance status validity period</strong> defaults to 30 days (1 to 120). A device that doesn&apos;t report within it becomes noncompliant, which is how a laptop that sat in a drawer shows up as a help desk call.</li>
<li>Compliance is evaluated when the device checks in, so a user who just fixed the problem may still be blocked until the next check-in. The companion script <a href="https://www.techcolumnist.com/2025/10/22/powershell-intune-force-a-compliance-policy-re-evaluation-fleet-wide/">PowerShell: Intune – Force a Compliance Policy Re-evaluation Fleet-Wide</a> shortens that wait.</li>
</ul>
<h2>Treat every policy as reversible until proven otherwise</h2>
<p>Never ship a new or modified Conditional Access policy without first confirming how to undo it quickly, with a tested rollback. A policy that can&apos;t be reversed in under five minutes by someone other than its author isn&apos;t ready to enforce. The fastest rollback that keeps the evidence is flipping the policy back to report-only, which disables enforcement while it keeps logging what the policy would have done:</p>
<pre><code class="language-powershell">Update-MgIdentityConditionalAccessPolicy -ConditionalAccessPolicyId &quot;&lt;policy-id&gt;&quot; -State &quot;enabledForReportingButNotEnforced&quot;
</code></pre>
<p>Know what rollback doesn&apos;t reset. Conditional Access is evaluated when a token is issued. Access tokens last one hour by default, but clients in Continuous Access Evaluation sessions get long-lived tokens of up to 28 hours. Microsoft also documents that Conditional Access policy and group membership changes can take up to a day to take effect at resource providers like Exchange Online and SharePoint Online (optimizations bring policy updates down to about two hours, but not in every scenario). When a change must apply to specific users right away, revoke their sessions (<code>Revoke-MgUserSignInSession -UserId &quot;&lt;user-id&gt;&quot;</code>, which needs <code>User.RevokeSessions.All</code>) or use <strong>Revoke sessions</strong> on the user&apos;s profile. And if every admin is locked out, Microsoft&apos;s documented last resort is a support request, which is exactly why the emergency access accounts come first.</p>
<p>To catch the slow version of this problem (a &quot;temporary&quot; exclusion that never gets removed, or a break-glass group that quietly drops off a policy), I run <a href="https://www.techcolumnist.com/2025/08/06/powershell-entra-id-audit-conditional-access-policy-drift/">PowerShell: Entra ID – Audit Conditional Access Policy Drift</a> on a schedule against a baseline taken right after rollout.</p>
<h2>References</h2>
<ul><li><a href="https://learn.microsoft.com/en-us/entra/identity/role-based-access-control/security-emergency-access">Manage emergency access admin accounts</a></li>
<li><a href="https://learn.microsoft.com/en-us/entra/identity/conditional-access/concept-conditional-access-report-only">Report-only mode, policy impact, and evaluation results</a></li>
<li><a href="https://learn.microsoft.com/en-us/entra/identity/conditional-access/howto-conditional-access-insights-reporting">Conditional Access insights and reporting workbook</a></li>
<li><a href="https://learn.microsoft.com/en-us/entra/identity/conditional-access/managed-policies">Microsoft-managed Conditional Access policies</a></li>
<li>Policy templates: <a href="https://learn.microsoft.com/en-us/entra/identity/conditional-access/policy-admin-phish-resistant-mfa">phishing-resistant MFA for admins</a>, <a href="https://learn.microsoft.com/en-us/entra/identity/conditional-access/policy-block-legacy-authentication">block legacy authentication</a>, <a href="https://learn.microsoft.com/en-us/entra/identity/conditional-access/policy-all-users-mfa-strength">MFA for all users</a>, <a href="https://learn.microsoft.com/en-us/entra/identity/conditional-access/policy-old-require-mfa-azure-mgmt">MFA for Azure management</a>, <a href="https://learn.microsoft.com/en-us/entra/identity/conditional-access/policy-all-users-security-info-registration">security info registration</a>, <a href="https://learn.microsoft.com/en-us/entra/identity/conditional-access/policy-all-users-device-compliance">device compliance</a></li>
<li><a href="https://learn.microsoft.com/en-us/graph/api/resources/conditionalaccesspolicy?view=graph-rest-1.0">conditionalAccessPolicy resource type (Microsoft Graph v1.0)</a> and <a href="https://learn.microsoft.com/en-us/graph/api/conditionalaccessroot-post-policies?view=graph-rest-1.0">Create conditionalAccessPolicy</a></li>
<li><a href="https://learn.microsoft.com/en-us/entra/identity/conditional-access/troubleshoot-conditional-access">Troubleshooting sign-in problems with Conditional Access</a> and <a href="https://learn.microsoft.com/en-us/entra/identity/conditional-access/what-if-tool">the What If tool</a></li>
<li><a href="https://learn.microsoft.com/en-us/entra/identity/role-based-access-control/permissions-reference">Microsoft Entra built-in roles</a> and <a href="https://learn.microsoft.com/en-us/graph/api/signin-list?view=graph-rest-1.0">List signIns permissions</a></li>
<li><a href="https://learn.microsoft.com/en-us/intune/intune-service/protect/actions-for-noncompliance">Intune actions for noncompliance</a> and <a href="https://learn.microsoft.com/en-us/intune/intune-service/protect/device-compliance-get-started">compliance policy settings</a></li>
<li><a href="https://learn.microsoft.com/en-us/entra/identity/conditional-access/concept-continuous-access-evaluation">Continuous access evaluation</a></li>
</ul>
]]></content:encoded>
      <category>Engineering</category>
    </item>
    <item>
      <title>Infrastructure: What a Real Disaster Recovery Test Actually Reveals</title>
      <link>https://www.techcolumnist.com/2026/07/22/infrastructure-what-a-real-disaster-recovery-test-actually-reveals/</link>
      <guid isPermaLink="true">https://www.techcolumnist.com/2026/07/22/infrastructure-what-a-real-disaster-recovery-test-actually-reveals/</guid>
      <pubDate>Wed, 22 Jul 2026 14:00:00 GMT</pubDate>
      <dc:creator>Tom Lasswell</dc:creator>
      <description>What a real DR failover exposes that a tabletop never catches, with a Hyper-V Replica test failover script that checks each recovered VM and a runbook checklist.</description>
      <content:encoded><![CDATA[<p>A disaster recovery plan that has only ever been reviewed on paper is a hypothesis, not a capability. I&apos;ve sat through plenty of tabletop exercises where everyone agreed the runbook made sense, the RTOs looked achievable, and the plan got signed off for another year — and then watched a real, full failover to the DR site find a dozen things the tabletop never could, because a tabletop only tests whether the plan reads well, not whether the systems actually do what the plan assumes.</p>
<h2>Tabletop Exercises Don&apos;t Find These</h2>
<p>Walking through a runbook out loud surfaces logic gaps — a missing step, an unclear owner, a sequencing question nobody had thought about. What it can&apos;t surface is anything that only breaks when bits actually move: a backup job that&apos;s been silently failing for a service nobody checks, a replication link that&apos;s been running behind for months without alerting because the alert threshold was set once and never revisited, or a script that references a path that stopped existing after a server rename. None of that shows up until someone actually tries to bring the environment up somewhere else.</p>
<p>The good news is that the tooling most of us already own was built for exactly this. Hyper-V Replica has a test failover that creates a temporary copy of the replica VM on the DR host, isolated from the production network, while the primary keeps running and replication carries on untouched. Azure Site Recovery has the same idea at recovery-plan scale: you pick a recovery point (latest processed, latest app-consistent, and so on), pick an isolated virtual network, and clean up the test VMs when you&apos;re done. Neither costs you downtime, which removes the usual excuse for only ever doing the tabletop.</p>
<h2>The Dependencies Nobody Documented</h2>
<p>Every DR plan I&apos;ve reviewed has a failover group — the list of systems that get included in the test or the real event. Every real test I&apos;ve run has found at least one application that depends on something outside that group. An app server fails over cleanly and then can&apos;t reach the license server, the internal API it calls for lookups, or a file share that was never in scope because nobody thought of it as &quot;infrastructure.&quot; These dependencies are invisible in an architecture diagram that only shows what a team explicitly built, because most of them accumulated informally after the diagram was drawn. A real failover is the only reliable way to find them, because it&apos;s the only exercise that actually tries to use the dependency and fails when it isn&apos;t there.</p>
<p>That&apos;s why the test script below doesn&apos;t just check that VMs boot. It reads a plan file that lists, for each VM, the services that must be running and the TCP endpoints it must reach, and it tests those from inside the recovered guest. The plan file becomes the dependency documentation, and every failed endpoint check is either a missing VM in the failover group or a hard-coded address that doesn&apos;t exist at the DR site.</p>
<h2>Licensing and Identity Break First</h2>
<p>In the DR tests I&apos;ve run, two categories of failure have come up more often than anything else, and neither is a capacity problem. Licensing tied to a hardware ID, a MAC address, or a specific IP will refuse to activate on DR hardware that doesn&apos;t match, and the fix is rarely fast if it requires a vendor support call mid-test. Identity is the other one: service accounts, Kerberos delegation, and certificate trust chains are full of assumptions about which domain controller, which site, or which network path is available, and a DR site that&apos;s a slower or differently-configured replica of production identity infrastructure surfaces authentication failures that never show up in normal operation.</p>
<p>Microsoft&apos;s Site Recovery guidance for Active Directory is a useful model even outside Azure. Test failover happens in a network isolated from production; before any application fails over, a domain controller and DNS server have to exist in that isolated network, most easily by test-failing-over a replicated DC first. That DC should be a global catalog and hold the FSMO roles the test needs, or those roles have to be seized afterwards. The isolated network should reuse the production address range and must not be connected back to production. On Hyper-V Replica, a test VM (named after the original with <code> - Test</code> appended) isn&apos;t connected to any network by default, which is safe but means no dependency can be tested. The equivalent of Site Recovery&apos;s isolated network is an internal or private virtual switch on the Replica server, assigned to each replicated adapter with <code>Set-VMNetworkAdapter -TestReplicaSwitchName</code>, plus a DC first in the plan file so it is up before anything that authenticates against it.</p>
<h2>Recovery Time vs Recovery Confidence</h2>
<p>The number everyone tracks is recovery time — how long the failover took against the target RTO. The number that actually matters more is recovery confidence: how much of the failover required a human improvising a fix in real time versus following the documented steps. A recovery that hit its RTO because three people quietly worked around three undocumented problems isn&apos;t a passing test; it&apos;s a test that got lucky with who happened to be in the room.</p>
<p>Automation doesn&apos;t create confidence by itself, but it measures it honestly. A script records the same timings and checks every run, so the only way the result improves is if the environment did. And the recovery point matters as much as the recovery time: Hyper-V Replica sends changes every 30 seconds, 5 minutes or 15 minutes, keeps up to 24 hourly recovery points if you configure them, and only produces application-consistent points when you schedule VSS snapshots. A test that fails over to a crash-consistent point on a database server is testing something different from what the business thinks it has.</p>
<h2>The Test Failover Script</h2>
<p>This runs on the Hyper-V Replica server that holds the replica VMs (PowerShell Direct only reaches VMs running on the local host). For each VM in the plan, in order, it checks replication health with <code>Get-VMReplication</code>, creates a test VM with <code>Start-VMFailover -AsTest</code>, starts it, waits until the guest answers over PowerShell Direct, gives services time to settle, then checks the listed services and endpoints from inside the guest. Test VMs stay running until every VM has been checked, because later VMs depend on earlier ones, and then <code>Stop-VMFailover</code> deletes them all, including when the run stops on an error. The results go to a CSV you can attach to the DR test record.</p>
<p>The plan file is a PowerShell data file, ordered the way the runbook boots things:</p>
<pre><code class="language-powershell">@{
    VMs = @(
        @{ Name = &apos;dc-dr01&apos;; Services = @(&apos;NTDS&apos;, &apos;DNS&apos;, &apos;Netlogon&apos;); Endpoints = @() }
        @{ Name = &apos;sql01&apos;; Services = @(&apos;MSSQLSERVER&apos;, &apos;SQLSERVERAGENT&apos;); Endpoints = @(&apos;dc-dr01:389&apos;, &apos;dc-dr01:88&apos;) }
        @{ Name = &apos;lic01&apos;; Services = @(&apos;&lt;license-service-name&gt;&apos;); Endpoints = @(&apos;dc-dr01:389&apos;) }
        @{ Name = &apos;app01&apos;; Services = @(&apos;W3SVC&apos;); Endpoints = @(&apos;sql01:1433&apos;, &apos;lic01:27000&apos;, &apos;files01:445&apos;) }
    )
}
</code></pre>
<p>The script needs the Hyper-V module on the replica host, Windows Server 2016 or later guests (a PowerShell Direct requirement), a guest credential valid in the isolated environment, and replicas that have finished initial replication.</p>
<pre><code class="language-powershell">&lt;#
.SYNOPSIS
    Runs a Hyper-V Replica test failover for a list of VMs and verifies services and dependencies inside each guest.
.DESCRIPTION
    Reads a plan file (.psd1) listing VMs in boot order with the services each must run and the host:port
    endpoints each must reach. For every VM it checks replication health, runs Start-VMFailover -AsTest,
    starts the test VM, waits for PowerShell Direct to respond, then checks services with Get-Service and
    endpoints with Test-NetConnection from inside the guest. When all VMs are done it removes every test VM
    with Stop-VMFailover (unless -KeepTestVMs is set) and writes the results to a CSV file.
.PARAMETER PlanPath
    Path to the .psd1 plan file.
.PARAMETER GuestCredential
    Credential for the guests, valid inside the isolated test network.
.PARAMETER BootTimeoutMinutes
    How long to wait for each test VM to answer PowerShell Direct.
.PARAMETER SettleSeconds
    How long to wait after the guest answers before checking services, for delayed-start services.
.PARAMETER EvidencePath
    CSV file for the results.
.PARAMETER KeepTestVMs
    Leave the test VMs running for manual testing; clean up later with Stop-VMFailover.
.EXAMPLE
    .\Invoke-DRTestFailover.ps1 -PlanPath .\dr-plan.psd1 -GuestCredential (Get-Credential)
.NOTES
    Author  : Thomas Lasswell (https://www.techcolumnist.com)
    Version : 1.0 (2026-07-22)
    Requires: Hyper-V module on the Replica server, Windows Server 2016+ guests
#&gt;

[CmdletBinding()]
param (
    [Parameter(Mandatory = $true)]
    [string]$PlanPath,

    [Parameter(Mandatory = $true)]
    [pscredential]$GuestCredential,

    [Parameter(Mandatory = $false)]
    [int]$BootTimeoutMinutes = 15,

    [Parameter(Mandatory = $false)]
    [int]$SettleSeconds = 120,

    [Parameter(Mandatory = $false)]
    [string]$EvidencePath = (Join-Path -Path (Get-Location).Path -ChildPath (&apos;DRTest-{0:yyyyMMdd-HHmm}.csv&apos; -f (Get-Date))),

    [switch]$KeepTestVMs
)

$ErrorActionPreference = &apos;Stop&apos;
$plan = Import-PowerShellDataFile -Path $PlanPath
$results = [System.Collections.Generic.List[object]]::new()
$testedVMs = [System.Collections.Generic.List[string]]::new()
$runClock = [System.Diagnostics.Stopwatch]::StartNew()

try {
    foreach ($entry in $plan.VMs) {
        $row = [ordered]@{
            VM           = $entry.Name
            Replication  = &apos;Normal&apos;
            TestVM       = &apos;&apos;
            ReadySeconds = $null
            FailedChecks = &apos;&apos;
            Result       = &apos;Pass&apos;
        }

        # Replication health first: a Critical replica is a finding before any test runs.
        foreach ($health in &apos;Warning&apos;, &apos;Critical&apos;) {
            if (Get-VMReplication -VMName $entry.Name -ReplicationHealth $health -ErrorAction SilentlyContinue) {
                $row.Replication = $health
            }
        }

        if ($row.Replication -eq &apos;Critical&apos;) {
            $row.Result = &apos;Fail&apos;
            $row.FailedChecks = &apos;Replication health is Critical; not tested&apos;
            $results.Add([PSCustomObject]$row)
            continue
        }

        # Create the test VM; Hyper-V names it after the replica with &apos; - Test&apos; appended.
        Start-VMFailover -VMName $entry.Name -AsTest -Confirm:$false
        $testVM = Get-VM -Name &quot;$($entry.Name) - Test&quot; -ErrorAction SilentlyContinue | Select-Object -First 1

        if (-not $testVM) {
            $row.Result = &apos;Fail&apos;
            $row.FailedChecks = &apos;Test VM was not created&apos;
            $results.Add([PSCustomObject]$row)
            continue
        }

        $testedVMs.Add($entry.Name)
        $row.TestVM = $testVM.Name
        $clock = [System.Diagnostics.Stopwatch]::StartNew()
        Start-VM -VM $testVM

        # Wait until the guest answers over PowerShell Direct.
        $ready = $false

        do {
            try {
                Invoke-Command -VMId $testVM.VMId -Credential $GuestCredential -ScriptBlock { $true } -ErrorAction Stop | Out-Null
                $ready = $true
            } catch {
                Start-Sleep -Seconds 15
            }
        } while (-not $ready -and $clock.Elapsed.TotalMinutes -lt $BootTimeoutMinutes)

        if (-not $ready) {
            $row.Result = &apos;Fail&apos;
            $row.FailedChecks = &quot;Guest did not answer PowerShell Direct within $BootTimeoutMinutes minutes&quot;
            $results.Add([PSCustomObject]$row)
            continue
        }

        $row.ReadySeconds = [int]$clock.Elapsed.TotalSeconds
        Start-Sleep -Seconds $SettleSeconds

        # Check services and dependencies from inside the recovered guest.
        $checks = Invoke-Command -VMId $testVM.VMId -Credential $GuestCredential -ArgumentList $entry.Services, $entry.Endpoints -ScriptBlock {
            param ($services, $endpoints)

            foreach ($serviceName in $services) {
                $service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
                [PSCustomObject]@{ Check = &quot;service $serviceName&quot;; Passed = [bool]($service -and $service.Status -eq &apos;Running&apos;) }
            }

            foreach ($endpoint in $endpoints) {
                $target, $port = $endpoint -split &apos;:&apos;
                $reachable = Test-NetConnection -ComputerName $target -Port $port -InformationLevel Quiet -WarningAction SilentlyContinue
                [PSCustomObject]@{ Check = &quot;tcp $endpoint&quot;; Passed = [bool]$reachable }
            }
        }

        $failed = @($checks | Where-Object { -not $_.Passed })

        if ($failed.Count -gt 0) {
            $row.Result = &apos;Fail&apos;
            $row.FailedChecks = ($failed.Check) -join &apos;; &apos;
        }

        $results.Add([PSCustomObject]$row)
    }
} finally {
    # Remove the test VMs only after every dependency has been exercised, or when the run stops on an error.
    if (-not $KeepTestVMs) {
        foreach ($name in $testedVMs) {
            Stop-VMFailover -VMName $name -Confirm:$false
        }
    }
}

$results | Export-Csv -Path $EvidencePath -NoTypeInformation
$results | Format-Table -AutoSize
Write-Output &quot;Test run took $([int]$runClock.Elapsed.TotalMinutes) minutes. Evidence: $EvidencePath&quot;
</code></pre>
<p>A first run against a plan like the one above tends to look something like this, and every <code>Fail</code> row is a finding for the report:</p>
<pre><code class="language-text">VM      Replication TestVM          ReadySeconds FailedChecks                      Result
--      ----------- ------          ------------ ------------                      ------
dc-dr01 Normal      dc-dr01 - Test           212                                   Pass
sql01   Warning     sql01 - Test             348                                   Pass
lic01   Normal      lic01 - Test             190 service &lt;license-service-name&gt;    Fail
app01   Normal      app01 - Test             241 tcp files01:445                   Fail
</code></pre>
<p><code>Stop-VMFailover</code> on a test failover turns the test VM off and deletes it; it does not touch the replica or the primary. For Azure Site Recovery the equivalent pair is <code>Start-AzRecoveryServicesAsrTestFailoverJob</code> (against a recovery plan, with <code>-AzureVMNetworkId</code> pointing at the isolated network) and <code>Start-AzRecoveryServicesAsrTestFailoverCleanupJob</code>, and the in-guest checks can run the same way over whatever remote access you have to the test network.</p>
<h2>The Runbook Checklist</h2>
<p>The script covers the mechanical part. The rest is a checklist I keep with the DR plan and fill in during every test:</p>
<p><strong>Before the test</strong></p>
<ul><li><input></input> Replication health is Normal for every VM in scope (<code>Get-VMReplication</code>, or Replicated items in the vault), and you know how far behind the last replication is.</li>
<li><input></input> Recovery point chosen deliberately: latest, or the latest application-consistent point for databases.</li>
<li><input></input> Isolated test network in place, using the production address range and with no route back to production. Test switch set on every replicated adapter.</li>
<li><input></input> DC and DNS first in the boot order; the DR DC is a global catalog and holds (or can seize) the FSMO roles the test needs.</li>
<li><input></input> Plan file reviewed against the application owners&apos; list of dependencies, including licence servers, file shares and external APIs.</li>
<li><input></input> Guest credentials that work without production DCs are available, and the break-glass account has been tested.</li>
</ul>
<p><strong>During the test</strong></p>
<ul><li><input></input> Start time, each VM&apos;s ready time and each failed check recorded (the script&apos;s CSV).</li>
<li><input></input> Every manual intervention written down with who did it and why. Each one counts against recovery confidence, however quickly it was done.</li>
<li><input></input> Application owners sign in and run a real transaction, not just a ping.</li>
<li><input></input> Licence activation and certificate validation checked on every application that has either.</li>
</ul>
<p><strong>After the test</strong></p>
<ul><li><input></input> Test VMs removed (<code>Stop-VMFailover</code>, or Cleanup test failover in Site Recovery) and replication confirmed healthy again.</li>
<li><input></input> Each finding logged as a fix with an owner and a date, and the plan file updated with any dependency the test discovered.</li>
<li><input></input> A retest of each fixed item scheduled as soon as the fix is in, not at next year&apos;s test.</li>
</ul>
<h2>Running It Again, On Purpose</h2>
<p>Every finding from a real test becomes a fix, and every fix needs to be verified by running the test again — not next year, but as soon as the fix is in, on the specific piece that broke. A test failover that costs no downtime and is driven by a script makes that cheap enough to actually do. A DR plan that&apos;s only ever been fully exercised once, however well it went, is still mostly a hypothesis about everything the last test didn&apos;t happen to touch.</p>
<h2>References</h2>
<ul><li><a href="https://learn.microsoft.com/en-us/windows-server/virtualization/hyper-v/replication-failover">Fail over a replicated virtual machine with Hyper-V Replica</a> (test VM naming, network default, one test failover at a time)</li>
<li><a href="https://learn.microsoft.com/en-us/windows-server/virtualization/hyper-v/manage/set-up-hyper-v-replica">Hyper-V Replica overview and setup</a> (test, planned and unplanned failover, replication intervals, recovery points)</li>
<li><a href="https://learn.microsoft.com/en-us/powershell/module/hyper-v/start-vmfailover">Start-VMFailover</a>, <a href="https://learn.microsoft.com/en-us/powershell/module/hyper-v/stop-vmfailover">Stop-VMFailover</a> and <a href="https://learn.microsoft.com/en-us/powershell/module/hyper-v/get-vmreplication">Get-VMReplication</a> cmdlet references</li>
<li><a href="https://learn.microsoft.com/en-us/windows-server/virtualization/hyper-v/powershell-direct">Manage Windows virtual machines with PowerShell Direct</a></li>
<li><a href="https://learn.microsoft.com/en-us/azure/site-recovery/site-recovery-test-failover-to-azure">Run a test failover (disaster recovery drill) to Azure</a></li>
<li><a href="https://learn.microsoft.com/en-us/azure/site-recovery/site-recovery-active-directory">Set up disaster recovery for Active Directory and DNS</a></li>
<li><a href="https://learn.microsoft.com/en-us/powershell/module/az.recoveryservices/start-azrecoveryservicesasrtestfailoverjob">Start-AzRecoveryServicesAsrTestFailoverJob</a></li>
</ul>
]]></content:encoded>
      <category>Engineering</category>
      <category>Strategy</category>
    </item>
    <item>
      <title>Infrastructure: Documenting an Undocumented Network, Discovery First</title>
      <link>https://www.techcolumnist.com/2026/07/15/infrastructure-a-discovery-first-approach-to-documenting-an-undocumented-network/</link>
      <guid isPermaLink="true">https://www.techcolumnist.com/2026/07/15/infrastructure-a-discovery-first-approach-to-documenting-an-undocumented-network/</guid>
      <pubDate>Wed, 15 Jul 2026 14:00:00 GMT</pubDate>
      <dc:creator>Tom Lasswell</dc:creator>
      <description>Document an undocumented network from what it already knows: DHCP leases, AD, ARP and switch MAC tables, then a scoped nmap pass. Scripts included.</description>
      <content:encoded><![CDATA[<p>The environments I get called into are rarely undocumented by accident. They are undocumented because the person who knew the network left, the diagram was last touched three reorganizations ago, and every attempt to rebuild it starting from a blank Visio canvas has stalled the same way: nobody wants to be wrong in front of the team, so the document sits half-finished. The fix I keep coming back to is to stop trying to document from memory and interview, and start from discovery instead.</p>
<p>This post is the process, plus the scripts that do the collecting. There are four of them, run in this order:</p>
<ol><li><code>Export-PassiveInventory.ps1</code>: DHCP leases and Active Directory computer accounts.</li>
<li><code>snmp_collect.py</code>: ARP tables from routers and MAC address tables from switches, over read-only SNMP.</li>
<li><code>merge_inventory.py</code>: joins everything on MAC address and writes <code>inventory.csv</code> plus <code>gaps.txt</code>, the addresses nobody can explain.</li>
<li>A scoped <code>nmap</code> pass against <code>gaps.txt</code> only, then the merge again.</li>
</ol>
<p>Only run any of this on networks you are authorized to assess, with the change window and the owner&apos;s sign-off in writing. Reading tables over SNMP is low-impact, but it is still access, and the active step is a port scan.</p>
<h2>Let the Network Describe Itself First</h2>
<p>Before I ask a single person what they think is connected to what, I pull what the infrastructure already knows about itself. Switch MAC address tables and ARP caches tell you what is actually plugged in and talking, not what someone remembers plugging in two years ago. DHCP lease tables tell you which device holds which address right now, and expired leases show what used to be there, including the things nobody put on a spreadsheet. Router and firewall configs list every VLAN, route, and rule that exists whether or not it was ever written down elsewhere. None of this requires a single meeting, and all of it is ground truth rather than institutional memory, which matters because institutional memory is exactly what is missing in an undocumented environment.</p>
<p>Each source answers a different question, and none is complete on its own:</p>
<table><thead><tr><th>Source</th><th>Answers</th><th>Blind spot</th></tr>
</thead><tbody><tr><td>DHCP leases</td><td>Which MAC holds which IP, and the hostname the client sent</td><td>Anything with a static IP</td></tr>
<tr><td>AD computer accounts</td><td>Which machines are domain-joined, with OS</td><td>Printers, appliances, Linux, anything not joined</td></tr>
<tr><td>Router ARP table</td><td>Every IP-to-MAC pair that talked through that router recently</td><td>Entries age out, so quiet devices can be missing</td></tr>
<tr><td>Switch MAC table</td><td>Which physical port and VLAN each MAC was seen on</td><td>No IP address at all</td></tr>
</tbody></table>
<p>The join key across all four is the MAC address. That&apos;s why the merge script is keyed on it rather than on IP or hostname.</p>
<h2>Step 1: DHCP Leases and AD Computers</h2>
<p>On Windows DHCP, <code>Get-DhcpServerv4Lease</code> returns only active leases by default; its <code>-AllLeases</code> switch adds offered, declined and expired leases, which is useful here because an expired lease is still evidence that a device existed. It is not evidence the device is there now, so the merge script only treats active leases as current and keeps the rest as history. The cmdlet takes scope objects from <code>Get-DhcpServerv4Scope</code> on the pipeline. <code>Get-ADComputer</code> needs <code>-Properties</code> for anything outside its default set, including <code>IPv4Address</code>, <code>OperatingSystem</code> and <code>LastLogonDate</code>.</p>
<p>Run it from a machine with the DhcpServer and ActiveDirectory modules (RSAT). It needs read access to each DHCP server and an ordinary domain account for the AD query.</p>
<pre><code class="language-powershell">&lt;#
.SYNOPSIS
    Exports DHCP leases and Active Directory computer accounts for discovery.
.DESCRIPTION
    Reads every IPv4 scope on each DHCP server, including offered, declined and
    expired leases, and writes dhcp-leases.csv. Then exports every AD computer
    account with its DNS name, IPv4 address, operating system and last logon
    date to ad-computers.csv. Both files feed merge_inventory.py.
.PARAMETER DhcpServer
    One or more Windows DHCP servers to read.
.PARAMETER OutputPath
    Folder for the two CSV files. Created if missing.
.PARAMETER SearchBase
    Optional distinguished name to limit the AD computer export.
.EXAMPLE
    .\Export-PassiveInventory.ps1 -DhcpServer dhcp01.corp.example -OutputPath C:\Discovery\2026-07-15
.NOTES
    Requires the DhcpServer and ActiveDirectory modules (RSAT).
#&gt;
[CmdletBinding()]
param(
    [Parameter(Mandatory)]
    [string[]]$DhcpServer,

    [Parameter(Mandatory)]
    [string]$OutputPath,

    [string]$SearchBase
)

$ErrorActionPreference = &apos;Stop&apos;
Import-Module DhcpServer, ActiveDirectory
New-Item -ItemType Directory -Path $OutputPath -Force | Out-Null

$leases = foreach ($server in $DhcpServer) {
    $scopes = Get-DhcpServerv4Scope -ComputerName $server
    foreach ($scope in $scopes) {
        try {
            Get-DhcpServerv4Lease -ComputerName $server -ScopeId $scope.ScopeId -AllLeases |
                Select-Object -Property IPAddress, ClientId, HostName, AddressState, LeaseExpiryTime,
                    @{ Name = &apos;ScopeId&apos;; Expression = { $scope.ScopeId } },
                    @{ Name = &apos;Server&apos;; Expression = { $server } }
        }
        catch {
            Write-Warning &quot;Could not read scope $($scope.ScopeId) on ${server}: $($_.Exception.Message)&quot;
        }
    }
}
$leases | Export-Csv -Path (Join-Path -Path $OutputPath -ChildPath &apos;dhcp-leases.csv&apos;) -NoTypeInformation

$adParams = @{
    Filter     = &apos;*&apos;
    Properties = &apos;DNSHostName&apos;, &apos;IPv4Address&apos;, &apos;OperatingSystem&apos;, &apos;LastLogonDate&apos;, &apos;Enabled&apos;
}
if ($SearchBase) { $adParams.SearchBase = $SearchBase }

$computers = Get-ADComputer @adParams |
    Select-Object -Property Name, DNSHostName, IPv4Address, OperatingSystem, LastLogonDate, Enabled
$computers | Export-Csv -Path (Join-Path -Path $OutputPath -ChildPath &apos;ad-computers.csv&apos;) -NoTypeInformation

Write-Output &quot;$(@($leases).Count) DHCP leases and $(@($computers).Count) AD computers written to $OutputPath&quot;
</code></pre>
<pre><code class="language-powershell">.\Export-PassiveInventory.ps1 -DhcpServer dhcp01.corp.example, dhcp02.corp.example -OutputPath C:\Discovery\2026-07-15
</code></pre>
<h2>Step 2: ARP and MAC Address Tables over SNMP</h2>
<p>Switches and routers publish their tables in standard MIBs, so one collector works across vendors:</p>
<ul><li><strong>ARP</strong>: <code>ipNetToMediaPhysAddress</code> (<code>1.3.6.1.2.1.4.22.1.2</code>) in the IP-MIB. The table is indexed by interface and IP address, so the IP comes out of the row index and the MAC is the value. RFC 4293 superseded this table with <code>ipNetToPhysicalTable</code>, which adds IPv6, but the older IPv4 table is the one most gear still answers. If yours doesn&apos;t, that&apos;s the table to switch to.</li>
<li><strong>MAC table</strong>: <code>dot1dTpFdbPort</code> (<code>1.3.6.1.2.1.17.4.3.1.2</code>) in the BRIDGE-MIB (RFC 4188). The MAC is encoded in the row index as six decimal numbers and the value is a bridge port number. <code>dot1dTpFdbStatus</code> marks each entry as <code>learned(3)</code>, <code>self(4)</code>, <code>mgmt(5)</code> and so on.</li>
<li><strong>Port names</strong>: bridge port numbers aren&apos;t interface numbers. <code>dot1dBasePortIfIndex</code> (<code>1.3.6.1.2.1.17.1.4.1.2</code>) maps bridge port to <code>ifIndex</code>, and <code>ifName</code> (<code>1.3.6.1.2.1.31.1.1.1.1</code>) turns that into <code>Gi1/0/12</code>.</li>
</ul>
<p>One vendor quirk matters a lot. Cisco Catalyst switches keep a separate BRIDGE-MIB instance per VLAN, reached with <em>community string indexing</em>: query with <code>community@20</code> to get VLAN 20&apos;s MAC table. Without it you only see VLAN 1. The collector takes a <code>--vlans</code> list for that.</p>
<p>The script shells out to Net-SNMP&apos;s <code>snmpbulkwalk</code> with <code>-On</code> (numeric OIDs), <code>-Oq</code> (no type labels), <code>-Oe</code> (numeric enums), <code>-Ob</code> (numeric indexes) and <code>-Ox</code> (hex strings, for MAC values). It reads the community string from an environment variable, which keeps it out of scripts and shell history. It is still passed to <code>snmpbulkwalk</code> with <code>-c</code>, so anyone who can list processes on the collector can see it while a walk runs: run the collector on a host only you can log in to. SNMPv2c sends that string in clear text, so use a read-only community restricted by ACL to your collector, or move to SNMPv3 if the gear supports it.</p>
<pre><code class="language-python">#!/usr/bin/env python3
&quot;&quot;&quot;Read ARP and MAC address tables from routers and switches over SNMP.

Writes arp.csv (IP -&gt; MAC per router) and fdb.csv (MAC -&gt; switch port per switch).
Needs Net-SNMP&apos;s snmpbulkwalk on PATH and read-only SNMP access to each device.
The community string comes from the SNMP_COMMUNITY environment variable so it
stays out of scripts and shell history. It is still visible in the process list
while snmpbulkwalk runs, so run this on a host only you can log in to.
&quot;&quot;&quot;
import argparse
import csv
import os
import subprocess
import sys

ARP_PHYS = &quot;.1.3.6.1.2.1.4.22.1.2&quot;        # IP-MIB ipNetToMediaPhysAddress
FDB_PORT = &quot;.1.3.6.1.2.1.17.4.3.1.2&quot;      # BRIDGE-MIB dot1dTpFdbPort
FDB_STATUS = &quot;.1.3.6.1.2.1.17.4.3.1.3&quot;    # BRIDGE-MIB dot1dTpFdbStatus
BASE_PORT_IFINDEX = &quot;.1.3.6.1.2.1.17.1.4.1.2&quot;  # BRIDGE-MIB dot1dBasePortIfIndex
IF_NAME = &quot;.1.3.6.1.2.1.31.1.1.1.1&quot;       # IF-MIB ifName
FDB_STATUS_NAMES = {&quot;1&quot;: &quot;other&quot;, &quot;2&quot;: &quot;invalid&quot;, &quot;3&quot;: &quot;learned&quot;, &quot;4&quot;: &quot;self&quot;, &quot;5&quot;: &quot;mgmt&quot;}


def walk(host, community, oid, hex_strings=False):
    &quot;&quot;&quot;Return [(index_suffix, value)] for every row under oid.&quot;&quot;&quot;
    fmt = &quot;-Onqeb&quot; + (&quot;x&quot; if hex_strings else &quot;&quot;)
    cmd = [&quot;snmpbulkwalk&quot;, &quot;-v2c&quot;, &quot;-c&quot;, community, &quot;-t&quot;, &quot;2&quot;, &quot;-r&quot;, &quot;1&quot;, fmt, host, oid]
    result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
    if result.returncode != 0:
        print(f&quot;warning: {host} {oid}: {result.stderr.strip()}&quot;, file=sys.stderr)
        return []
    rows = []
    for line in result.stdout.splitlines():
        if not line.startswith(oid + &quot;.&quot;):
            continue  # &quot;No Such Object&quot; and similar end-of-table lines
        name, _, value = line.partition(&quot; &quot;)
        rows.append((name[len(oid) + 1:], value.strip().strip(&apos;&quot;&apos;)))
    return rows


def hex_to_mac(value):
    octets = value.replace(&quot;:&quot;, &quot; &quot;).split()
    if len(octets) != 6:
        return None
    return &quot;:&quot;.join(o.lower().zfill(2) for o in octets)


def collect_arp(host, community):
    rows = []
    for index, value in walk(host, community, ARP_PHYS, hex_strings=True):
        parts = index.split(&quot;.&quot;)
        if len(parts) != 5:
            continue
        mac = hex_to_mac(value)
        if mac:
            rows.append({&quot;router&quot;: host, &quot;ifindex&quot;: parts[0], &quot;ip&quot;: &quot;.&quot;.join(parts[1:]), &quot;mac&quot;: mac})
    return rows


def collect_fdb(host, community, vlans):
    if_names = dict(walk(host, community, IF_NAME))
    rows = []
    # Cisco Catalyst keeps one BRIDGE-MIB instance per VLAN, reached with community@vlan.
    contexts = [(community + &quot;@&quot; + v, v) for v in vlans] if vlans else [(community, &quot;&quot;)]
    for ctx_community, vlan in contexts:
        port_ifindex = dict(walk(host, ctx_community, BASE_PORT_IFINDEX))
        status = dict(walk(host, ctx_community, FDB_STATUS))
        for index, port in walk(host, ctx_community, FDB_PORT):
            octets = index.split(&quot;.&quot;)
            if len(octets) != 6 or port == &quot;0&quot;:
                continue
            ifindex = port_ifindex.get(port, &quot;&quot;)
            rows.append({
                &quot;switch&quot;: host,
                &quot;vlan&quot;: vlan,
                &quot;mac&quot;: &quot;:&quot;.join(f&quot;{int(o):02x}&quot; for o in octets),
                &quot;bridge_port&quot;: port,
                &quot;port_name&quot;: if_names.get(ifindex, &quot;&quot;),
                &quot;status&quot;: FDB_STATUS_NAMES.get(status.get(index, &quot;&quot;), &quot;&quot;),
            })
    return rows


def write_csv(path, rows, fields):
    with open(path, &quot;w&quot;, newline=&quot;&quot;) as handle:
        writer = csv.DictWriter(handle, fieldnames=fields)
        writer.writeheader()
        writer.writerows(rows)


def main():
    parser = argparse.ArgumentParser(description=&quot;Read ARP and MAC address tables from routers and switches over SNMP.&quot;)
    parser.add_argument(&quot;--routers&quot;, nargs=&quot;*&quot;, default=[], help=&quot;Layer 3 devices to read ARP tables from&quot;)
    parser.add_argument(&quot;--switches&quot;, nargs=&quot;*&quot;, default=[], help=&quot;Switches to read MAC address tables from&quot;)
    parser.add_argument(&quot;--vlans&quot;, nargs=&quot;*&quot;, default=[], help=&quot;VLAN IDs for Cisco community@vlan indexing&quot;)
    parser.add_argument(&quot;--out&quot;, default=&quot;.&quot;, help=&quot;Output directory&quot;)
    args = parser.parse_args()

    community = os.environ.get(&quot;SNMP_COMMUNITY&quot;)
    if not community:
        sys.exit(&quot;Set SNMP_COMMUNITY to a read-only community string.&quot;)

    os.makedirs(args.out, exist_ok=True)
    arp = [row for host in args.routers for row in collect_arp(host, community)]
    fdb = [row for host in args.switches for row in collect_fdb(host, community, args.vlans)]
    write_csv(os.path.join(args.out, &quot;arp.csv&quot;), arp, [&quot;router&quot;, &quot;ifindex&quot;, &quot;ip&quot;, &quot;mac&quot;])
    write_csv(os.path.join(args.out, &quot;fdb.csv&quot;), fdb, [&quot;switch&quot;, &quot;vlan&quot;, &quot;mac&quot;, &quot;bridge_port&quot;, &quot;port_name&quot;, &quot;status&quot;])
    print(f&quot;{len(arp)} ARP entries, {len(fdb)} MAC table entries&quot;)


if __name__ == &quot;__main__&quot;:
    main()
</code></pre>
<pre><code class="language-bash">export SNMP_COMMUNITY=&apos;read-only-string&apos;
python3 snmp_collect.py --routers 10.0.0.1 10.20.0.1 \
    --switches 10.0.0.11 10.0.0.12 --vlans 1 10 20 30 --out /srv/discovery/2026-07-15
</code></pre>
<h2>Build the Inventory Before the Diagram</h2>
<p>The instinct is to open a drawing tool immediately, because a diagram feels like real progress. I have learned to resist that until there is a structured inventory: every discovered device with its IP, MAC, switch port, VLAN, and whatever role can be inferred from its hostname or services. A diagram built directly from a spreadsheet like that is trustworthy in a way that a diagram built from someone&apos;s best recollection during a meeting is not, and updating a spreadsheet row is far less friction than redrawing a canvas every time discovery turns up something new.</p>
<p>The merge script builds that spreadsheet. Two details in it matter:</p>
<ul><li><strong>Uplinks.</strong> A switch learns every downstream MAC on its uplink and trunk ports, so the same MAC appears on several switches. The script treats any port that learned more than <code>--uplink-threshold</code> MACs (default 5) as an uplink and keeps the port with the fewest MACs as the device&apos;s real access port. That&apos;s a heuristic: raise the threshold for ports that feed an unmanaged switch or a desk hub, and check the result against a couple of known devices.</li>
<li><strong>Gaps.</strong> An IP that answered ARP but has no DHCP lease and no AD account is a statically addressed device nobody wrote down: a printer, a UPS card, a camera, an old appliance. Those go to <code>gaps.txt</code>, and they&apos;re the only thing the active scan in the next step touches.</li>
</ul>
<pre><code class="language-python">#!/usr/bin/env python3
&quot;&quot;&quot;Merge passive discovery exports into one inventory keyed by MAC address.

Inputs (any may be missing): arp.csv and fdb.csv from snmp_collect.py,
dhcp-leases.csv and ad-computers.csv from Export-PassiveInventory.ps1, and
optionally an nmap XML file from the scoped active scan.
Outputs inventory.csv, plus gaps.txt: IPs that answer ARP but have no DHCP
lease and no AD computer account, which is the short list worth scanning.
&quot;&quot;&quot;
import argparse
import csv
import ipaddress
import os
import xml.etree.ElementTree as ET
from collections import Counter, defaultdict


def read_csv(path):
    if not os.path.exists(path):
        return []
    with open(path, newline=&quot;&quot;, encoding=&quot;utf-8-sig&quot;) as handle:
        return list(csv.DictReader(handle))


def norm_mac(value):
    hexdigits = &quot;&quot;.join(c for c in (value or &quot;&quot;).lower() if c in &quot;0123456789abcdef&quot;)
    return &quot;:&quot;.join(hexdigits[i:i + 2] for i in range(0, 12, 2)) if len(hexdigits) == 12 else &quot;&quot;


def edge_ports(fdb, uplink_threshold):
    &quot;&quot;&quot;Pick the access port for each MAC, ignoring ports that learn many MACs (uplinks, trunks).&quot;&quot;&quot;
    per_port = Counter((r[&quot;switch&quot;], r[&quot;port_name&quot;] or r[&quot;bridge_port&quot;]) for r in fdb)
    best = {}
    for r in fdb:
        if r.get(&quot;status&quot;) not in (&quot;&quot;, &quot;learned&quot;):
            continue
        port = (r[&quot;switch&quot;], r[&quot;port_name&quot;] or r[&quot;bridge_port&quot;])
        count = per_port[port]
        if count &gt; uplink_threshold:
            continue
        mac = norm_mac(r[&quot;mac&quot;])
        if mac and (mac not in best or count &lt; best[mac][1]):
            best[mac] = ({&quot;switch&quot;: port[0], &quot;port&quot;: port[1], &quot;vlan&quot;: r[&quot;vlan&quot;]}, count)
    return {mac: info for mac, (info, _) in best.items()}


def read_nmap(path):
    &quot;&quot;&quot;Return {ip: {&quot;mac&quot;: ..., &quot;vendor&quot;: ..., &quot;services&quot;: &quot;22/ssh OpenSSH; ...&quot;}}.&quot;&quot;&quot;
    found = {}
    if not path:
        return found
    for host in ET.parse(path).getroot().iter(&quot;host&quot;):
        status = host.find(&quot;status&quot;)
        if status is None or status.get(&quot;state&quot;) != &quot;up&quot;:
            continue
        ip, mac, vendor = &quot;&quot;, &quot;&quot;, &quot;&quot;
        for addr in host.findall(&quot;address&quot;):
            if addr.get(&quot;addrtype&quot;) == &quot;ipv4&quot;:
                ip = addr.get(&quot;addr&quot;)
            elif addr.get(&quot;addrtype&quot;) == &quot;mac&quot;:
                mac, vendor = norm_mac(addr.get(&quot;addr&quot;)), addr.get(&quot;vendor&quot;, &quot;&quot;)
        services = []
        for port in host.iter(&quot;port&quot;):
            state = port.find(&quot;state&quot;)
            if state is None or state.get(&quot;state&quot;) != &quot;open&quot;:
                continue
            svc = port.find(&quot;service&quot;)
            label = f&apos;{port.get(&quot;portid&quot;)}/{svc.get(&quot;name&quot;, &quot;&quot;) if svc is not None else &quot;&quot;}&apos;
            product = svc.get(&quot;product&quot;, &quot;&quot;) if svc is not None else &quot;&quot;
            if product:
                label += &quot; &quot; + product
            services.append(label)
        if ip:
            found[ip] = {&quot;mac&quot;: mac, &quot;vendor&quot;: vendor, &quot;services&quot;: &quot;; &quot;.join(services)}
    return found


def main():
    parser = argparse.ArgumentParser(description=&quot;Merge passive discovery exports into one inventory keyed by MAC address.&quot;)
    parser.add_argument(&quot;--dir&quot;, default=&quot;.&quot;, help=&quot;Folder holding the exports&quot;)
    parser.add_argument(&quot;--nmap&quot;, help=&quot;nmap -oX file from the scoped scan&quot;)
    parser.add_argument(&quot;--uplink-threshold&quot;, type=int, default=5,
                        help=&quot;Ports that learned more MACs than this are treated as uplinks&quot;)
    args = parser.parse_args()
    path = lambda name: os.path.join(args.dir, name)

    inv = defaultdict(lambda: defaultdict(str))
    sources = defaultdict(set)

    for r in read_csv(path(&quot;arp.csv&quot;)):
        mac = norm_mac(r[&quot;mac&quot;])
        if mac:
            inv[mac][&quot;ip&quot;] = inv[mac][&quot;ip&quot;] or r[&quot;ip&quot;]
            sources[mac].add(&quot;arp&quot;)

    for r in read_csv(path(&quot;dhcp-leases.csv&quot;)):
        mac = norm_mac(r[&quot;ClientId&quot;])
        if not mac:
            continue
        inv[mac][&quot;hostname&quot;] = inv[mac][&quot;hostname&quot;] or r[&quot;HostName&quot;]
        if r.get(&quot;AddressState&quot;, &quot;&quot;).startswith(&quot;Active&quot;):
            inv[mac][&quot;ip&quot;] = inv[mac][&quot;ip&quot;] or r[&quot;IPAddress&quot;]
            sources[mac].add(&quot;dhcp&quot;)
        else:
            sources[mac].add(&quot;dhcp-history&quot;)  # expired, declined or offered: seen once, not proof it is here now

    for mac, port in edge_ports(read_csv(path(&quot;fdb.csv&quot;)), args.uplink_threshold).items():
        inv[mac].update(port)
        sources[mac].add(&quot;switch&quot;)

    ip_to_mac = {row[&quot;ip&quot;]: mac for mac, row in inv.items() if row[&quot;ip&quot;]}
    ad_ips = set()
    for r in read_csv(path(&quot;ad-computers.csv&quot;)):
        ip = r.get(&quot;IPv4Address&quot;, &quot;&quot;)
        if ip:
            ad_ips.add(ip)
        mac = ip_to_mac.get(ip)
        if mac:
            inv[mac][&quot;ad_name&quot;] = r[&quot;Name&quot;]
            inv[mac][&quot;os&quot;] = r.get(&quot;OperatingSystem&quot;, &quot;&quot;)
            sources[mac].add(&quot;ad&quot;)

    for ip, hit in read_nmap(args.nmap).items():
        mac = hit[&quot;mac&quot;] or ip_to_mac.get(ip) or f&quot;ip:{ip}&quot;
        inv[mac][&quot;ip&quot;] = inv[mac][&quot;ip&quot;] or ip
        inv[mac][&quot;vendor&quot;] = hit[&quot;vendor&quot;]
        inv[mac][&quot;services&quot;] = hit[&quot;services&quot;]
        sources[mac].add(&quot;nmap&quot;)

    fields = [&quot;mac&quot;, &quot;ip&quot;, &quot;hostname&quot;, &quot;ad_name&quot;, &quot;os&quot;, &quot;vendor&quot;, &quot;switch&quot;, &quot;port&quot;, &quot;vlan&quot;, &quot;services&quot;, &quot;sources&quot;]
    with open(path(&quot;inventory.csv&quot;), &quot;w&quot;, newline=&quot;&quot;) as handle:
        writer = csv.DictWriter(handle, fieldnames=fields)
        writer.writeheader()
        for mac in sorted(inv, key=lambda m: ipaddress.ip_address(inv[m][&quot;ip&quot;] or &quot;0.0.0.0&quot;)):
            writer.writerow({&quot;mac&quot;: mac, **{f: inv[mac][f] for f in fields[1:-1]}, &quot;sources&quot;: &quot;+&quot;.join(sorted(sources[mac]))})

    gaps = sorted({row[&quot;ip&quot;] for mac, row in inv.items()
                   if row[&quot;ip&quot;] and &quot;arp&quot; in sources[mac] and &quot;dhcp&quot; not in sources[mac] and row[&quot;ip&quot;] not in ad_ips}, key=ipaddress.ip_address)
    with open(path(&quot;gaps.txt&quot;), &quot;w&quot;) as handle:
        handle.write(&quot;\n&quot;.join(gaps) + (&quot;\n&quot; if gaps else &quot;&quot;))
    print(f&quot;{len(inv)} devices in inventory.csv, {len(gaps)} unexplained IPs in gaps.txt&quot;)


if __name__ == &quot;__main__&quot;:
    main()
</code></pre>
<p>The output looks like this:</p>
<pre><code class="language-text">mac,ip,hostname,ad_name,os,vendor,switch,port,vlan,services,sources
00:50:56:ab:cd:01,10.0.0.1,,,,,,,,,arp
00:50:56:ab:cd:20,10.0.0.20,WS-ACCT-07.corp.example,WS-ACCT-07,Windows 11 Enterprise,,sw1,Gi1/0/1,10,,ad+arp+dhcp+switch
b0:7b:25:00:00:30,10.0.0.30,,,,Dell,sw1,Gi1/0/48,10,443/https lighttpd,arp+nmap+switch
</code></pre>
<p>The <code>sources</code> column is the useful part. A row with <code>ad+arp+dhcp+switch</code> is fully explained. A row with only <code>arp</code> is a question for the people who run the place.</p>
<h2>Passive Before Active</h2>
<p>I run passive discovery first, before anything that actively probes the network. An undocumented environment is exactly the kind of place where an aggressive subnet-wide scan finds a piece of ancient building-management or industrial gear that falls over the moment something unexpected talks to it. Nmap&apos;s own documentation makes the relevant point: crashes are rare with the default timing, and &quot;omitting version detection is far more effective than playing with timing values at reducing these problems.&quot; So the active step is narrow on purpose: only the addresses in <code>gaps.txt</code>, with anything known to be fragile excluded, and version detection kept light.</p>
<pre><code class="language-bash">#!/usr/bin/env bash
# Scoped active pass: only the addresses passive discovery could not explain.
set -euo pipefail
DIR=/srv/discovery/2026-07-15

# fragile.txt: one address or range per line (PLCs, BMS controllers, old UPS cards).
touch &quot;$DIR/fragile.txt&quot;

# 1. Confirm which gap addresses are alive. On a local Ethernet segment nmap uses ARP for this.
nmap -sn -iL &quot;$DIR/gaps.txt&quot; --excludefile &quot;$DIR/fragile.txt&quot; -oX &quot;$DIR/ping.xml&quot;

# 2. Light service detection on the top 100 ports, rate-capped.
nmap -sV --version-light --top-ports 100 -T3 --max-rate 100 \
    -iL &quot;$DIR/gaps.txt&quot; --excludefile &quot;$DIR/fragile.txt&quot; -oX &quot;$DIR/services.xml&quot;

# 3. Fold the results back into the inventory.
python3 merge_inventory.py --dir &quot;$DIR&quot; --nmap &quot;$DIR/services.xml&quot;
</code></pre>
<p><code>-sn</code> does host discovery only, with no port scan. <code>-iL</code> reads targets from a file and <code>--excludefile</code> removes addresses from any range you give it. <code>--version-light</code> is shorthand for <code>--version-intensity 2</code>, faster and a little less likely to identify a service than the default intensity of 7. <code>--max-rate 100</code> caps sending at 100 packets per second. <code>-oX</code> writes the XML the merge script parses: each <code>&lt;host&gt;</code> has <code>&lt;address addrtype=&quot;ipv4&quot;&gt;</code> and, on a local segment, <code>&lt;address addrtype=&quot;mac&quot; vendor=&quot;…&quot;&gt;</code>, and each open <code>&lt;port&gt;</code> carries a <code>&lt;service name product version&gt;</code>. Run nmap as root (or with raw-socket capability) so it can use ARP and SYN probes.</p>
<p>For deeper per-device fingerprinting of what&apos;s left, the <a href="https://www.techcolumnist.com/2026/01/07/python-discovery-fingerprint-every-device-on-a-subnet/">subnet fingerprinting script</a> adds vendor lookups, SSH banners and HTTP <code>Server</code> headers, and the <a href="https://www.techcolumnist.com/2026/02/11/node-js-discovery-scanning-a-subnet-for-open-rdp-and-ssh/">RDP and SSH scanner</a> answers the narrower &quot;where can someone log in remotely&quot; question.</p>
<h2>Interview People to Fill Gaps, Not to Start the Picture</h2>
<p>Once discovery has done as much as it can on its own, that is when I bring in the people who have been running the place. But the conversation changes completely when you show up with &quot;here is what I found, help me understand these three things I could not resolve on my own&quot; instead of &quot;tell me what you remember about the network.&quot; The first version respects their time and gets specific, useful answers. The second version puts someone on the spot to reconstruct years of undocumented decisions from memory, and the gaps in what they say get treated as gaps in the network rather than gaps in recall.</p>
<p>In practice the interview sheet is just the inventory filtered to rows whose <code>sources</code> column lacks <code>dhcp</code> and <code>ad</code>, sorted by switch and port, so someone can walk to the closet with it:</p>
<pre><code class="language-bash">python3 - &lt;&lt;&apos;EOF&apos;
import csv
rows = [r for r in csv.DictReader(open(&quot;/srv/discovery/2026-07-15/inventory.csv&quot;))
        if not {&quot;dhcp&quot;, &quot;ad&quot;} &amp; set(r[&quot;sources&quot;].split(&quot;+&quot;))]
for r in sorted(rows, key=lambda r: (r[&quot;switch&quot;], r[&quot;port&quot;])):
    print(f&apos;{r[&quot;switch&quot;]:&lt;12} {r[&quot;port&quot;]:&lt;12} {r[&quot;ip&quot;]:&lt;15} {r[&quot;mac&quot;]}  {r[&quot;vendor&quot;]}  {r[&quot;services&quot;]}&apos;)
EOF
</code></pre>
<h2>Documentation That Outlives the Discovery Effort</h2>
<p>The point of doing this discovery-first is not just to produce one good diagram, it is to leave behind a process that can be re-run. I hand off the inventory and the scripts that built it, not just a static drawing, so that six months later when something has inevitably changed, the next person does not have to start from zero and a stale document again. An undocumented network usually got that way because documentation was treated as a one-time deliverable instead of a habit; discovery-first work only pays off long term if it becomes the habit, not the exception.</p>
<p>Making it a habit is mostly scheduling. A weekly run into a dated folder, committed to a Git repository, turns <code>git diff</code> into a change report:</p>
<pre><code class="language-bash"># /etc/cron.d/discovery: Sundays 02:00, passive collection only
0 2 * * 0 discovery /srv/discovery/run-weekly.sh &gt;&gt; /var/log/discovery.log 2&gt;&amp;1
</code></pre>
<pre><code class="language-bash">#!/usr/bin/env bash
# /srv/discovery/run-weekly.sh
set -euo pipefail
. /srv/discovery/env   # exports SNMP_COMMUNITY, ROUTERS, SWITCHES, VLANS (mode 600)
DIR=/srv/discovery/$(date +%F)
mkdir -p &quot;$DIR&quot;
cp /srv/discovery/latest/dhcp-leases.csv /srv/discovery/latest/ad-computers.csv &quot;$DIR&quot;/ 2&gt;/dev/null || true
python3 /srv/discovery/snmp_collect.py --routers $ROUTERS --switches $SWITCHES --vlans $VLANS --out &quot;$DIR&quot;
python3 /srv/discovery/merge_inventory.py --dir &quot;$DIR&quot;
ln -sfn &quot;$DIR&quot; /srv/discovery/latest
cd /srv/discovery
# env holds the community string: it is listed in .gitignore and never staged.
git add -- &quot;$DIR&quot; latest
git diff --cached --quiet || git commit -qm &quot;discovery $(date +%F)&quot;
</code></pre>
<p>The Windows half runs as a scheduled task on a management server and drops its two CSVs into the share the Linux collector reads. Keep the active nmap step out of the schedule. It stays a deliberate, scoped action someone chooses to run; to flag new hosts between those runs, <a href="https://www.techcolumnist.com/2026/03/11/node-js-discovery-diffing-two-network-scans-to-flag-new-hosts/">diff two scans</a> instead.</p>
<p>From here the inventory feeds everything else: <a href="https://www.techcolumnist.com/2025/12/10/python-discovery-inventory-vmware-hosts-and-vms-via-pyvmomi/">VMware inventory</a> for the virtual side, <a href="https://www.techcolumnist.com/2026/01/28/python-discovery-crawling-dns-zones-for-orphaned-records/">orphaned DNS records</a> cross-checked against live IPs, a <a href="https://www.techcolumnist.com/2026/09/02/windows-management-building-a-discovery-inventory-nobody-has-to-maintain-by-hand/">Windows inventory that maintains itself</a>, and <a href="https://www.techcolumnist.com/2025/08/20/powershell-connectwise-sync-configuration-items-from-discovery-scans/">ConnectWise configuration items</a> synced from the results so the PSA matches reality.</p>
<h2>References</h2>
<ul><li><a href="https://learn.microsoft.com/en-us/powershell/module/dhcpserver/get-dhcpserverv4lease">Get-DhcpServerv4Lease</a> (Microsoft Learn)</li>
<li><a href="https://learn.microsoft.com/en-us/powershell/module/activedirectory/get-adcomputer">Get-ADComputer</a> (Microsoft Learn)</li>
<li><a href="https://www.rfc-editor.org/rfc/rfc4188">RFC 4188: Definitions of Managed Objects for Bridges</a> (BRIDGE-MIB)</li>
<li><a href="https://www.rfc-editor.org/rfc/rfc4293">RFC 4293: Management Information Base for the Internet Protocol</a> (IP-MIB)</li>
<li><a href="https://www.rfc-editor.org/rfc/rfc1213">RFC 1213: MIB-II</a> (<code>ipNetToMediaTable</code>)</li>
<li><a href="https://www.cisco.com/c/en/us/support/docs/ip/simple-network-management-protocol-snmp/40367-camsnmp40367.html">Use SNMP to obtain the CAM table on Catalyst switches</a> (Cisco, community string indexing)</li>
<li><a href="https://www.net-snmp.org/docs/man/snmpcmd.html">Net-SNMP snmpcmd options</a></li>
<li>Nmap reference guide: <a href="https://nmap.org/book/man-host-discovery.html">host discovery</a>, <a href="https://nmap.org/book/man-target-specification.html">target specification</a>, <a href="https://nmap.org/book/man-version-detection.html">version detection</a>, <a href="https://nmap.org/book/man-performance.html">timing and performance</a>, <a href="https://nmap.org/book/output-formats-xml-output.html">XML output</a></li>
</ul>
]]></content:encoded>
      <category>Engineering</category>
      <category>Strategy</category>
    </item>
    <item>
      <title>Kubernetes: Running Talos Alongside a Legacy Hyper-V Estate</title>
      <link>https://www.techcolumnist.com/2026/07/08/kubernetes-running-talos-alongside-a-legacy-hyper-v-estate/</link>
      <guid isPermaLink="true">https://www.techcolumnist.com/2026/07/08/kubernetes-running-talos-alongside-a-legacy-hyper-v-estate/</guid>
      <pubDate>Wed, 08 Jul 2026 14:00:00 GMT</pubDate>
      <dc:creator>Tom Lasswell</dc:creator>
      <description>Introducing a Talos Kubernetes cluster into an existing Hyper-V estate: VM build script, Image Factory schematic, VLAN, VIP, firewall and storage boundaries.</description>
      <content:encoded><![CDATA[<p>Most of the Kubernetes-on-Hyper-V advice I&apos;ve read assumes you&apos;re starting from a clean slate or migrating everything to a new hypervisor. Neither describes reality when you&apos;re supporting a Windows estate that has years of Hyper-V clusters, System Center tooling, and operational habits built around VMM and Failover Clustering. Ripping that out to make room for Kubernetes was never on the table. What worked was treating Talos Linux as just another guest OS on the existing Hyper-V hosts, and being deliberate about where the two worlds have to touch.</p>
<p>Everything here is written against Talos 1.14. Hyper-V is on Talos&apos; list of supported virtualized platforms, and there&apos;s a Hyper-V page in the Talos docs, but it&apos;s a lab walkthrough built on a community PowerShell module. What follows is how I turned that into something that fits a managed estate.</p>
<h2>Talos as a guest, not a replacement</h2>
<p>Talos ships as an ISO from the Image Factory, and as far as Talos is concerned Hyper-V is an ordinary hypervisor: the VM boots into maintenance mode, gets a machine config applied over the network, and comes up as an immutable, API-managed node with no SSH and no package manager to drift. The settings that took adjustment were on the Hyper-V side, and once they were captured in a script, a new node became a five-minute task instead of a bespoke one.</p>
<p>First, the image. I build a schematic that adds the official <code>hyperv-guest-agent</code> system extension, which provides the Hyper-V KVP daemon (it reports the guest&apos;s IP, hostname and OS to the host, so <code>Get-VMNetworkAdapter</code> shows the address) and the VSS daemon:</p>
<pre><code class="language-yaml"># schematic.yaml
customization:
  systemExtensions:
    officialExtensions:
      - siderolabs/hyperv-guest-agent
</code></pre>
<pre><code class="language-bash">curl -X POST --data-binary @schematic.yaml https://factory.talos.dev/schematics
# {&quot;id&quot;:&quot;&lt;schematic-id&gt;&quot;,&quot;schematic&quot;:&quot;customization:\n    systemExtensions: ...&quot;}

SCHEMATIC_ID=&quot;&lt;schematic-id&gt;&quot;   # the id from the response

# ISO for the VMs, and the installer image the machine config must reference
curl -LO &quot;https://factory.talos.dev/image/${SCHEMATIC_ID}/v1.14.0/metal-amd64.iso&quot;
echo &quot;factory.talos.dev/metal-installer/${SCHEMATIC_ID}:v1.14.0&quot;
</code></pre>
<p>Schematics are content-addressed, so the same YAML always yields the same ID. Keep that ID with the cluster&apos;s patches: from Talos 1.14 on, installer images come from the Image Factory, and every future <code>talosctl upgrade</code> has to reference the same schematic or the node loses its extensions.</p>
<p>Then the VM. The shape follows what the module linked from the Talos Hyper-V guide does (Generation 2, Secure Boot off, ISO as the first boot device) plus the settings a shared estate needs:</p>
<ul><li><strong>Secure Boot off.</strong> The standard Talos ISO isn&apos;t a SecureBoot image; Talos publishes separate <code>-secureboot</code> assets signed with Sidero Labs&apos; own key, and enrolling that key requires the firmware to be in setup mode. The Talos docs don&apos;t cover doing that on Hyper-V, so I don&apos;t half-configure it: Secure Boot is explicitly off.</li>
<li><strong>A static MAC per VM</strong>, from a range reserved for the cluster. Talos can then match the NIC by MAC with a <code>LinkAliasConfig</code> instead of trusting interface naming, and the network team&apos;s reservations never go stale.</li>
<li><strong>An access-mode VLAN</strong> on the vNIC, so the node lands on the cluster VLAN with no tagging inside the guest.</li>
<li><strong>Static memory and no checkpoints.</strong> Rolling an etcd member&apos;s disk back to an older point in time is never what you want, and I&apos;d rather Kubernetes see a fixed memory size than a balloon.</li>
<li><strong>Sizing from Talos&apos; system requirements.</strong> Control plane nodes get at least the recommended 4 cores, 4 GiB and 100 GiB. Talos&apos; amd64 images also require a CPU that exposes the x86-64-v2 microarchitecture level; a VM below that level halts at boot with a message saying so.</li>
</ul>
<p>This script builds the VM and writes the node&apos;s Talos patch at the same time, so the MAC in the config is the MAC on the VM:</p>
<pre><code class="language-powershell">#Requires -Modules Hyper-V
#Requires -RunAsAdministrator
&lt;#
.SYNOPSIS
    Creates a Talos Linux VM on a Hyper-V host and writes its Talos node patch.

.DESCRIPTION
    Builds a Generation 2 VM with Secure Boot off, a static MAC address, an
    access-mode VLAN, static memory, checkpoints disabled and the Talos ISO as
    the first boot device. Writes patches/nodes/&lt;Name&gt;.yaml with a hostname,
    a link alias pinned to the static MAC, and the node&apos;s static address, so
    the Talos config matches the VM without anyone copying MACs by hand.
    Run it on the Hyper-V host (or a cluster node that owns the storage path).

.PARAMETER Name
    VM name and Talos hostname, for example talos-cp1.

.PARAMETER IPAddress
    Static address in CIDR form, for example 10.20.30.11/24.

.PARAMETER Gateway
    Default gateway for the node.

.PARAMETER StaticMacAddress
    MAC address without separators, for example 00155D1E1E0B. Keep it inside
    a range your DHCP and IPAM teams have reserved for the cluster.

.PARAMETER SwitchName
    External virtual switch the cluster VLAN is trunked to.

.PARAMETER VlanId
    Access VLAN for the Talos node NIC.

.PARAMETER IsoPath
    Path to the Talos ISO (from the Image Factory schematic) on the host.

.PARAMETER VMPath
    Folder for the VM configuration and its VHDX files.

.PARAMETER ProcessorCount
    Virtual processors. Talos recommends 4 for control plane nodes.

.PARAMETER MemoryBytes
    Static memory. Talos recommends 4 GiB for control plane nodes; the 8 GB
    default leaves room for workloads on nodes that also run pods.

.PARAMETER OsDiskBytes
    System disk size. Talos recommends 100 GiB.

.PARAMETER DataDiskBytes
    Optional second VHDX for workload storage (for example a CSI backend).

.PARAMETER PatchDirectory
    Where to write the node patch. Defaults to .\patches\nodes.

.EXAMPLE
    .\New-TalosHyperVNode.ps1 -Name talos-cp1 -IPAddress 10.20.30.11/24 -Gateway 10.20.30.1 -StaticMacAddress 00155D1E1E0B -SwitchName vSwitch-Trunk -VlanId 230 -IsoPath C:\ISO\talos-hyperv-amd64.iso -VMPath C:\ClusterStorage\Volume1\Talos
#&gt;
[CmdletBinding(SupportsShouldProcess)]
param(
    [Parameter(Mandatory)] [string] $Name,
    [Parameter(Mandatory)] [ValidatePattern(&apos;^\d{1,3}(\.\d{1,3}){3}/\d{1,2}$&apos;)] [string] $IPAddress,
    [Parameter(Mandatory)] [string] $Gateway,
    [Parameter(Mandatory)] [ValidatePattern(&apos;^[0-9A-Fa-f]{12}$&apos;)] [string] $StaticMacAddress,
    [Parameter(Mandatory)] [string] $SwitchName,
    [Parameter(Mandatory)] [ValidateRange(1, 4094)] [int] $VlanId,
    [Parameter(Mandatory)] [string] $IsoPath,
    [Parameter(Mandatory)] [string] $VMPath,
    [int] $ProcessorCount = 4,
    [long] $MemoryBytes = 8GB,
    [long] $OsDiskBytes = 100GB,
    [long] $DataDiskBytes = 0,
    [string] $PatchDirectory = (Join-Path -Path (Get-Location) -ChildPath &apos;patches\nodes&apos;)
)

$ErrorActionPreference = &apos;Stop&apos;

if (Get-VM -Name $Name -ErrorAction SilentlyContinue) {
    throw &quot;A VM named $Name already exists on this host.&quot;
}

$vhdFolder = Join-Path -Path $VMPath -ChildPath &quot;$Name\Virtual Hard Disks&quot;
$osDiskPath = Join-Path -Path $vhdFolder -ChildPath &quot;$Name-os.vhdx&quot;

if ($PSCmdlet.ShouldProcess($Name, &apos;Create Talos VM&apos;)) {
    New-Item -Path $vhdFolder -ItemType Directory -Force | Out-Null

    New-VM -Name $Name -Generation 2 -MemoryStartupBytes $MemoryBytes -NewVHDPath $osDiskPath `
        -NewVHDSizeBytes $OsDiskBytes -SwitchName $SwitchName -Path $VMPath | Out-Null

    # Fixed CPU and memory, and no checkpoints: reverting an etcd member or a
    # node&apos;s disk to an older point in time is never what you want.
    Set-VM -Name $Name -ProcessorCount $ProcessorCount -StaticMemory -MemoryStartupBytes $MemoryBytes `
        -CheckpointType Disabled -AutomaticCheckpointsEnabled $false

    Set-VMNetworkAdapter -VMName $Name -StaticMacAddress $StaticMacAddress
    Set-VMNetworkAdapterVlan -VMName $Name -Access -VlanId $VlanId

    if ($DataDiskBytes -gt 0) {
        $dataDiskPath = Join-Path -Path $vhdFolder -ChildPath &quot;$Name-data.vhdx&quot;
        New-VHD -Path $dataDiskPath -SizeBytes $DataDiskBytes -Dynamic | Out-Null
        Add-VMHardDiskDrive -VMName $Name -Path $dataDiskPath
    }

    # The standard Talos ISO is not a SecureBoot image (Talos publishes separate
    # -secureboot assets), so Secure Boot is off, as in the Talos Hyper-V guide.
    Add-VMDvdDrive -VMName $Name -Path $IsoPath
    Set-VMFirmware -VMName $Name -EnableSecureBoot Off -FirstBootDevice (Get-VMDvdDrive -VMName $Name)
}

# Talos matches the NIC by MAC, in lowercase colon-separated form.
$macForTalos = (($StaticMacAddress.ToLower() -split &apos;(..)&apos;) -ne &apos;&apos;) -join &apos;:&apos;

$patch = @&quot;
apiVersion: v1alpha1
kind: HostnameConfig
hostname: $Name
auto: off
---
apiVersion: v1alpha1
kind: LinkAliasConfig
name: net0
selector:
  match: mac(link.permanent_addr) == &quot;$macForTalos&quot;
---
apiVersion: v1alpha1
kind: LinkConfig
name: net0
addresses:
  - address: $IPAddress
routes:
  - gateway: $Gateway
&quot;@

New-Item -Path $PatchDirectory -ItemType Directory -Force | Out-Null
$patchPath = Join-Path -Path $PatchDirectory -ChildPath &quot;$Name.yaml&quot;
# WriteAllText writes UTF-8 without a byte order mark on every PowerShell version.
[System.IO.File]::WriteAllText($patchPath, $patch)

if ($PSCmdlet.ShouldProcess($Name, &apos;Start VM&apos;)) {
    Start-VM -Name $Name
}

[pscustomobject]@{
    Name       = $Name
    MacAddress = $macForTalos
    VlanId     = $VlanId
    Address    = $IPAddress
    Patch      = $patchPath
}
</code></pre>
<p>Running it for the first control plane node looks like this:</p>
<pre><code class="language-text">Name       : talos-cp1
MacAddress : 00:15:5d:1e:1e:0b
VlanId     : 230
Address    : 10.20.30.11/24
Patch      : C:\talos\lab\patches\nodes\talos-cp1.yaml
</code></pre>
<p>After the config is applied and the node has installed itself to disk, remove the DVD drive. The Talos Hyper-V guide warns that Talos might fail to boot if the ISO stays attached:</p>
<pre><code class="language-powershell">Get-VMDvdDrive -VMName talos-cp1 | Remove-VMDvdDrive
Set-VMFirmware -VMName talos-cp1 -FirstBootDevice (Get-VMHardDiskDrive -VMName talos-cp1 -ControllerLocation 0)
</code></pre>
<p>If you already run Hyper-V failover clusters, the Talos VMs are just more cluster roles. The same placement rules that keep two domain controllers off one host apply to control plane nodes: three etcd members on one host is one host failure away from losing quorum. <a href="https://www.techcolumnist.com/2026/06/03/hyper-v-deploying-a-two-node-failover-cluster-on-a-budget/">Hyper-V: Deploying a Two-Node Failover Cluster on a Budget</a> covers the host side.</p>
<h2>Networking is where the two estates actually meet</h2>
<p>The existing estate has its own VLAN structure, its own DHCP scopes, and firewall rules built around the assumption that everything on a given VLAN is a traditional Windows or Linux VM with predictable, mostly-static behavior. Kubernetes doesn&apos;t share that assumption: pods come and go, services get new endpoints, and a CNI like Cilium makes its own routing decisions on top of whatever the physical network provides.</p>
<p>So the Talos nodes live on a dedicated VLAN (<code>10.20.30.0/24</code> in these examples), and the cluster&apos;s pod and service ranges are picked from space that isn&apos;t routed anywhere else in the estate. The shared cluster patch sets those ranges, adds a Layer 2 VIP for the Kubernetes API (the control plane nodes elect an owner through etcd, so no load balancer is needed), removes the default Flannel CNI so Cilium can be installed per Talos&apos; Cilium guide, and pins the installer image to the schematic:</p>
<pre><code class="language-yaml"># patches/controlplane.yaml
apiVersion: v1alpha1
kind: KubeNetworkConfig
podSubnets:
  - 172.28.0.0/16
serviceSubnets:
  - 172.29.0.0/16
---
apiVersion: v1alpha1
kind: KubeFlannelCNIConfig
$patch: delete
---
apiVersion: v1alpha1
kind: Layer2VIPConfig
name: 10.20.30.10
link: net0
---
apiVersion: v1alpha1
kind: UnattendedInstallConfig
installer:
  image: factory.talos.dev/metal-installer/&lt;schematic-id&gt;:v1.14.0
provisioning:
  diskSelector:
    match: disk.dev_path == &quot;/dev/sda&quot;
</code></pre>
<p>The subnet lists replace the defaults on merge rather than appending, per the patching guide, and the Flannel removal is the documented Talos 1.14 way to set the CNI to none. The VIP must come from the nodes&apos; own subnet and must not be handed out by DHCP. The VIP documentation also says not to use it as a <code>talosconfig</code> endpoint, because it disappears exactly when etcd or the API server is broken, so <code>talosctl</code> points at the three node addresses.</p>
<p>For the network team, the useful artifact isn&apos;t a Kubernetes diagram. It&apos;s the port list. Talos&apos; ingress firewall guide gives it: apid on TCP 50000, trustd on TCP 50001, the Kubernetes API on TCP 6443, etcd on TCP 2379-2380 between control plane nodes only, kubelet on TCP 10250 inside the cluster, and the CNI&apos;s VXLAN port (UDP 8472 for Cilium, 4789 for Flannel). I enforce the same thing on the nodes with Talos&apos; own ingress firewall, so the cluster doesn&apos;t depend solely on the estate&apos;s ACLs. The doc&apos;s example opens apid and the API to everyone; I narrow both to the cluster VLAN plus the management subnet the jump hosts live in:</p>
<pre><code class="language-yaml"># patches/firewall-controlplane.yaml
apiVersion: v1alpha1
kind: NetworkDefaultActionConfig
ingress: block
---
apiVersion: v1alpha1
kind: NetworkRuleConfig
name: apid-ingress
portSelector:
  ports:
    - 50000
  protocol: tcp
ingress:
  - subnet: 10.20.30.0/24
  - subnet: 10.20.0.0/24
---
apiVersion: v1alpha1
kind: NetworkRuleConfig
name: kubernetes-api-ingress
portSelector:
  ports:
    - 6443
  protocol: tcp
ingress:
  - subnet: 10.20.30.0/24
  - subnet: 10.20.0.0/24
---
apiVersion: v1alpha1
kind: NetworkRuleConfig
name: trustd-ingress
portSelector:
  ports:
    - 50001
  protocol: tcp
ingress:
  - subnet: 10.20.30.0/24
---
apiVersion: v1alpha1
kind: NetworkRuleConfig
name: kubelet-ingress
portSelector:
  ports:
    - 10250
  protocol: tcp
ingress:
  - subnet: 10.20.30.0/24
---
apiVersion: v1alpha1
kind: NetworkRuleConfig
name: etcd-ingress
portSelector:
  ports:
    - 2379-2380
  protocol: tcp
ingress:
  - subnet: 10.20.30.11/32
  - subnet: 10.20.30.12/32
  - subnet: 10.20.30.13/32
---
apiVersion: v1alpha1
kind: NetworkRuleConfig
name: cni-vxlan
portSelector:
  ports:
    - 8472
  protocol: udp
ingress:
  - subnet: 10.20.30.0/24
</code></pre>
<p>Roll a default-block firewall out with <code>--mode=try</code> first. If a rule is wrong and you lock yourself out, Talos reverts the change after the timeout instead of leaving you at the Hyper-V console of a node with no shell.</p>
<p>Ingress for applications is the one deliberate, documented crossing point between &quot;legacy VLAN&quot; and &quot;cluster network.&quot; Everything else in the estate talks to the cluster through that door rather than learning about pod IPs.</p>
<h2>Storage means picking your dependency deliberately</h2>
<p>Hyper-V&apos;s storage story (CSVs, Storage Spaces Direct, whatever SAN sits behind it) and Kubernetes&apos; storage story (CSI drivers, StorageClasses, PersistentVolumes) don&apos;t talk to each other by default. I didn&apos;t want Talos nodes depending on the same storage fabric in a way that could let a Kubernetes storage problem cascade into the Hyper-V estate or the other way round. Talos node OS disks are ordinary VHDX files on existing storage; that part is fine, it&apos;s just another VM disk. Persistent workload storage inside the cluster goes through a CSI driver with its own backend, kept operationally separate from the Hyper-V storage stack. Talos&apos; storage guide walks through the options it documents on Talos (Rook/Ceph, Longhorn, Mayastor, Piraeus/LINSTOR, SeaweedFS, and vendor drivers such as Dell PowerStore and Synology). The <code>-DataDiskBytes</code> parameter in the script exists for the replicated options that want a raw disk per node. That separation costs some duplication, but a bad day in one storage system doesn&apos;t automatically become a bad day in the other.</p>
<h2>The estate doesn&apos;t need to know Kubernetes exists</h2>
<p>The System Center and VMM tooling that manages the rest of the fleet doesn&apos;t understand Talos nodes as anything other than VMs, and I&apos;ve left it that way on purpose. Talos&apos; API and <code>talosctl</code> handle node lifecycle, upgrades and configuration; VMM&apos;s job is limited to &quot;this VM exists, is powered on, and lives on the right host,&quot; the same as any other guest. Two estate processes needed an explicit exception: patch orchestration and backup. Host patching treats the Talos VMs like any other clustered role, which is fine as long as only one host (and so at most one control plane node) is out at a time, but Talos OS upgrades go through <code>talosctl upgrade</code>, never through the Windows patch cycle. And VM-level backup of Talos nodes is the wrong unit: what you need back after a disaster is the <code>secrets.yaml</code>, the patches, and an etcd snapshot (<code>talosctl etcd snapshot</code>), not a VHDX of a node that can be rebuilt from its config in minutes. Trying to make the legacy tooling Kubernetes-aware would have meant fighting both toolchains at once. Keeping the boundary sharp let each one do the job it&apos;s actually good at.</p>
<h2>References</h2>
<ul><li><a href="https://docs.siderolabs.com/talos/v1.14/platform-specific-installations/virtualized-platforms/hyper-v">Hyper-V (Talos platform guide)</a></li>
<li><a href="https://docs.siderolabs.com/talos/v1.14/learn-more/image-factory">Image Factory</a> and <a href="https://docs.siderolabs.com/talos/v1.14/configure-your-talos-cluster/lifecycle-management/upgrading-talos">Upgrading Talos Linux</a> (Factory installer images from 1.14)</li>
<li><a href="https://docs.siderolabs.com/talos/v1.14/platform-specific-installations/bare-metal-platforms/secureboot">SecureBoot</a></li>
<li><a href="https://docs.siderolabs.com/talos/v1.14/getting-started/system-requirements">System Requirements</a></li>
<li><a href="https://docs.siderolabs.com/talos/v1.14/networking/advanced/vip">Virtual (shared) IP</a> and <a href="https://docs.siderolabs.com/talos/v1.14/networking/configuration/aliases">Link Aliases</a></li>
<li><a href="https://docs.siderolabs.com/talos/v1.14/networking/ingress-firewall">Ingress Firewall</a></li>
<li><a href="https://docs.siderolabs.com/kubernetes-guides/cni/deploying-cilium">Deploy Cilium CNI</a> and <a href="https://docs.siderolabs.com/kubernetes-guides/csi/storage">Storage</a></li>
<li><a href="https://github.com/siderolabs/extensions">Siderolabs extensions catalog</a> (<code>hyperv-guest-agent</code>)</li>
<li>Microsoft Hyper-V module: <a href="https://learn.microsoft.com/en-us/powershell/module/hyper-v/new-vm">New-VM</a>, <a href="https://learn.microsoft.com/en-us/powershell/module/hyper-v/set-vm">Set-VM</a>, <a href="https://learn.microsoft.com/en-us/powershell/module/hyper-v/set-vmfirmware">Set-VMFirmware</a>, <a href="https://learn.microsoft.com/en-us/powershell/module/hyper-v/set-vmnetworkadapter">Set-VMNetworkAdapter</a></li>
</ul>
]]></content:encoded>
      <category>Engineering</category>
    </item>
    <item>
      <title>Windows Server: TCP Stack Tuning for a 10GbE Storage Network</title>
      <link>https://www.techcolumnist.com/2026/07/01/windows-server-tcp-stack-tuning-for-a-10gbe-storage-network/</link>
      <guid isPermaLink="true">https://www.techcolumnist.com/2026/07/01/windows-server-tcp-stack-tuning-for-a-10gbe-storage-network/</guid>
      <pubDate>Wed, 01 Jul 2026 14:00:00 GMT</pubDate>
      <dc:creator>Tom Lasswell</dc:creator>
      <description>Field notes on getting 10GbE-class throughput from Windows Server storage links: RSS, SMB Multichannel, autotuning, offloads, jumbo frames, and a baseline script.</description>
      <content:encoded><![CDATA[<p>A 10GbE link between a Windows Server host and an iSCSI or SMB storage target should, in theory, move a little over a gigabyte a second. In practice, the box you just cabled up will often plateau well below that, and the reflex is to blame the switch, the cabling, or the storage array before anyone looks at the host&apos;s own network stack. I&apos;ve chased that plateau enough times now to check the host first, because more often than not that&apos;s where the ceiling is. Most of the time it isn&apos;t a missing registry tweak, either. It&apos;s one of a handful of settings that Microsoft documents clearly and that have drifted from where they should be.</p>
<h2>Start with a baseline, not a setting</h2>
<p>The tuning below only matters if you know what &quot;good&quot; looks like on that specific link. I always run a raw throughput test between the two endpoints with no storage protocol in the way before touching anything, so a marginal cable or a port negotiated at the wrong speed doesn&apos;t get misdiagnosed as a stack problem three settings into a change window. Microsoft&apos;s NTTTCP tool is what I use between Windows hosts. The receiver and sender commands differ only in <code>-r</code> and <code>-s</code>. <code>-m</code> takes threads, CPU (<code>*</code> for any) and the receiver&apos;s IP; Microsoft&apos;s own guidance uses twice the receiver&apos;s core count for threads, so the <code>16</code> below is for an eight-core receiver. <code>-t</code> is the duration in seconds:</p>
<pre><code class="language-powershell"># On the receiver (the storage-side host).
ntttcp.exe -r -m 16,*,10.20.30.11 -t 60

# On the sender.
ntttcp.exe -s -m 16,*,10.20.30.11 -t 60
</code></pre>
<p>Run it once with <code>-m 1,*,&lt;ip&gt;</code> too. The gap between one thread and many is the whole story of the next section.</p>
<h2>One connection lands on one core</h2>
<p>Receive Side Scaling exists because a single CPU core can&apos;t keep up with a fast NIC. RSS hashes each incoming packet&apos;s headers and spreads different connections across cores. The key word is <em>connections</em>. Microsoft&apos;s SMB Multichannel documentation spells out the consequence for storage: with a single 10GbE adapter and one SMB session without Multichannel, &quot;SMB creates a single TCP/IP connection. With only a single CPU core, this configuration inherently leads to congestion, especially when many small I/O operations are performed,&quot; and &quot;if you use a single connection, RSS cannot help.&quot;</p>
<p>So there are two things to check, in order:</p>
<ol><li><strong>RSS is on and has cores to use.</strong> <code>Get-NetAdapterRss</code> shows <code>Enabled</code>, the <code>Profile</code> (the default is <code>NUMAStatic</code>), <code>BaseProcessorNumber</code> and <code>MaxProcessors</code>. I&apos;ve found RSS enabled at the driver level while every one of its queues was pinned to core 0, and I&apos;ve found it switched off globally (<code>Get-NetOffloadGlobalSetting</code>); &quot;enabled&quot; in the adapter properties proves neither. The full object (<code>Get-NetAdapterRss -Name &lt;adapter&gt; | Format-List -Property *</code>) shows which processors are actually in the RSS array. Microsoft&apos;s own advice on the knobs is restrained: &quot;Selecting the correct profile should be sufficient in most scenarios.&quot; Set <code>BaseProcessorNumber</code> and <code>MaxProcessors</code> only when you&apos;re deliberately dividing cores between several adapters. If Task Manager shows logical processors underused for receive traffic, the tuning guide suggests raising the number of RSS queues toward what the adapter supports.</li>
<li><strong>The storage protocol actually uses more than one connection.</strong> For SMB 3.x that&apos;s SMB Multichannel, which is on by default and, with an RSS-capable NIC, &quot;creates multiple TCP/IP connections for that particular session.&quot; Two traps: Multichannel ignores slower adapters when a faster one exists (&quot;network adapters that are the same type... and have the same speed are simultaneously used&quot;), and disabling it on either the client or the server disables it for both. For iSCSI, the equivalent is multiple sessions or connections through MPIO, which is a separate configuration on the initiator.</li>
</ol>
<p>Verify Multichannel during a long copy, not at idle:</p>
<pre><code class="language-powershell">Get-SmbClientConfiguration | Select-Object -Property EnableMultiChannel
Get-SmbClientNetworkInterface
Get-SmbMultichannelConnection
</code></pre>
<p>If Multichannel isn&apos;t selecting an interface, Microsoft&apos;s troubleshooting guide checks the obvious first: <code>ms_server</code> and <code>ms_msclient</code> bound on the adapter (<code>Get-NetAdapterBinding -ComponentID ms_server,ms_msclient</code>), the interface listed by <code>Get-SmbServerNetworkInterface</code>, the network profile not being Public, and nothing in the path blocking the SMB3 <code>NETWORK_INTERFACE_INFO</code> exchange. SMB2 and earlier don&apos;t do Multichannel at all.</p>
<h2>The TCP window is autotuned; leave it that way</h2>
<p>It&apos;s tempting to decide that small, low-latency storage I/O never gives autotuning a fair chance and to pin the window instead. I&apos;ve been down that road, and it isn&apos;t what Microsoft documents. Receive window autotuning has five levels (<code>Normal</code>, <code>Disabled</code>, <code>Restricted</code>, <code>HighlyRestricted</code>, <code>Experimental</code>) and <code>Normal</code> is the default, described as growing the window &quot;to accommodate almost all scenarios.&quot; <code>Disabled</code> is the one that hurts: the window stays at its default size, which depends on link speed (64 KB from 100 Mbps up to 10 Gbps, 128 KB at 10 Gbps and above). Microsoft&apos;s formula is throughput = window / latency, so a fixed window caps a single connection no matter how fast the wire is.</p>
<p>The other half of the story is that the old registry method is gone. Microsoft lists <code>TcpWindowSize</code>, <code>NumTcbTablePartitions</code> and <code>MaxHashTableSize</code> under <code>HKLM\System\CurrentControlSet\Services\Tcpip\Parameters</code> as &quot;no longer supported, and are ignored,&quot; and &quot;starting with Windows Server 2019, you can no longer use the registry to configure the TCP receive window size.&quot; If a tuning guide tells you to create those values, it was written for Windows Server 2003. Check and set autotuning with the supported tools:</p>
<pre><code class="language-powershell">Get-NetTCPSetting | Select-Object -Property SettingName, AutoTuningLevelLocal, CongestionProvider
Set-NetTCPSetting -AutoTuningLevelLocal Normal
</code></pre>
<p>Same for congestion control: since Windows Server 2019, the Internet, Datacenter and Custom templates use CUBIC (Compat stays on NewReno). <code>DCTCP</code> is only worth considering when the switches mark ECN end to end, which is a fabric project, not a host setting.</p>
<h2>Offloads help until one of them doesn&apos;t</h2>
<p>Checksum offload, Large Send Offload and Receive Segment Coalescing reduce CPU cost per byte by pushing work onto the NIC, which matters at 10GbE rates. Microsoft&apos;s guidance: &quot;Enabling network adapter offload features is usually beneficial,&quot; with the caveat that a NIC without enough hardware resources can sustain <em>less</em> throughput with segmentation offload on. The two offloads Microsoft says not to use at all are TCP Chimney Offload and IPsec Task Offload: &quot;deprecated in Windows Server 2016, and might adversely affect server and networking performance.&quot; If you see Chimney in an old tuning checklist, that checklist predates Server 2016.</p>
<p>RSC deserves a specific check because it can be enabled and still not be working. <code>Get-NetAdapterRsc</code> reports <code>IPv4OperationalState</code> and, if it&apos;s off, <code>IPv4FailureReason</code>: documented reasons include a Windows Filtering Platform filter in the path (<code>WFPCompatibility</code>), an old driver (<code>NDISCompatibility</code>), IP forwarding being on (<code>ForwardingEnabled</code>), or RSC disabled globally (<code>NetOffloadGlobalDisabled</code>). WFP is the one that surprises people: the tuning guide warns that &quot;a poorly written WFP filter can significantly decrease a server&apos;s networking performance,&quot; and firewall and antivirus products are the usual source.</p>
<p>The catch with offloads is the NIC doing the work. Microsoft&apos;s <a href="https://learn.microsoft.com/en-us/windows-server/networking/technologies/network-subsystem/net-sub-performance-tuning-nics#offload-features">network adapter tuning guide</a> only goes as far as the resource caveat above (&quot;the network adapter might not be powerful enough to handle the offload capabilities with high throughput&quot;); it says nothing about firmware bugs. In my experience, though, offload bugs in NIC firmware and drivers turn up often enough that &quot;disable offloads and see if it gets faster&quot; is a legitimate diagnostic step, not folklore. I&apos;ve hit at least one NIC generation where LSO corrupted iSCSI frames under sustained load in a way that only showed up as intermittent retransmits, not outright failures, the kind of problem that survives a quick smoke test. That&apos;s why the baseline script below records the retransmit rate.</p>
<h2>Jumbo frames only pay off end to end</h2>
<p>Enabling 9000-byte jumbo frames on the server NIC without confirming every switch port and the storage target&apos;s NIC match doesn&apos;t just fail to help. The oversized frames get dropped or fragmented, which looks like intermittent packet loss under load rather than a configuration mismatch. On Windows, set it with the standardized driver keyword rather than a vendor display name. <code>*JumboPacket</code> is defined as the largest frame the hardware supports, counted including the Ethernet header, with a default of 1514 (a 1500-byte MTU), so a 9000-byte MTU is <code>9014</code>. The valid range is vendor-defined, so check it first:</p>
<pre><code class="language-powershell">Get-NetAdapterAdvancedProperty -Name &quot;SLOT 2 Port 1&quot; -RegistryKeyword &quot;*JumboPacket&quot; | Format-List -Property DisplayValue, RegistryValue, ValidRegistryValues
Set-NetAdapterAdvancedProperty -Name &quot;SLOT 2 Port 1&quot; -RegistryKeyword &quot;*JumboPacket&quot; -RegistryValue 9014
</code></pre>
<p>Then test the path, rather than trusting that three management consoles agree. <code>ping -f</code> sets Don&apos;t Fragment, and <code>-l</code> is the payload: 9000 minus 28 bytes of IPv4 and ICMP headers is 8972.</p>
<pre><code class="language-powershell">ping.exe -f -l 8972 10.20.30.11
</code></pre>
<h2>A baseline script for the host</h2>
<p>Before and after any change I capture the same snapshot on both ends, so &quot;it&apos;s faster&quot; is a comparison and not a feeling. This script is read-only. It records RSS, RSC and jumbo state per adapter and the host-wide offload state, flags ignored legacy registry values and the Chimney state, lists SMB Multichannel connections, and samples the TCP retransmit rate while you run a copy or NTTTCP. It needs Windows Server 2016 or later and an elevated session.</p>
<pre><code class="language-powershell">&lt;#
.SYNOPSIS
    Captures a read-only network baseline for storage-facing adapters on Windows Server.
.DESCRIPTION
    Reports RSS, RSC, *JumboPacket and global offload state for the named adapters,
    TCP autotuning and congestion provider per template, legacy Tcpip registry
    values that Windows ignores, current SMB Multichannel connections, and the
    TCPv4 retransmit rate sampled over a short window. Changes nothing.
.PARAMETER AdapterName
    Storage-facing adapter names, as shown by Get-NetAdapter.
.PARAMETER SampleSeconds
    How long to sample TCP counters. Default 30. Run a copy or NTTTCP meanwhile.
.EXAMPLE
    .\Get-StorageNicBaseline.ps1 -AdapterName &quot;SLOT 2 Port 1&quot;, &quot;SLOT 2 Port 2&quot; -SampleSeconds 60
.NOTES
    Author  : Thomas Lasswell (https://www.techcolumnist.com)
    Version : 1.0 (2026-07-01)
    Requires: Windows Server 2016 or later, NetAdapter, NetTCPIP and SmbShare modules
#&gt;
[CmdletBinding()]
param (
    [Parameter(Mandatory = $true)]
    [string[]]$AdapterName,

    [ValidateRange(5, 600)]
    [int]$SampleSeconds = 30
)

Write-Host &quot;== Adapters&quot;
Get-NetAdapter -Name $AdapterName |
    Format-Table -Property Name, InterfaceDescription, Status, LinkSpeed, DriverVersion -AutoSize

Write-Host &quot;== RSS&quot;
Get-NetAdapterRss -Name $AdapterName |
    Format-Table -Property Name, Enabled, Profile, BaseProcessorNumber, MaxProcessors, NumberOfReceiveQueues -AutoSize

Write-Host &quot;== RSC (enabled vs actually operating)&quot;
Get-NetAdapterRsc -Name $AdapterName |
    Format-Table -Property Name, IPv4Enabled, IPv4OperationalState, IPv4FailureReason -AutoSize

Write-Host &quot;== Jumbo packet&quot;
Get-NetAdapterAdvancedProperty -Name $AdapterName -RegistryKeyword &quot;*JumboPacket&quot; -ErrorAction SilentlyContinue |
    Format-Table -Property Name, DisplayValue, @{ Name = &quot;RegistryValue&quot;; Expression = { $_.RegistryValue -join &quot;,&quot; } } -AutoSize

Write-Host &quot;== Global offloads&quot;
Get-NetOffloadGlobalSetting |
    Format-List -Property ReceiveSideScaling, ReceiveSegmentCoalescing, Chimney, TaskOffload

Write-Host &quot;== TCP templates&quot;
Get-NetTCPSetting |
    Where-Object { $_.AutoTuningLevelLocal } |
    Format-Table -Property SettingName, AutoTuningLevelLocal, CongestionProvider -AutoSize

Write-Host &quot;== Legacy registry values (ignored by Windows)&quot;
$tcpipParams = Get-ItemProperty -Path &quot;HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters&quot;
$legacyFound = $false

foreach ($legacy in @(&quot;TcpWindowSize&quot;, &quot;NumTcbTablePartitions&quot;, &quot;MaxHashTableSize&quot;)) {
    if ($null -ne $tcpipParams.$legacy) {
        Write-Warning &quot;$legacy = $($tcpipParams.$legacy) (ignored; safe to remove)&quot;
        $legacyFound = $true
    }
}

if (-not $legacyFound) {
    Write-Host &quot;None found.&quot;
}

Write-Host &quot;== SMB Multichannel&quot;
Get-SmbClientConfiguration | Format-List -Property EnableMultiChannel
Get-SmbMultichannelConnection -ErrorAction SilentlyContinue | Format-Table -AutoSize

Write-Host &quot;== TCPv4 retransmits over $SampleSeconds seconds&quot;
$counters = &quot;\TCPv4\Segments Sent/sec&quot;, &quot;\TCPv4\Segments Retransmitted/sec&quot;
$samples = Get-Counter -Counter $counters -SampleInterval 1 -MaxSamples $SampleSeconds

$sent = ($samples.CounterSamples | Where-Object { $_.Path -like &quot;*segments sent/sec&quot; } | Measure-Object -Property CookedValue -Sum).Sum
$retrans = ($samples.CounterSamples | Where-Object { $_.Path -like &quot;*segments retransmitted/sec&quot; } | Measure-Object -Property CookedValue -Sum).Sum

if ($sent -gt 0) {
    &quot;Retransmitted {0:N0} of {1:N0} segments ({2:P3})&quot; -f $retrans, $sent, ($retrans / $sent)
} else {
    &quot;No TCPv4 segments sent during the sample.&quot;
}
</code></pre>
<p>Run it on both hosts, save the output with the change ticket, and run it again after each change. The one-setting-at-a-time version of the fixes (RSS, RSC, checksum and LSO on, jumbo frames, autotuning back to <code>Normal</code>) is packaged as <a href="https://www.techcolumnist.com/2025/04/10/powershell-windows-server-optimize-the-tcp-stack-for-10gbe-workloads/">PowerShell: Windows Server – Tune the TCP Stack for 10GbE Workloads</a>, which also warns that the adapter cmdlets bounce the NIC unless you pass <code>-NoRestart</code>.</p>
<h2>None of this replaces the baseline</h2>
<p>If I had to reduce this to an order of operations: measure the raw link with NTTTCP, confirm RSS is spreading load and the storage protocol is using more than one connection, confirm autotuning is <code>Normal</code> and delete any 2003-era registry values, check that RSC and the offloads are actually operating, then do jumbo frames last and prove them with a Don&apos;t Fragment ping. Each step is cheap to check and hard to argue with, which is exactly what you want at 2 a.m. when the storage team is sure it&apos;s the network and the network team is sure it&apos;s storage.</p>
<h2>References</h2>
<ul><li><a href="https://learn.microsoft.com/en-us/windows-server/networking/technologies/network-subsystem/net-sub-performance-tuning-nics">Network adapter performance tuning in Windows Server</a></li>
<li><a href="https://learn.microsoft.com/en-us/windows-server/storage/storage-spaces/manage-smb-multichannel">Manage SMB Multichannel</a></li>
<li><a href="https://learn.microsoft.com/en-us/troubleshoot/windows-server/networking/smb-multichannel-troubleshooting">SMB Multichannel troubleshooting</a></li>
<li><a href="https://learn.microsoft.com/en-us/powershell/module/netadapter/set-netadapterrss">Set-NetAdapterRss</a></li>
<li><a href="https://learn.microsoft.com/en-us/powershell/module/nettcpip/set-nettcpsetting">Set-NetTCPSetting</a></li>
<li><a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/network/keywords-that-can-be-edited">Standardized INF keywords that can be edited (*JumboPacket)</a></li>
<li><a href="https://learn.microsoft.com/en-us/previous-versions/windows/desktop/legacy/hh872380(v=vs.85)">MSFT_NetAdapterRscSettingData class (RSC failure reasons)</a></li>
<li><a href="https://learn.microsoft.com/en-us/azure/virtual-network/virtual-network-bandwidth-testing">Test VM network throughput by using NTTTCP</a></li>
<li><a href="https://techcommunity.microsoft.com/t5/networking-blog/windows-transport-converges-on-two-congestion-providers-cubic/ba-p/339819">Windows Transport converges on two congestion providers: Cubic and LEDBAT</a></li>
<li><a href="https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/ping">ping command reference</a></li>
</ul>
]]></content:encoded>
      <category>Engineering</category>
    </item>
    <item>
      <title>Windows Server: Disabling IPv6 Company-Wide — What Actually Broke</title>
      <link>https://www.techcolumnist.com/2026/06/24/windows-server-disabling-ipv6-company-wide-what-actually-broke/</link>
      <guid isPermaLink="true">https://www.techcolumnist.com/2026/06/24/windows-server-disabling-ipv6-company-wide-what-actually-broke/</guid>
      <pubDate>Wed, 24 Jun 2026 14:00:00 GMT</pubDate>
      <dc:creator>Tom Lasswell</dc:creator>
      <description>Field notes on disabling IPv6 across a Windows Server estate: what Microsoft says, what breaks, why prefer-IPv4 (0x20) beats 0xFF, and an audit script.</description>
      <content:encoded><![CDATA[<p>The push to disable IPv6 across a Windows estate almost always starts the same way: a vulnerability scan flags IPv6 as an unmanaged attack surface, nobody in the environment is actually routing IPv6 anywhere, and someone reasonably asks why it&apos;s enabled at all. The honest answer is in Microsoft&apos;s own guidance (KB 929852, now titled &quot;Configure IPv6 for advanced users&quot;): IPv6 &quot;is a mandatory part of Windows Vista and Windows Server 2008 and newer versions,&quot; and &quot;we don&apos;t recommend that you disable IPv6 or IPv6 components or unbind IPv6 from interfaces. If you do, some Windows components might not function.&quot; The Windows network stack was never designed to have IPv6 removed, only quieted, and the gap between those two things is where most of the pain lives.</p>
<h2>The three things people mean by &quot;disable IPv6&quot;</h2>
<p>Most arguments about this go sideways because three different changes get the same name. Keeping them separate is most of the battle.</p>
<table><thead><tr><th>Change</th><th>How</th><th>Microsoft&apos;s position</th></tr>
</thead><tbody><tr><td>Prefer IPv4 over IPv6</td><td><code>DisabledComponents</code> = <code>0x20</code> (decimal 32)</td><td>Recommended &quot;instead of disabling IPv6&quot;</td></tr>
<tr><td>Disable IPv6 components</td><td><code>DisabledComponents</code> = <code>0x01</code> (tunnels), <code>0x10</code> (native interfaces), <code>0x11</code>, or <code>0xFF</code> (everything except loopback)</td><td>Supported registry setting, not recommended</td></tr>
<tr><td>Unbind IPv6 from an adapter</td><td>Untick &quot;Internet Protocol Version 6 (TCP/IPv6)&quot; or <code>Disable-NetAdapterBinding -ComponentID ms_tcpip6</code></td><td>Not recommended; &quot;can result in an unsupported Windows configuration&quot;</td></tr>
</tbody></table>
<p>All the registry options live in one DWORD, <code>DisabledComponents</code>, under <code>HKLM\SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters</code>, and all of them need a restart. It&apos;s a bitmask: bit 0 disables tunnel interfaces, bits 1 to 3 disable 6to4, ISATAP and Teredo individually, bit 4 disables native interfaces (including PPP), and bit 5 switches the default prefix policy to prefer IPv4. <code>0xFF</code> sets them all.</p>
<p><code>0x20</code> is the one people skip, and it&apos;s usually the one that answers the actual complaint. By default Windows follows RFC 3484 and &quot;favors IPv6 global unicast addresses over IPv4 addresses.&quot; Setting bit 5 changes the prefix table so the IPv4-mapped prefix <code>::ffff:0:0/96</code> outranks <code>::/0</code>: name resolution that returns both an AAAA and an A record connects over IPv4, while the IPv6 stack, link-local addresses and loopback keep working for everything inside Windows that expects them.</p>
<h2>The wrong way in, and why it&apos;s tempting</h2>
<p>The tempting approach is unchecking the IPv6 box on every NIC, because it&apos;s visible, it&apos;s fast, and it makes the compliance scan happy on the spot. It&apos;s the option Microsoft is bluntest about: &quot;We don&apos;t recommend unbinding IPv6 from an Ethernet or WiFi network adapter without a justifiable need. Windows is tested with, and some products and features expect, IPv6 to be bound and functional.&quot; And it doesn&apos;t do what people think. The checkbox and the registry are independent. The KB points out that the <code>DisabledComponents</code> value &quot;doesn&apos;t affect the state of the check box,&quot; so a box can be ticked while IPv6 is disabled, and unticking it on one adapter leaves the stack, the tunnel adapters and the other NICs exactly as they were.</p>
<p>The next temptation is <code>0xFF</code>, because &quot;disabled&quot; feels more final than &quot;preferred.&quot; Two details from the KB matter here. First, the right value is <code>0xFF</code>, not <code>0xFFFFFFFF</code>; the latter is a common copy-paste error that Microsoft says delays every startup by five seconds. Second, even <code>0xFF</code> leaves loopback alone: &quot;You cannot completely disable IPv6 as IPv6 is used internally on the system for many TCPIP tasks. For example, you will still be able to run ping <code>::1</code> after configuring this setting.&quot; So <code>0xFF</code> doesn&apos;t remove the attack surface the scanner flagged. It just switches off the parts that were doing useful work.</p>
<h2>What broke immediately</h2>
<p>Failover clustering was the first thing to complain, and loudly. The cluster service talks node to node through the hidden Microsoft Failover Cluster Virtual Adapter (NetFT). The adapter carries an APIPA IPv4 address and an IPv6 link-local address, and the cluster log shows the node-to-node connections established on the <code>fe80::</code> virtual endpoints, tunneled over the physical NICs. That is true even in clusters where every client-facing IP is IPv4. Microsoft&apos;s KB lists failover clusters as a known casualty of disabling IPv6 for this reason. Clusters get IPv6 left alone, full stop.</p>
<p>The KB names two more immediate failures worth planning around: on domain controllers, LDAP over UDP 389 can stop working, and Exchange Server can stop working outright (the KB&apos;s example is Exchange 2010, and the linked Microsoft material covers why). And one that isn&apos;t in most checklists: &quot;Values other than 0 or 32 causes the Routing and Remote Access service to fail after this change takes effect.&quot; Any RRAS box, whether it does VPN, routing, or DirectAccess, has to stay at <code>0</code> or <code>0x20</code>.</p>
<h2>What broke weeks later</h2>
<p>The slower failures were worse to diagnose because they showed up disconnected from the change window. DirectAccess, where it was still in use on a few management workstations, quietly stopped working. DirectAccess clients reach the server over IPv6, tunneled across IPv4 networks with 6to4, Teredo or IP-HTTPS, so a disable that takes out tunnel interfaces takes DirectAccess with it. And DirectAccess failing looks like a VPN problem, not a protocol-stack problem, so it took real time to connect the dots back to a change made a month earlier.</p>
<p>The other slow burn was a trickle of tickets from devices and agents that behaved differently once IPv6 was gone, none of which said &quot;IPv6&quot; in the first report. I&apos;m not going to pretend I can give you a clean list for your environment. The practical lesson is that the tickets arrive late, and you need the change record and the per-server state (below) to hand when they do.</p>
<h2>Audit before you touch anything</h2>
<p>Before changing anything I want to know what the estate looks like today: which servers already have a <code>DisabledComponents</code> value (and whether anyone typed <code>0xFFFFFFFF</code>), which have IPv6 unbound on an adapter, and which roles are present that the KB flags. This script collects that over PowerShell remoting and writes a CSV. It reads only; it changes nothing.</p>
<p>It needs Windows PowerShell 5.1 or later, WinRM reachable on the targets, and local admin rights on them (<code>Get-WindowsFeature</code> is a Server Manager cmdlet, so it reports roles on Windows Server only).</p>
<pre><code class="language-powershell">&lt;#
.SYNOPSIS
    Audits IPv6 configuration across Windows servers without changing anything.
.DESCRIPTION
    For each server, reads the Tcpip6 DisabledComponents value, decodes it,
    lists adapters where IPv6 (ms_tcpip6) is unbound, and flags installed roles
    that Microsoft&apos;s KB 929852 calls out (failover clustering, AD DS, RRAS).
    Writes one row per server to a CSV.
.PARAMETER ComputerName
    Servers to audit.
.PARAMETER OutputPath
    CSV path. Default .\ipv6-audit.csv.
.EXAMPLE
    .\Get-Ipv6Audit.ps1 -ComputerName (Get-Content -Path .\servers.txt)
.NOTES
    Author  : Thomas Lasswell (https://www.techcolumnist.com)
    Version : 1.0 (2026-06-24)
    Requires: PowerShell remoting, local admin on targets
#&gt;
[CmdletBinding()]
param (
    [Parameter(Mandatory = $true)]
    [string[]]$ComputerName,

    [string]$OutputPath = &quot;.\ipv6-audit.csv&quot;
)

$auditScript = {
    $regPath = &quot;HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters&quot;
    $property = Get-ItemProperty -Path $regPath -Name DisabledComponents -ErrorAction SilentlyContinue
    $value = $null

    if ($property) {
        $value = [int64]$property.DisabledComponents

        if ($value -lt 0) {
            $value += 4294967296
        }
    }

    $meaning = switch ($value) {
        $null { &quot;Not set (default: IPv6 preferred)&quot; }
        0 { &quot;0x00 default&quot; }
        1 { &quot;0x01 tunnels disabled&quot; }
        16 { &quot;0x10 native interfaces disabled&quot; }
        17 { &quot;0x11 native and tunnels disabled&quot; }
        32 { &quot;0x20 prefer IPv4 (recommended)&quot; }
        255 { &quot;0xFF IPv6 disabled except loopback&quot; }
        4294967295 { &quot;0xFFFFFFFF WRONG VALUE (5 s boot delay)&quot; }
        default { &quot;0x{0:X} custom bitmask&quot; -f $value }
    }

    $unbound = Get-NetAdapterBinding -ComponentID ms_tcpip6 -ErrorAction SilentlyContinue |
        Where-Object { -not $_.Enabled } |
        ForEach-Object { $_.Name }

    $roles = @()

    if (Get-Command -Name Get-WindowsFeature -ErrorAction SilentlyContinue) {
        $roles = Get-WindowsFeature -Name Failover-Clustering, AD-Domain-Services, RemoteAccess |
            Where-Object { $_.Installed } |
            ForEach-Object { $_.Name }
    }

    [PSCustomObject]@{
        DisabledComponents = $meaning
        UnboundAdapters    = ($unbound -join &quot;; &quot;)
        FlaggedRoles       = ($roles -join &quot;; &quot;)
    }
}

$results = Invoke-Command -ComputerName $ComputerName -ScriptBlock $auditScript -ErrorAction SilentlyContinue -ErrorVariable remoteErrors

$results |
    Select-Object -Property PSComputerName, DisabledComponents, UnboundAdapters, FlaggedRoles |
    Sort-Object -Property PSComputerName |
    Export-Csv -Path $OutputPath -NoTypeInformation

foreach ($failure in $remoteErrors) {
    Write-Warning &quot;Unreachable: $($failure.TargetObject) - $($failure.Exception.Message)&quot;
}

Write-Host &quot;Audit written to $OutputPath&quot;
</code></pre>
<p>Sample output, opened with <code>Import-Csv -Path .\ipv6-audit.csv | Format-Table</code>:</p>
<pre><code class="language-text">PSComputerName DisabledComponents                      UnboundAdapters FlaggedRoles
-------------- ------------------                      --------------- ------------
SRV-APP01      Not set (default: IPv6 preferred)
SRV-CL01N1     Not set (default: IPv6 preferred)                       Failover-Clustering
SRV-DC01       0xFFFFFFFF WRONG VALUE (5 s boot delay)                 AD-Domain-Services
SRV-RAS01      0x20 prefer IPv4 (recommended)                          RemoteAccess
SRV-FILE02     Not set (default: IPv6 preferred)       Ethernet 2
</code></pre>
<p>Anything with <code>FlaggedRoles</code> goes to the back of the queue or out of scope entirely. Anything with <code>UnboundAdapters</code> gets re-bound (<code>Enable-NetAdapterBinding -Name &quot;&lt;adapter&gt;&quot; -ComponentID ms_tcpip6</code>) as part of the same change, because that&apos;s the configuration Microsoft won&apos;t support.</p>
<h2>Rolling it out</h2>
<p>For the change itself I use a Group Policy computer startup script that writes <code>DisabledComponents</code>, logs what it did, and warns about unbound adapters. It&apos;s published separately with parameters, sample logs and rollback as <a href="https://www.techcolumnist.com/2025/04/03/powershell-windows-disable-ipv6-fleet-wide-via-group-policy-startup-script/">PowerShell: Windows – Disable IPv6 Fleet-Wide via GPO Startup Script</a>. Its default is <code>0x20</code>. If you don&apos;t need the logging, a GPO registry setting does the same with one line from the <code>GroupPolicy</code> module:</p>
<pre><code class="language-powershell">Set-GPRegistryValue -Name &quot;IPv6 - Prefer IPv4&quot; -Key &quot;HKLM\SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters&quot; -ValueName &quot;DisabledComponents&quot; -Type DWord -Value 32
</code></pre>
<p>If the actual problem is stray tunnel addresses, fix that problem instead. Windows turns on 6to4 when an interface gets a public IPv4 address and registers the resulting IPv6 addresses in DNS. Either <code>0x01</code> or the policies under Computer Configuration &gt; Administrative Templates &gt; Network &gt; TCPIP Settings &gt; IPv6 Transition Technologies (6to4 State, ISATAP State and Teredo State all set to Disabled) turn the tunnels off without touching native IPv6. ISATAP and Teredo are already off by default.</p>
<h2>What I&apos;d do differently</h2>
<p>Prefer IPv4 first (<code>0x20</code>), and only go further for a specific, written-down reason. Never unbind at the adapter unless a driver or vendor genuinely requires it. Stage by server role, not by blast-radius convenience: standalone application servers first, because that&apos;s where a mistake is cheapest to find, then everything else, with cluster nodes, domain controllers, Exchange and RRAS/DirectAccess last or excluded with a security-group filter on the GPO. Keep the audit CSV from before and after so the late tickets can be checked against a known state. And budget for those late tickets: the DirectAccess failure took longer to attribute to the change than the change itself took to roll out. Disabling IPv6 the right way isn&apos;t really a technical challenge, since the registry value is one line. It&apos;s a change-management challenge, and the technical shortcuts are exactly where the cost hides.</p>
<h2>References</h2>
<ul><li><a href="https://learn.microsoft.com/en-us/troubleshoot/windows-server/networking/configure-ipv6-in-windows">Configure IPv6 for advanced users in Windows (KB 929852)</a></li>
<li><a href="https://learn.microsoft.com/en-us/archive/blogs/netro/arguments-against-disabling-ipv6">Arguments against disabling IPv6 (Microsoft networking blog archive)</a></li>
<li><a href="https://learn.microsoft.com/en-us/archive/blogs/askcore/what-is-a-microsoft-failover-cluster-virtual-adapter-anyway">What is a Microsoft Failover Cluster Virtual Adapter anyway? (Ask the Core Team archive)</a></li>
<li><a href="https://learn.microsoft.com/en-us/windows-server/remote/remote-access/directaccess/single-server-wizard/da-basic-plan-s1-infrastructure">Plan the basic DirectAccess infrastructure</a></li>
<li><a href="https://learn.microsoft.com/en-us/powershell/module/netadapter/get-netadapterbinding">Get-NetAdapterBinding</a></li>
<li><a href="https://learn.microsoft.com/en-us/powershell/module/grouppolicy/set-gpregistryvalue">Set-GPRegistryValue</a></li>
<li><a href="https://datatracker.ietf.org/doc/html/rfc3484">RFC 3484: Default Address Selection for IPv6</a></li>
</ul>
]]></content:encoded>
      <category>Engineering</category>
    </item>
    <item>
      <title>Windows 11: A Debloat and Hardening Baseline for New Deployments</title>
      <link>https://www.techcolumnist.com/2026/06/17/windows-11-a-debloat-and-hardening-baseline-for-new-deployments/</link>
      <guid isPermaLink="true">https://www.techcolumnist.com/2026/06/17/windows-11-a-debloat-and-hardening-baseline-for-new-deployments/</guid>
      <pubDate>Wed, 17 Jun 2026 14:00:00 GMT</pubDate>
      <dc:creator>Tom Lasswell</dc:creator>
      <description>A repeatable Windows 11 baseline: policy-based app removal, Microsoft security baselines, BitLocker, Defender and ASR settings, plus a fleet audit script.</description>
      <content:encoded><![CDATA[<p>Every new Windows 11 deployment starts from the same place: an image or a fresh OOBE install carrying a set of consumer-oriented defaults that have no business on a managed business endpoint. Widgets, a taskbar full of pinned consumer apps, Start suggestions, and a handful of provisioned apps nobody in the fleet asked for. None of it is individually a big deal, but treated as a checklist instead of an afterthought, it turns into a baseline that&apos;s consistent across every machine that ships, which matters more than any single setting on its own.</p>
<p>This post is the checklist I use, with the scripts behind it. The companion script posts go deeper on the two debloat paths: <a href="https://www.techcolumnist.com/2025/07/16/powershell-windows-11-debloat-a-golden-image-before-sysprep/">debloating a golden image before Sysprep</a> and <a href="https://www.techcolumnist.com/2025/11/05/powershell-windows-11-strip-preinstalled-apps-from-a-deployment-image/">stripping apps from a deployment image</a>.</p>
<h2>Decide what &quot;debloat&quot; actually means before touching anything</h2>
<p>The word gets used loosely enough to mean anything from removing a game bar overlay to disabling Windows Update entirely, and the second interpretation is how debloat scripts turn into support tickets six months later. My working definition is narrower: remove provisioned consumer apps that serve no business purpose, turn off consumer experiences that fight the management stack, and leave anything that&apos;s arguably still useful alone: Snipping Tool, Terminal, Calculator, Notepad, Quick Assist if your help desk uses it. A debloat pass that quietly disables Windows Update, removes the Store&apos;s ability to service inbox apps, or rips out Defender components because a blog post said so is a hardening regression wearing a hardening costume.</p>
<p>In practice that&apos;s three settings groups:</p>
<ol><li><strong>Provisioned apps.</strong> News, Weather, Solitaire, the Xbox overlays, Clipchamp, Feedback Hub.</li>
<li><strong>Consumer experiences.</strong> The &quot;Turn off Microsoft consumer experiences&quot; and &quot;Do not show Windows tips&quot; policies under Computer Configuration &gt; Administrative Templates &gt; Windows Components &gt; Cloud Content. Both are honored only on Enterprise and Education; the Experience Policy CSP lists Pro as not applicable.</li>
<li><strong>Widgets.</strong> &quot;Allow widgets&quot; under Windows Components &gt; Widgets (registry <code>HKLM\SOFTWARE\Policies\Microsoft\Dsh</code>, value <code>AllowNewsAndInterests</code> = 0). This one does apply to Pro.</li>
</ol>
<h2>Use the policy for app removal if your edition allows it</h2>
<p>For a long time the only way to remove inbox apps was a script: <code>Remove-AppxPackage</code> for existing users, <code>Remove-AppxProvisionedPackage</code> for future ones, run in the image or at provisioning. That still works, and it&apos;s the only option on Pro, but on <strong>Windows 11, version 24H2 or later, Enterprise and Education</strong> there&apos;s now a policy: <strong>Remove default Microsoft Store packages from the system</strong> (Group Policy, under Windows Components &gt; App Package Deployment) or <code>ApplicationManagement/RemoveDefaultMicrosoftStorePackages</code> in the Policy CSP.</p>
<p>What makes it better than a script is the lifecycle. Removal runs at OOBE, at the first sign-in after an OS upgrade, and at the first sign-in after the policy changes, and an app stays blocked from reinstalling (including from the Store) while it&apos;s selected. A feature update that would have brought an app back on a scripted device doesn&apos;t on a policy-managed one. The documented limits are worth knowing before you commit: it&apos;s device-scoped only, multi-session environments aren&apos;t supported, existing profiles only lose the app at their next sign-in, and deselecting an app doesn&apos;t reinstall it. The strip-apps post has the full OMA-URI payload and the <code>AppXDeploymentServer</code> event IDs (606, 614, 762) for verifying it.</p>
<h2>Start from Microsoft&apos;s security baseline, not a blank page</h2>
<p>Microsoft&apos;s own guidance is to implement a broadly known, well-tested configuration, such as the Microsoft security baselines, rather than building one yourself. The baselines ship in the Security Compliance Toolkit as GPO backups you can import into GPMC, and as MDM security baselines in Intune. They&apos;re designed for organizations where standard users don&apos;t have admin rights, and they only enforce a setting when it mitigates a current threat without causing worse operational problems. That design principle is exactly what you want from a baseline: it saves you arguing about three thousand Group Policy settings.</p>
<p>The baseline covers a lot, but I still verify four things explicitly on a fresh device, because they&apos;re the ones that most often end up wrong in practice: disk encryption, Defender&apos;s cloud protection, attack surface reduction rules, and Credential Guard.</p>
<h2>The four hardening settings I check on every device</h2>
<p><strong>BitLocker with a backed-up recovery key.</strong> The BitLocker cmdlet reference describes the pattern: add a recovery password protector, back it up, then enable BitLocker with the TPM protector. Enabling without an escrowed recovery password is how a firmware update turns into a data-loss event. XTS-AES-128 is the default; I specify XTS-AES-256 and skip hardware encryption, which Microsoft&apos;s reference advises against (security advisory ADV180028).</p>
<p><strong>Defender cloud-delivered protection and sample submission.</strong> Cloud protection is on by default, but earlier policy can have turned it off (the <code>Set-MpPreference</code> reference still lists <code>MAPSReporting</code> as defaulting to Disabled), so I set it explicitly: <code>MAPSReporting</code> to Advanced, and <code>SubmitSamplesConsent</code> to SendSafeSamples. Several ASR rules (obfuscated scripts, ransomware protection, prevalence-based blocking) require cloud-delivered protection to work at all.</p>
<p><strong>ASR rules.</strong> Microsoft groups three rules as &quot;standard protection&quot; that you can typically enable in Block mode without an audit period: block abuse of exploited vulnerable signed drivers, block credential stealing from LSASS, and block persistence through WMI event subscription. Everything else goes into Audit first. One nuance from the reference: if LSA protection or Credential Guard is on, the LSASS rule adds nothing and shows as not applicable. And if you use Configuration Manager, test the WMI persistence rule in Audit first, since the ConfigMgr client relies heavily on WMI.</p>
<p><strong>Credential Guard.</strong> On Windows 11 22H2 and later, Credential Guard is enabled by default on Enterprise and Education devices that meet the hardware and license requirements, unless it was explicitly disabled before the upgrade. That &quot;unless&quot; is why I check rather than assume. Microsoft also says to enable it before domain join or before the first domain user signs in, so it belongs in provisioning, not in a post-deployment fix. It isn&apos;t available on Pro.</p>
<p>Here&apos;s the local script I run in a provisioning step (an Autopilot platform script, a task sequence step, or by hand on a lab device). It&apos;s deliberately explicit so you can read exactly what it does:</p>
<pre><code class="language-powershell">&lt;#
.SYNOPSIS
    Applies the local hardening defaults for a new Windows 11 device.
.DESCRIPTION
    Adds and escrows a BitLocker recovery password, enables BitLocker on the OS drive
    with the TPM protector (XTS-AES-256, used space only), sets Defender cloud
    protection and sample submission, puts the three standard-protection ASR rules in
    Block and a set of other rules in Audit, and reports Credential Guard status.
    Policy from Intune, ConfigMgr or GPO overrides these local settings, which is the
    intended end state.
.PARAMETER KeyBackup
    Where to escrow the BitLocker recovery password: AD or Entra.
.EXAMPLE
    .\Set-EndpointHardening.ps1 -KeyBackup Entra
.NOTES
    Author  : Thomas Lasswell (https://www.techcolumnist.com)
    Version : 1.0 (2026-06-17)
    Requires: Windows 11 Pro/Enterprise/Education, elevated Windows PowerShell 5.1,
              BitLocker and Defender modules (in box). ASR rules also need
              Microsoft Defender Antivirus as the primary antivirus, in Active mode.
#&gt;

#Requires -RunAsAdministrator

[CmdletBinding()]
param (
    [Parameter(Mandatory = $true)]
    [ValidateSet(&quot;AD&quot;, &quot;Entra&quot;)]
    [string]$KeyBackup
)

$osDrive = $env:SystemDrive

# BitLocker: recovery password first, escrow it, then the TPM protector.
$volume = Get-BitLockerVolume -MountPoint $osDrive
if ($volume.VolumeStatus -eq &quot;FullyDecrypted&quot;) {
    $recovery = $volume.KeyProtector | Where-Object { $_.KeyProtectorType -eq &quot;RecoveryPassword&quot; } | Select-Object -First 1

    if (-not $recovery) {
        Add-BitLockerKeyProtector -MountPoint $osDrive -RecoveryPasswordProtector | Out-Null
        $recovery = (Get-BitLockerVolume -MountPoint $osDrive).KeyProtector |
            Where-Object { $_.KeyProtectorType -eq &quot;RecoveryPassword&quot; } | Select-Object -First 1
    }

    if ($KeyBackup -eq &quot;Entra&quot;) {
        BackupToAAD-BitLockerKeyProtector -MountPoint $osDrive -KeyProtectorId $recovery.KeyProtectorId | Out-Null
    } else {
        Backup-BitLockerKeyProtector -MountPoint $osDrive -KeyProtectorId $recovery.KeyProtectorId | Out-Null
    }

    Enable-BitLocker -MountPoint $osDrive -TpmProtector -EncryptionMethod XtsAes256 -UsedSpaceOnly | Out-Null
    Write-Host &quot;BitLocker enabled on $osDrive; recovery password escrowed to $KeyBackup.&quot;
} else {
    Write-Host &quot;BitLocker already $($volume.VolumeStatus) on $osDrive; leaving it alone.&quot;
}

# Defender cloud-delivered protection and automatic safe-sample submission.
Set-MpPreference -MAPSReporting Advanced -SubmitSamplesConsent SendSafeSamples -PUAProtection Enabled

# ASR: standard protection rules in Block.
$blockRules = @(
    # Block abuse of exploited vulnerable signed drivers
    &quot;56a863a9-875e-4185-98a7-b882c64b5ce5&quot;,
    # Block credential stealing from LSASS
    &quot;9e6c4e1f-7d60-472f-ba1a-a39ef669e4b2&quot;,
    # Block persistence through WMI event subscription
    &quot;e6db77e5-3df2-4cf1-b95a-636979351e5b&quot;
)

# ASR: other rules in Audit until the event data says they&apos;re safe to block.
$auditRules = @(
    # Block executable content from email client and webmail
    &quot;be9ba2d9-53ea-4cdc-84e5-9b1eeee46550&quot;,
    # Block all Office applications from creating child processes
    &quot;d4f940ab-401b-4efc-aadc-ad5f3c50688a&quot;,
    # Block Office applications from creating executable content
    &quot;3b576869-a4ec-4529-8536-b80a7769e899&quot;,
    # Block Office applications from injecting code into other processes
    &quot;75668c1f-73b5-4cf0-bb93-3ecf5cb7cc84&quot;,
    # Block JavaScript or VBScript from launching downloaded executable content
    &quot;d3e037e1-3eb8-44c8-a917-57927947596d&quot;,
    # Block execution of potentially obfuscated scripts
    &quot;5beb7efe-fd9a-4556-801d-275e5ffc04cc&quot;,
    # Block Win32 API calls from Office macros
    &quot;92e97fa1-2edf-4476-bdd6-9dd0b4dddc7b&quot;,
    # Use advanced protection against ransomware
    &quot;c1db55ab-c21a-4637-bb3f-a12568109d35&quot;
)

Add-MpPreference -AttackSurfaceReductionRules_Ids $blockRules -AttackSurfaceReductionRules_Actions (@(&quot;Enabled&quot;) * $blockRules.Count)
Add-MpPreference -AttackSurfaceReductionRules_Ids $auditRules -AttackSurfaceReductionRules_Actions (@(&quot;AuditMode&quot;) * $auditRules.Count)

# Credential Guard: report only; enable it through policy before domain join.
$deviceGuard = Get-CimInstance -ClassName Win32_DeviceGuard -Namespace &quot;root\Microsoft\Windows\DeviceGuard&quot;
$cgRunning = @($deviceGuard.SecurityServicesRunning) -contains 1
Write-Host &quot;Credential Guard running: $cgRunning&quot;
</code></pre>
<p><code>Set-MpPreference</code> has the lowest precedence of any ASR configuration method. Group Policy and MDM overwrite it at startup. That&apos;s fine: the script gives a lab or pilot device a sane state on day one, and the real baseline lives in policy.</p>
<h2>Bake it into provisioning, not into a post-deployment script</h2>
<p>The version of this baseline that actually holds up over time lives in the provisioning pipeline: an Autopilot profile with the app removal policy, security baseline and endpoint security profiles assigned to device groups, or GPOs linked to the workstation OU. Not a PowerShell script run once by hand on day one. A script run once drifts the moment someone reimages a machine outside the documented path or restores from an older image during a break-fix. A baseline enforced through the same mechanism that provisions every machine self-heals on the next sync, which is the difference between a policy and a one-time favor to your future self.</p>
<p>For Autopilot specifically, Microsoft recommends configuring the Enrollment Status Page to block until device configuration completes so the app removal policy lands before the user reaches the desktop. If it arrives late, apps can appear until the following sign-in.</p>
<h2>Measure what the baseline actually enforces</h2>
<p>The debloat half is easy to verify (a provisioned app is either gone or it isn&apos;t), but the hardening half needs an audit trail. Pull BitLocker status, Defender configuration, ASR rule state and Credential Guard across the fleet on a schedule, not just at image-build time. A setting that&apos;s correct in the base image but gets overridden by a conflicting GPO six months later is functionally the same as never having set it, and the only way to catch that kind of regression is to keep checking.</p>
<p>This is the audit I schedule weekly. It fans out over PowerShell remoting, so it needs WinRM on the targets and an account in the Administrators group (or Remote Management Users with a suitably configured endpoint):</p>
<pre><code class="language-powershell">&lt;#
.SYNOPSIS
    Reports BitLocker, Defender, ASR, Credential Guard and provisioned-app state across
    a list of Windows 11 computers.
.PARAMETER ComputerName
    Computers to audit.
.PARAMETER OutputPath
    CSV to write. Defaults to .\baseline-audit.csv.
.EXAMPLE
    .\Get-BaselineCompliance.ps1 -ComputerName (Get-Content .\workstations.txt)
.NOTES
    Author  : Thomas Lasswell (https://www.techcolumnist.com)
    Version : 1.0 (2026-06-17)
    Requires: PowerShell remoting on targets; admin rights on targets
#&gt;
[CmdletBinding()]
param (
    [Parameter(Mandatory = $true)]
    [string[]]$ComputerName,

    [string]$OutputPath = &quot;.\baseline-audit.csv&quot;
)

$auditScript = {
    $os = Get-BitLockerVolume -MountPoint $env:SystemDrive
    $status = Get-MpComputerStatus
    $prefs = Get-MpPreference
    $deviceGuard = Get-CimInstance -ClassName Win32_DeviceGuard -Namespace &quot;root\Microsoft\Windows\DeviceGuard&quot;

    # Pair each ASR rule GUID with its action (0 off, 1 block, 2 audit, 6 warn).
    $asr = @()
    for ($i = 0; $i -lt @($prefs.AttackSurfaceReductionRules_Ids).Count; $i++) {
        $asr += &quot;$($prefs.AttackSurfaceReductionRules_Ids[$i])=$($prefs.AttackSurfaceReductionRules_Actions[$i])&quot;
    }

    $consumerApps = @(Get-AppxProvisionedPackage -Online | Where-Object {
        $_.DisplayName -match &quot;BingNews|BingWeather|SolitaireCollection|GamingApp|Clipchamp&quot;
    })

    [pscustomobject]@{
        ComputerName         = $env:COMPUTERNAME
        BitLockerStatus      = &quot;$($os.VolumeStatus)&quot;
        BitLockerProtection  = &quot;$($os.ProtectionStatus)&quot;
        EncryptionMethod     = &quot;$($os.EncryptionMethod)&quot;
        HasRecoveryPassword  = [bool]($os.KeyProtector | Where-Object { $_.KeyProtectorType -eq &quot;RecoveryPassword&quot; })
        DefenderService      = $status.AMServiceEnabled
        RealTimeProtection   = $status.RealTimeProtectionEnabled
        SignaturesUpdated    = $status.AntivirusSignatureLastUpdated
        MAPSReporting        = $prefs.MAPSReporting
        AsrRules             = ($asr -join &quot;;&quot;)
        CredentialGuard      = @($deviceGuard.SecurityServicesRunning) -contains 1
        ConsumerAppsRemaining = $consumerApps.Count
    }
}

$results = Invoke-Command -ComputerName $ComputerName -ScriptBlock $auditScript -ErrorAction SilentlyContinue -ErrorVariable remoteErrors

$results | Select-Object -Property * -ExcludeProperty PSComputerName, RunspaceId, PSShowComputerName |
    Export-Csv -Path $OutputPath -NoTypeInformation

Write-Host &quot;Audited $(@($results).Count) of $($ComputerName.Count) computers; results in $OutputPath&quot;
foreach ($err in $remoteErrors) {
    Write-Warning $err.Exception.Message
}
</code></pre>
<p>Sample row from a device that drifted:</p>
<pre><code class="language-text">ComputerName          : WKS-0142
BitLockerStatus       : FullyEncrypted
BitLockerProtection   : Off
EncryptionMethod      : XtsAes256
HasRecoveryPassword   : True
DefenderService       : True
RealTimeProtection    : True
SignaturesUpdated     : 6/15/2026 3:12:44 AM
MAPSReporting         : 2
AsrRules              : 56a863a9-875e-4185-98a7-b882c64b5ce5=1;9e6c4e1f-7d60-472f-ba1a-a39ef669e4b2=1;...
CredentialGuard       : False
ConsumerAppsRemaining : 0
</code></pre>
<p><code>BitLockerProtection : Off</code> on a fully encrypted volume means the keys are not currently protected, most often because protection was suspended (for example with <code>Suspend-BitLocker</code> ahead of a firmware update) and never resumed; <code>Resume-BitLocker</code> turns it back on. <code>CredentialGuard : False</code> on an Enterprise device is worth checking against msinfo32 and the WinInit events 13 through 17 in the System log that Microsoft documents for Credential Guard.</p>
<p>If you&apos;d rather not run anything, the same questions can be answered by the Intune security baseline and endpoint security reports. I still like having the CSV, because it&apos;s the same shape for every device regardless of which management channel it&apos;s in, and it feeds straight into the <a href="https://www.techcolumnist.com/2026/09/02/windows-management-building-a-discovery-inventory-nobody-has-to-maintain-by-hand/">discovery inventory</a>.</p>
<h2>References</h2>
<ul><li><a href="https://learn.microsoft.com/en-us/windows/configuration/policy-based-inbox-app-removal/policy-based-inbox-app-removal">Policy-based in-box app removal</a></li>
<li><a href="https://learn.microsoft.com/en-us/windows/client-management/mdm/policy-csp-experience">Experience Policy CSP</a> and <a href="https://learn.microsoft.com/en-us/windows/client-management/mdm/policy-csp-newsandinterests">NewsAndInterests Policy CSP</a></li>
<li><a href="https://learn.microsoft.com/en-us/windows/security/operating-system-security/device-management/windows-security-configuration-framework/windows-security-baselines">Security baselines guide</a></li>
<li><a href="https://learn.microsoft.com/en-us/powershell/module/bitlocker/enable-bitlocker">Enable-BitLocker</a> and <a href="https://learn.microsoft.com/en-us/powershell/module/bitlocker/backuptoaad-bitlockerkeyprotector">BackupToAAD-BitLockerKeyProtector</a></li>
<li><a href="https://learn.microsoft.com/en-us/powershell/module/defender/set-mppreference">Set-MpPreference</a></li>
<li><a href="https://learn.microsoft.com/en-us/defender-endpoint/attack-surface-reduction-rules-reference">ASR rules reference</a></li>
<li><a href="https://learn.microsoft.com/en-us/defender-endpoint/attack-surface-reduction-rules-configure">Configure ASR rules and exclusions</a></li>
<li><a href="https://learn.microsoft.com/en-us/windows/security/identity-protection/credential-guard/">Credential Guard overview</a> and <a href="https://learn.microsoft.com/en-us/windows/security/identity-protection/credential-guard/configure">Configure Credential Guard</a></li>
</ul>
]]></content:encoded>
      <category>Engineering</category>
    </item>
    <item>
      <title>Hyper-V: Migrating VMs Off an Aging Cluster Without Downtime</title>
      <link>https://www.techcolumnist.com/2026/06/10/hyper-v-migrating-vms-off-an-aging-cluster-without-downtime/</link>
      <guid isPermaLink="true">https://www.techcolumnist.com/2026/06/10/hyper-v-migrating-vms-off-an-aging-cluster-without-downtime/</guid>
      <pubDate>Wed, 10 Jun 2026 14:00:00 GMT</pubDate>
      <dc:creator>Tom Lasswell</dc:creator>
      <description>Moving VMs from an old Hyper-V cluster to a new one with shared-nothing live migration: configuration versions, CPU compatibility, delegation, bandwidth and a migration script.</description>
      <content:encoded><![CDATA[<p>An aging Hyper-V cluster doesn&apos;t announce that it&apos;s time to go. It just accumulates small warning signs — a host that takes longer to fail over than it used to, firmware updates the vendor no longer tests against the current build, storage that&apos;s a generation behind what the newer hosts get — until replacing it stops being optional. The workloads on it are still production, though, and &quot;just schedule a maintenance window&quot; gets harder to justify every year as more of the business runs around the clock. Moving VMs to a new cluster without downtime is possible, but it&apos;s a different operation than the failover most admins are used to, and it has its own set of surprises.</p>
<h2>Why We Couldn&apos;t Just Fail Over</h2>
<p>A normal Hyper-V cluster failover or live migration moves a VM between nodes that share the same cluster, the same Cluster Shared Volumes and the same cluster database. Moving to a new cluster entirely is a different animal. There&apos;s no shared CSV between the old cluster and the new one, so this is a shared-nothing live migration: Hyper-V copies the VM&apos;s memory and streams its virtual disks across the network to the destination host while the VM keeps running on the source. <code>Move-VM</code> does this when you pass <code>-IncludeStorage</code> and a <code>-DestinationStoragePath</code>; without them it assumes the storage is already reachable from the destination.</p>
<p>Two things about clustered VMs are not obvious. First, Microsoft&apos;s older cluster migration guidance says plainly that you cannot live migrate a highly available VM to a new failover cluster; its supported path, the Copy Cluster Roles wizard, moves the role and then remaps the same LUNs to the new cluster with a brief outage. To get a zero-downtime move you take the VM out of the old cluster&apos;s control first (remove its clustered role, which leaves the VM itself running and registered in Hyper-V on its owner node), live migrate it with its storage to a node of the new cluster, then make it highly available again there with <code>Add-ClusterVirtualMachineRole</code>. For the minutes the copy takes, the VM is not protected by either cluster, which is one more reason to move them one at a time.</p>
<p>Second, if you were hoping to avoid all of this, Cluster OS Rolling Upgrade only helps when you keep the hardware: it upgrades the OS one node at a time, one Windows Server version per pass. Replacing the hosts means migrating.</p>
<h2>Configuration Versions Were the First Surprise</h2>
<p>The VM configuration version decides which hosts a VM can run on at all, and new hosts drop old versions. Windows Server 2022 runs configuration versions 8.0 through 10.0, and Windows Server 2025 runs 8.0 through 12.0. Anything still at 5.0 (created on Windows Server 2012 R2) or at 6.2 to 7.1 and never upgraded cannot run on either, so it cannot live migrate there. <code>Update-VMVersion</code> fixes that, but it needs the VM shut down and it cannot be undone: after the upgrade the VM can&apos;t go back to a host that doesn&apos;t support the new version. That meant a short, scheduled restart for a handful of old VMs before the zero-downtime part could even begin, and it&apos;s why I now run <code>Get-VM | Format-Table Name, Version</code> against every old cluster long before the new hardware arrives.</p>
<h2>CPU Compatibility Was the Second</h2>
<p>The old cluster&apos;s hosts and the new cluster&apos;s hosts were bought years apart, which meant different CPU generations with different instruction sets exposed to the guest. Hyper-V checks the processor features a running VM can see against the destination before a live migration, and cancels the move if they don&apos;t match. Processor compatibility mode fixes that by presenting a reduced feature set, but it has to be turned on while the VM is shut down, so it goes in the same maintenance slot as any configuration-version upgrade, not mid-move. It doesn&apos;t help across vendors either: even with it enabled you can&apos;t live migrate from an Intel host to an AMD host. Microsoft recommends turning it on only for the migration and off again afterwards, because it hides the newer instructions from the guest. Windows Server 2025 adds a dynamic mode that calculates the common feature set across a cluster&apos;s nodes automatically, for VMs at configuration version 10.0 or later.</p>
<p><code>Compare-VM</code> is the tool that catches both problems before they turn into a failed migration in front of an audience. It builds the same compatibility report <code>Move-VM</code> would, without moving anything, and lists every incompatibility with a message and ID.</p>
<h2>Authentication and Bandwidth</h2>
<p>Shared-nothing moves started from a management machine need Kerberos constrained delegation: each host&apos;s computer account trusted to delegate <code>Microsoft Virtual System Migration Service</code> (for the VM) and <code>cifs</code> (for the storage) to the other side, set with &quot;Use any authentication protocol&quot;. CredSSP avoids the delegation but only works if you&apos;re signed in to the source host, and it stops working entirely once hosts run Windows Server 2025, which enables Credential Guard by default on domain members. Microsoft&apos;s Scale-Out File Server deployment guide ships a delegation script built on <code>msDS-AllowedToDelegateTo</code>; this is the same idea for an old-cluster-to-new-cluster move, run once with the ActiveDirectory module as a Domain Admin:</p>
<pre><code class="language-powershell">&lt;#
.SYNOPSIS
    Grants Kerberos constrained delegation for live migration and storage moves between two sets of Hyper-V hosts.
.DESCRIPTION
    For every source and destination host pair, adds the Microsoft Virtual System Migration Service and cifs
    SPNs of the other host to msDS-AllowedToDelegateTo and enables protocol transition (&quot;Use any
    authentication protocol&quot;), in both directions. Hosts need a new Kerberos ticket (a restart is simplest)
    before the change takes effect.
.PARAMETER SourceHosts
    Hyper-V hosts in the old cluster.
.PARAMETER DestinationHosts
    Hyper-V hosts in the new cluster.
.EXAMPLE
    .\Set-MigrationDelegation.ps1 -SourceHosts &apos;old-hv01&apos;, &apos;old-hv02&apos; -DestinationHosts &apos;new-hv01&apos;, &apos;new-hv02&apos;
.NOTES
    Author  : Thomas Lasswell (https://www.techcolumnist.com)
    Version : 1.0 (2026-06-10)
    Requires: ActiveDirectory module, Domain Admins
#&gt;

[CmdletBinding()]
param (
    [Parameter(Mandatory = $true)]
    [string[]]$SourceHosts,

    [Parameter(Mandatory = $true)]
    [string[]]$DestinationHosts
)

Import-Module -Name ActiveDirectory

$pairs = foreach ($source in $SourceHosts) {
    foreach ($destination in $DestinationHosts) {
        [PSCustomObject]@{ From = $source; To = $destination }
        [PSCustomObject]@{ From = $destination; To = $source }
    }
}

foreach ($pair in $pairs) {
    $target = Get-ADComputer -Identity $pair.To
    $services = @(
        &quot;Microsoft Virtual System Migration Service/$($target.Name)&quot;,
        &quot;Microsoft Virtual System Migration Service/$($target.DNSHostName)&quot;,
        &quot;cifs/$($target.Name)&quot;,
        &quot;cifs/$($target.DNSHostName)&quot;
    )

    $computer = Get-ADComputer -Identity $pair.From -Properties &apos;msDS-AllowedToDelegateTo&apos;
    $missing = $services | Where-Object { $computer.&apos;msDS-AllowedToDelegateTo&apos; -notcontains $_ }

    if ($missing) {
        Set-ADComputer -Identity $computer -Add @{ &apos;msDS-AllowedToDelegateTo&apos; = [string[]]$missing }
        Write-Output &quot;$($pair.From): added delegation to $($pair.To)&quot;
    }

    Set-ADAccountControl -Identity $computer -TrustedToAuthForDelegation $true
}
</code></pre>
<p>Then, on every source and destination host, turn on live migrations outside the cluster with <code>Enable-VMMigration</code> (off by default), allow the migration network with <code>Add-VMMigrationNetwork</code>, and set <code>Set-VMHost -VirtualMachineMigrationAuthenticationType Kerberos</code>. Remember that live migration traffic isn&apos;t encrypted on the wire, so keep it on a trusted, isolated network.</p>
<p>Bandwidth is the other half. A shared-nothing move carries the whole virtual disk, not just memory, so it saturates whatever link it&apos;s given. Hyper-V allows two simultaneous live migrations per host by default. <code>Set-VMHost</code> caps live and storage migrations separately (<code>MaximumVirtualMachineMigrations</code>, <code>MaximumStorageMigrations</code>), and on a cluster node the cluster&apos;s <code>MaximumParallelMigrations</code> property takes precedence for live migrations. If you use the SMB performance option, the SMB bandwidth limit feature (<code>FS-SMBBW</code>, which defaults to 25% of a node&apos;s bandwidth once installed) keeps migrations from starving storage and cluster traffic on shared adapters.</p>
<h2>The Migration Script</h2>
<p>This is the per-VM loop I run from a management machine. It reads the VMs in the order given, finds each one&apos;s owner node on the old cluster, checks the configuration version against the destination host and runs <code>Compare-VM</code>. Without <code>-Execute</code> it stops there and prints the report, which is the pre-flight I run days ahead. With <code>-Execute</code> it removes the clustered role on the old cluster, live migrates the VM and its storage to the new CSV, and makes it highly available on the new cluster. If the move fails, it puts the role back on the old cluster.</p>
<pre><code class="language-powershell">&lt;#
.SYNOPSIS
    Checks and, optionally, live migrates clustered VMs from an old Hyper-V cluster to a new one, one at a time.
.DESCRIPTION
    For each VM, in the order given: finds the owner node on the source cluster, checks that the destination
    host supports the VM configuration version, and runs Compare-VM with storage. Without -Execute it only
    reports. With -Execute it removes the VM&apos;s clustered role on the source cluster, runs Move-VM with
    -IncludeStorage to a folder under the destination CSV, then runs Add-ClusterVirtualMachineRole on the
    destination cluster. If Move-VM fails, the role is re-created on the source cluster.
.PARAMETER VMName
    VMs to migrate, lowest business risk first.
.PARAMETER SourceCluster
    The old cluster.
.PARAMETER DestinationCluster
    The new cluster.
.PARAMETER DestinationHost
    Node of the new cluster that receives the VMs.
.PARAMETER DestinationCsvPath
    CSV folder on the new cluster; each VM gets a subfolder named after it.
.PARAMETER Execute
    Perform the migration. Without it the script only reports.
.EXAMPLE
    .\Move-VMToNewCluster.ps1 -VMName &apos;file01&apos;, &apos;print01&apos; -SourceCluster &apos;old-clu&apos; -DestinationCluster &apos;new-clu&apos; -DestinationHost &apos;new-hv01&apos; -DestinationCsvPath &apos;C:\ClusterStorage\Volume1&apos;
.NOTES
    Author  : Thomas Lasswell (https://www.techcolumnist.com)
    Version : 1.0 (2026-06-10)
    Requires: Hyper-V and FailoverClusters modules, Kerberos constrained delegation between the hosts
#&gt;

[CmdletBinding()]
param (
    [Parameter(Mandatory = $true)]
    [string[]]$VMName,

    [Parameter(Mandatory = $true)]
    [string]$SourceCluster,

    [Parameter(Mandatory = $true)]
    [string]$DestinationCluster,

    [Parameter(Mandatory = $true)]
    [string]$DestinationHost,

    [Parameter(Mandatory = $true)]
    [string]$DestinationCsvPath,

    [switch]$Execute
)

$ErrorActionPreference = &apos;Stop&apos;
$sourceNodes = (Get-ClusterNode -Cluster $SourceCluster).Name
$supportedVersions = (Get-VMHostSupportedVersion -ComputerName $DestinationHost).Version | ForEach-Object { &quot;$_&quot; }

foreach ($name in $VMName) {
    $vm = Get-VM -ComputerName $sourceNodes -Name $name -ErrorAction SilentlyContinue | Select-Object -First 1

    if (-not $vm) {
        Write-Warning &quot;$name not found on $SourceCluster&quot;
        continue
    }

    $storagePath = Join-Path -Path $DestinationCsvPath -ChildPath $vm.Name
    $problems = @()

    if ($supportedVersions -notcontains &quot;$($vm.Version)&quot;) {
        $problems += &quot;Configuration version $($vm.Version) is not supported on $DestinationHost (Update-VMVersion needs a shutdown)&quot;
    }

    $report = Compare-VM -ComputerName $vm.ComputerName -Name $vm.Name -DestinationHost $DestinationHost -IncludeStorage -DestinationStoragePath $storagePath
    $problems += $report.Incompatibilities | ForEach-Object { &quot;$($_.MessageId): $($_.Message)&quot; }

    [PSCustomObject]@{
        VM       = $vm.Name
        Owner    = $vm.ComputerName
        Version  = &quot;$($vm.Version)&quot;
        SizeGB   = [math]::Round(((Get-VHD -ComputerName $vm.ComputerName -VMId $vm.VMId).FileSize | Measure-Object -Sum).Sum / 1GB, 1)
        Problems = if ($problems) { $problems -join &apos; | &apos; } else { &apos;None&apos; }
    }

    if (-not $Execute -or $problems) {
        continue
    }

    # Take the VM out of the old cluster&apos;s control; the VM keeps running on its owner node.
    Remove-ClusterGroup -Cluster $SourceCluster -VMId $vm.VMId -RemoveResources -Force

    try {
        $clock = [System.Diagnostics.Stopwatch]::StartNew()
        Move-VM -ComputerName $vm.ComputerName -Name $vm.Name -DestinationHost $DestinationHost -IncludeStorage -DestinationStoragePath $storagePath
        Write-Output &quot;$($vm.Name) moved to $DestinationHost in $([int]$clock.Elapsed.TotalMinutes) minutes&quot;
    } catch {
        Write-Warning &quot;Move of $($vm.Name) failed, restoring its clustered role on $SourceCluster : $($_.Exception.Message)&quot;
        Add-ClusterVirtualMachineRole -Cluster $SourceCluster -VMId $vm.VMId | Out-Null
        continue
    }

    Add-ClusterVirtualMachineRole -Cluster $DestinationCluster -VMName $vm.Name | Out-Null
    Get-ClusterGroup -Cluster $DestinationCluster -Name $vm.Name | Format-Table -Property Name, OwnerNode, State -AutoSize
}
</code></pre>
<p>A dry run produces a report like this, which is what we sequenced the schedule from:</p>
<pre><code class="language-text">VM        Owner    Version SizeGB Problems
--        -----    ------- ------ --------
file01    OLD-HV01 9.0      412.0 None
print01   OLD-HV02 9.0       60.0 None
legacy01  OLD-HV01 5.0       80.0 Configuration version 5.0 is not supported on new-hv01 (Update-VMVersion needs a shutdown)
</code></pre>
<p><code>Add-ClusterVirtualMachineRole</code> can&apos;t run inside a remote PowerShell session without CredSSP, so run the script in a local session on the management machine, not through <code>Enter-PSSession</code>.</p>
<h2>Sequencing to Protect the Business</h2>
<p>We didn&apos;t move everything at once, and not just because of bandwidth. Migrating VMs one at a time, starting with the lowest-risk, least-latency-sensitive workloads, gave us a chance to validate the new cluster&apos;s storage performance and network throughput under real migration load before committing anything that actually mattered to the timeline. It also meant that if a migration did have to be aborted partway through — which happened once, when a migration&apos;s network path saturated a link shared with a backup job we hadn&apos;t accounted for — the blast radius was one non-critical VM, not the whole schedule.</p>
<h2>What We&apos;d Repeat</h2>
<p>Check configuration versions and run <code>Compare-VM</code> for every VM before scheduling anything, and book the shutdowns that version upgrades and processor compatibility need. Set up constrained delegation early and test it with a throwaway VM. Move in ascending order of business criticality so early mistakes are cheap. And treat the network path for the migration traffic as a first-class resource to plan around, not spare capacity — the migrations that caused trouble were always the ones that collided with something else using the same link. None of the workloads went down. The migrations that felt uneventful were the ones where we&apos;d already found the surprises on something smaller first.</p>
<h2>References</h2>
<ul><li><a href="https://learn.microsoft.com/en-us/windows-server/virtualization/hyper-v/manage/use-live-migration-without-failover-clustering-to-move-a-virtual-machine">Use live migration without Failover Clustering to move a VM</a></li>
<li><a href="https://learn.microsoft.com/en-us/windows-server/virtualization/hyper-v/deploy/set-up-hosts-for-live-migration-without-failover-clustering">Set up hosts for live migration without Failover Clustering</a> (Kerberos, CredSSP and Windows Server 2025)</li>
<li><a href="https://learn.microsoft.com/en-us/windows-server/virtualization/hyper-v/processor-compatibility-mode">Processor compatibility for Hyper-V virtual machines</a></li>
<li><a href="https://learn.microsoft.com/en-us/windows-server/virtualization/hyper-v/deploy/upgrade-virtual-machine-version-in-hyper-v-on-windows-or-windows-server">Upgrade virtual machine version in Hyper-V</a> (supported versions per host OS)</li>
<li><a href="https://learn.microsoft.com/en-us/windows-server/failover-clustering/cluster-operating-system-rolling-upgrade">Cluster OS rolling upgrade</a></li>
<li><a href="https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2012-r2-and-2012/dn486772(v=ws.11)">Migration of highly available VMs using the Migrate a Cluster Wizard</a></li>
<li><a href="https://learn.microsoft.com/en-us/powershell/module/hyper-v/compare-vm">Compare-VM</a>, <a href="https://learn.microsoft.com/en-us/powershell/module/hyper-v/move-vm">Move-VM</a> and <a href="https://learn.microsoft.com/en-us/powershell/module/failoverclusters/add-clustervirtualmachinerole">Add-ClusterVirtualMachineRole</a></li>
<li><a href="https://learn.microsoft.com/en-us/windows-server/failover-clustering/configure-live-migration-smb-bandwidth">Control Live Migration SMB bandwidth cluster-wide</a></li>
</ul>
]]></content:encoded>
      <category>Engineering</category>
    </item>
    <item>
      <title>Hyper-V: Deploying a Two-Node Failover Cluster on a Budget</title>
      <link>https://www.techcolumnist.com/2026/06/03/hyper-v-deploying-a-two-node-failover-cluster-on-a-budget/</link>
      <guid isPermaLink="true">https://www.techcolumnist.com/2026/06/03/hyper-v-deploying-a-two-node-failover-cluster-on-a-budget/</guid>
      <pubDate>Wed, 03 Jun 2026 14:00:00 GMT</pubDate>
      <dc:creator>Tom Lasswell</dc:creator>
      <description>Building a two-node Hyper-V cluster without a SAN: Storage Spaces Direct requirements, nested resiliency, witness options, hardware rules and scripts to build and test it.</description>
      <content:encoded><![CDATA[<p>Every failover cluster design guide I read early on assumed a shared SAN, a fibre channel fabric, and a budget to match. Most of the small and mid-size environments I have supported have none of those things and still need two Hyper-V hosts that can survive one of them dying mid-shift. Here is how I have gotten a real two-node cluster onto hardware that would make a SAN vendor wince, with the Microsoft requirements that decide what &quot;budget&quot; is allowed to mean, and the scripts I use to build it and then try to break it.</p>
<h2>Storage Spaces Direct Instead of a SAN</h2>
<p>The single biggest budget lever is skipping shared storage entirely. Storage Spaces Direct (S2D) pools drives that are physically attached to one server each and mirrors data between the servers over the network, so the SAN, the fibre channel switches and the HBAs all disappear from the bill. The catch that surprises people pricing it: S2D needs Windows Server Datacenter edition on every node. Standard edition will not do it, so compare the Datacenter licences against the SAN you are not buying, not against nothing.</p>
<p>What Microsoft documents as the floor for a two-node build:</p>
<ul><li>Two to 16 servers, ideally the same make and model. Two is a supported number, not a hack.</li>
<li>At least four capacity drives per server (all-flash or all-NVMe), plus at least two cache drives per server if you mix media types, with the same number and type of drives in every server.</li>
<li>4 GB of RAM per terabyte of cache drive capacity on each server, on top of what the VMs need, for S2D metadata.</li>
<li>A 10 Gbps NIC or faster for a two- or three-node cluster, with two or more connections per node recommended. RDMA (iWARP or RoCE) and 25 Gbps are the recommendation for four nodes and up, and the deployment guide recommends RDMA in general.</li>
</ul>
<p>For a two-node cluster, a classic two-way mirror costs you half your raw capacity. Windows Server 2019 added nested resiliency, which exists only for exactly two nodes: a nested two-way mirror keeps two copies on each server (effectively a four-way mirror), so the volume survives a server down and a drive failing on the survivor at the same time. The price is capacity efficiency: 25% for nested two-way mirror, or roughly 35-40% for nested mirror-accelerated parity, depending on drive count and the mirror/parity split. Resiliency is chosen per volume, so I put the VMs I cannot lose on nested volumes and scratch or test workloads on classic mirror. You cannot convert a volume between resiliency types later, so decide before the first VM lands.</p>
<p>The interconnect matters more than people expect. Microsoft supports switchless interconnects, where every node has a direct connection to every other node. With two nodes that is just a pair of cables between two NICs, which removes the storage switch from the bill and is the cheapest supported topology. I have built more than one two-node cluster this way precisely because there is no third node that would need a switch to reach everyone else.</p>
<h2>The Witness Is Not Optional, and It Is Nearly Free</h2>
<p>A two-node cluster without a quorum witness is a coin flip waiting to happen. Microsoft&apos;s S2D guide is blunt about it: a two-server deployment requires a witness, otherwise if either server goes offline the other becomes unavailable. You have three realistic choices:</p>
<ul><li><strong>Cloud witness</strong>: a blob in an Azure Standard general-purpose v2 storage account (LRS if the cluster is on-premises), reached over HTTPS on port 443. The cluster creates an <code>msft-cloud-witness</code> container and can share one account across many clusters. Small branch-office clusters, including two-node ones, are an explicitly supported scenario, and there is no third machine on site.</li>
<li><strong>File share witness</strong>: an SMB 2+ share with at least 5 MB free, dedicated to one cluster. From Windows Server 2019 it can sit on a non-domain device, including a router with local USB storage, which is the no-internet, no-third-server option.</li>
<li><strong>Disk witness</strong>: needs shared storage, which an S2D cluster by definition does not have.</li>
</ul>
<p>I have stopped recommending a file share witness on a physical server in the same rack, and Microsoft&apos;s guidance agrees: the share should be physically separate from the nodes, down to network, power, rack or room. A witness that goes down with the same power event as your two nodes protects you against nothing. When the site has reliable outbound internet, cloud witness is my default.</p>
<h2>Used Enterprise Gear Beats New Consumer Gear</h2>
<p>Budget builds tempt people toward consumer NVMe drives and desktop-class NICs, and I understand the instinct when the alternative is an eye-watering enterprise SKU. Microsoft&apos;s hardware requirements settle the argument for drives: solid-state drives must provide power-loss protection, and cache drives are recommended at 3 drive-writes-per-day or more. Components need Windows Server Catalog certification for your OS version, and Microsoft recommends the Software-Defined Data Center (SDDC) Standard or Premium qualifications for servers and NICs. Drives have to reach Windows directly: a SAS HBA in pass-through, or direct-attached SATA or NVMe. A RAID controller that cannot pass physical devices through is not supported.</p>
<p>So the better budget move, in my experience, has been sourcing recently retired enterprise gear: a generation-old server with real enterprise NVMe that has power-loss protection, an HBA instead of a RAID card, and a NIC that appears in the catalog. It is still a fraction of the cost of a comparable current-generation SAN-attached build, and it behaves the way the clustering documentation assumes hardware behaves.</p>
<h2>Build It From a Script</h2>
<p>I use the general-purpose <a href="https://www.techcolumnist.com/2025/07/09/powershell-hyper-v-script-a-failover-cluster-deployment-end-to-end/">cluster deployment script</a> for most builds. For a two-node S2D cluster I also run the version below, which adds the pre-flight checks that matter at this size (edition, drive count, drive symmetry) and creates nested-resiliency volumes at the end. Run it from a management machine on the same Windows version as the nodes, in a local elevated session, after the nodes have Hyper-V and Failover Clustering installed and their drives have been wiped of old partitions. Tier creation follows Microsoft&apos;s nested resiliency steps: Windows Server 2019 needs the tier templates created once, and on 2022 the script only creates them if they are missing.</p>
<pre><code class="language-powershell">&lt;#
.SYNOPSIS
    Builds a two-node Storage Spaces Direct Hyper-V cluster with a cloud witness and nested two-way mirror volumes.
.DESCRIPTION
    Checks that both nodes run Datacenter edition and have the same number (four or more) and media types
    of poolable drives, validates with the Storage Spaces Direct test set, creates the cluster without storage,
    configures a cloud witness, enables S2D and creates nested two-way mirror CSV volumes. Prints the
    resulting virtual disks and quorum configuration.
.PARAMETER NodeNames
    The two cluster nodes.
.PARAMETER ClusterName
    NetBIOS name for the cluster, 15 characters or fewer.
.PARAMETER ClusterIPAddress
    Static IPv4 address for the cluster name.
.PARAMETER WitnessAccountName
    Azure storage account (Standard general-purpose v2) for the cloud witness.
.PARAMETER WitnessAccessKey
    Primary access key for that storage account.
.PARAMETER CapacityMediaType
    Media type of the capacity drives: SSD or HDD.
.PARAMETER VolumeNames
    Names of the nested two-way mirror volumes to create.
.PARAMETER VolumeSize
    Size of each volume.
.EXAMPLE
    .\New-TwoNodeS2DCluster.ps1 -NodeNames &apos;hv-node01&apos;, &apos;hv-node02&apos; -ClusterName &apos;hv-clu01&apos; -ClusterIPAddress &apos;10.10.10.50&apos; -WitnessAccountName &apos;&lt;storageaccount&gt;&apos; -WitnessAccessKey &apos;&lt;access-key&gt;&apos;
.NOTES
    Author  : Thomas Lasswell (https://www.techcolumnist.com)
    Version : 1.0 (2026-06-03)
    Requires: Windows Server 2019+ Datacenter nodes, FailoverClusters and Storage modules, WinRM
#&gt;

[CmdletBinding()]
param (
    [Parameter(Mandatory = $true)]
    [ValidateCount(2, 2)]
    [string[]]$NodeNames,

    [Parameter(Mandatory = $true)]
    [ValidateLength(1, 15)]
    [string]$ClusterName,

    [Parameter(Mandatory = $true)]
    [string]$ClusterIPAddress,

    [Parameter(Mandatory = $true)]
    [string]$WitnessAccountName,

    [Parameter(Mandatory = $true)]
    [string]$WitnessAccessKey,

    [Parameter(Mandatory = $false)]
    [ValidateSet(&apos;SSD&apos;, &apos;HDD&apos;)]
    [string]$CapacityMediaType = &apos;SSD&apos;,

    [Parameter(Mandatory = $false)]
    [string[]]$VolumeNames = @(&apos;Volume01&apos;),

    [Parameter(Mandatory = $false)]
    [UInt64]$VolumeSize = 1TB
)

$ErrorActionPreference = &apos;Stop&apos;
$firstNode = $NodeNames[0]

# Pre-flight: edition and drive symmetry.
$inventory = Invoke-Command -ComputerName $NodeNames -ScriptBlock {
    $operatingSystem = Get-CimInstance -ClassName Win32_OperatingSystem
    $poolable = @(Get-PhysicalDisk -CanPool $true)

    [PSCustomObject]@{
        Node          = $env:COMPUTERNAME
        Edition       = $operatingSystem.Caption
        PoolableDisks = $poolable.Count
        MediaTypes    = ($poolable | Group-Object -Property MediaType | Sort-Object -Property Name | ForEach-Object { &quot;$($_.Name) x$($_.Count)&quot; }) -join &apos;, &apos;
    }
}

$inventory | Format-Table -Property Node, Edition, PoolableDisks, MediaTypes -AutoSize

if ($inventory | Where-Object { $_.Edition -notmatch &apos;Datacenter&apos; }) {
    throw &apos;Storage Spaces Direct requires Windows Server Datacenter edition on every node.&apos;
}

if (@($inventory.MediaTypes | Sort-Object -Unique).Count -ne 1) {
    throw &apos;The nodes have different numbers or types of poolable drives. S2D expects the same number and type in every server.&apos;
}

if ($inventory | Where-Object { $_.PoolableDisks -lt 4 }) {
    throw &apos;Fewer than four poolable drives on a node. Windows Server needs at least four capacity drives per server.&apos;
}

# Validate with the S2D test set, as the Microsoft deployment guide does.
$report = Test-Cluster -Node $NodeNames -Include &apos;Storage Spaces Direct&apos;, &apos;Inventory&apos;, &apos;Network&apos;, &apos;System Configuration&apos;
Write-Output &quot;Validation report: $(($report | Where-Object { $_ -is [System.IO.FileInfo] }).FullName)&quot;

# Create the cluster without storage, then the witness, then S2D.
if (-not (Get-Cluster -Name $firstNode -ErrorAction SilentlyContinue)) {
    New-Cluster -Name $ClusterName -Node $NodeNames -StaticAddress $ClusterIPAddress -NoStorage | Out-Null
}

Set-ClusterQuorum -Cluster $firstNode -CloudWitness -AccountName $WitnessAccountName -AccessKey $WitnessAccessKey | Out-Null

if (-not (Get-StoragePool -CimSession $firstNode -IsPrimordial $false -ErrorAction SilentlyContinue)) {
    Enable-ClusterStorageSpacesDirect -CimSession $firstNode -Confirm:$false | Out-Null
}

# Nested two-way mirror tier template (required on Windows Server 2019, harmless if already present).
$mirrorTier = &quot;NestedMirrorOn$CapacityMediaType&quot;

if (-not (Get-StorageTier -CimSession $firstNode -FriendlyName $mirrorTier -ErrorAction SilentlyContinue)) {
    New-StorageTier -CimSession $firstNode -StoragePoolFriendlyName &apos;S2D*&apos; -FriendlyName $mirrorTier -ResiliencySettingName Mirror -MediaType $CapacityMediaType -NumberOfDataCopies 4 | Out-Null
}

# With HDD capacity (storage bus cache), stop caching writes once a node has been down for 30 minutes.
if ($CapacityMediaType -eq &apos;HDD&apos;) {
    Get-StorageSubSystem -CimSession $firstNode -FriendlyName &apos;Cluster*&apos; |
        Set-StorageHealthSetting -Name &apos;System.Storage.NestedResiliency.DisableWriteCacheOnNodeDown.Enabled&apos; -Value &apos;True&apos;
}

# New-Volume on S2D creates the virtual disk, formats it and adds it to Cluster Shared Volumes.
foreach ($volumeName in $VolumeNames) {
    if (-not (Get-VirtualDisk -CimSession $firstNode -FriendlyName $volumeName -ErrorAction SilentlyContinue)) {
        New-Volume -CimSession $firstNode -StoragePoolFriendlyName &apos;S2D*&apos; -FriendlyName $volumeName -FileSystem CSVFS_ReFS -StorageTierFriendlyNames $mirrorTier -StorageTierSizes $VolumeSize | Out-Null
    }
}

Get-VirtualDisk -CimSession $firstNode |
    Format-Table -Property FriendlyName, ResiliencySettingName, OperationalStatus, HealthStatus, Size -AutoSize

Get-ClusterQuorum -Cluster $firstNode | Format-List -Property Cluster, QuorumResource
</code></pre>
<h2>Test the Failure You Are Actually Buying Insurance Against</h2>
<p>The point of a two-node cluster is surviving the loss of one node, so that is the test that matters before you call the build done. I run it twice. First a planned drain, which proves live migration and storage resync behave; Microsoft&apos;s maintenance procedure is to confirm every volume is <code>Healthy</code>/<code>OK</code>, <code>Suspend-ClusterNode -Drain</code> (on Windows Server 2019, also <code>Enable-StorageMaintenanceMode</code> on the node&apos;s disks), do the work, take the disks out of maintenance mode on 2019, <code>Resume-ClusterNode -Failback Immediate</code>, then wait for <code>Get-StorageJob</code> to come back empty before touching the other node. Then the unplanned one: pull power on a host without warning and time how long the VMs take to come back on the survivor. I have seen budget builds pass every health check in Failover Cluster Manager and then take minutes to fail over in practice because the interconnect could not keep up with resynchronization traffic after a rebuild. Run the test before the cluster goes anywhere near production, not after the first real outage tells you the answer.</p>
<p>This script times both halves. It refuses to start unless every volume is healthy, drains and restarts one node, handling storage maintenance mode itself on Windows Server 2019 (or, with <code>-Unplanned</code>, has you pull its power), measures how long until every clustered role is online on the survivor, and then measures how long storage takes to resync.</p>
<pre><code class="language-powershell">&lt;#
.SYNOPSIS
    Times a planned drain or an unplanned node loss on a two-node S2D cluster, then times the storage resync.
.DESCRIPTION
    Refuses to start unless every virtual disk is Healthy. In planned mode it drains the target node,
    restarts it and resumes it with immediate failback; on Windows Server 2019 it puts the node&apos;s disks in
    storage maintenance mode before the restart and takes them out before the resume (2022 and later do this
    automatically). In unplanned mode the clock starts when the operator presses Enter, just before pulling
    power on the target node. It records how long until every clustered role is online on a surviving node,
    then how long until Get-StorageJob reports no repair jobs and every virtual disk is Healthy again.
.PARAMETER ClusterName
    The cluster to test.
.PARAMETER NodeName
    The node to take down.
.PARAMETER Unplanned
    Wait for the operator to cut power instead of draining and restarting the node.
.PARAMETER TimeoutMinutes
    How long to wait for each phase before giving up.
.EXAMPLE
    .\Test-TwoNodeFailover.ps1 -ClusterName &apos;hv-clu01&apos; -NodeName &apos;hv-node02&apos; -Unplanned
.NOTES
    Author  : Thomas Lasswell (https://www.techcolumnist.com)
    Version : 1.0 (2026-06-03)
    Requires: FailoverClusters and Storage modules; run from a machine that is not in the cluster
#&gt;

[CmdletBinding()]
param (
    [Parameter(Mandatory = $true)]
    [string]$ClusterName,

    [Parameter(Mandatory = $true)]
    [string]$NodeName,

    [switch]$Unplanned,

    [Parameter(Mandatory = $false)]
    [int]$TimeoutMinutes = 60
)

$ErrorActionPreference = &apos;Stop&apos;
$survivor = (Get-ClusterNode -Cluster $ClusterName | Where-Object { $_.Name -ne $NodeName }).Name

$unhealthy = Get-VirtualDisk -CimSession $survivor | Where-Object { $_.HealthStatus -ne &apos;Healthy&apos; }

if ($unhealthy) {
    throw &quot;Not safe to take a node down: $($unhealthy.FriendlyName -join &apos;, &apos;) not Healthy.&quot;
}

# Windows Server 2019 (build 17763) needs storage maintenance mode set by hand; 2022 (build 20348) and later do it on drain.
$manualStorageMaintenance = [int](Get-CimInstance -ClassName Win32_OperatingSystem -ComputerName $NodeName).BuildNumber -lt 20348

$roles = Get-ClusterGroup -Cluster $survivor | Where-Object { $_.Name -notin &apos;Cluster Group&apos;, &apos;Available Storage&apos; }
Write-Output &quot;Testing $($roles.Count) clustered roles; $NodeName goes down, $survivor survives&quot;

$clock = [System.Diagnostics.Stopwatch]::StartNew()

if ($Unplanned) {
    Read-Host &quot;Press Enter, then pull power on $NodeName immediately&quot;
    $clock.Restart()
} else {
    Suspend-ClusterNode -Cluster $survivor -Name $NodeName -Drain -Wait | Out-Null
    Write-Output &quot;Drain finished after $([int]$clock.Elapsed.TotalSeconds)s&quot;

    if ($manualStorageMaintenance) {
        Get-StorageScaleUnit -CimSession $survivor -FriendlyName $NodeName | Enable-StorageMaintenanceMode
    }

    Restart-Computer -ComputerName $NodeName -Force
}

# Phase 1: every role online on the survivor.
do {
    Start-Sleep -Seconds 5
    $pending = Get-ClusterGroup -Cluster $survivor |
        Where-Object { $_.Name -notin &apos;Cluster Group&apos;, &apos;Available Storage&apos; } |
        Where-Object { $_.State -ne &apos;Online&apos; -or $_.OwnerNode.Name -ne $survivor }
} while ($pending -and $clock.Elapsed.TotalMinutes -lt $TimeoutMinutes)

Write-Output &quot;Roles online on $survivor after $([int]$clock.Elapsed.TotalSeconds)s; still pending: $(@($pending).Count)&quot;

# Wait for the node to come back before measuring resync.
Read-Host &quot;Press Enter once $NodeName is powered on and shows Up or Paused in Get-ClusterNode&quot;

if (-not $Unplanned) {
    if ($manualStorageMaintenance) {
        Get-StorageScaleUnit -CimSession $survivor -FriendlyName $NodeName | Disable-StorageMaintenanceMode
    }

    Resume-ClusterNode -Cluster $survivor -Name $NodeName -Failback Immediate | Out-Null
}

# Phase 2: storage resync.
$clock.Restart()

do {
    Start-Sleep -Seconds 30
    $jobs = @(Get-StorageJob -CimSession $survivor | Where-Object { $_.JobState -eq &apos;Running&apos; })
    $degraded = @(Get-VirtualDisk -CimSession $survivor | Where-Object { $_.HealthStatus -ne &apos;Healthy&apos; })
    Write-Verbose &quot;$($jobs.Count) repair job(s) running, $($degraded.Count) volume(s) not Healthy&quot;
} while (($jobs.Count -gt 0 -or $degraded.Count -gt 0) -and $clock.Elapsed.TotalMinutes -lt $TimeoutMinutes)

Write-Output &quot;Storage resync finished after $([int]$clock.Elapsed.TotalMinutes) minutes&quot;
</code></pre>
<p>While resync runs, <code>Get-VirtualDisk</code> shows volumes as <code>InService</code>/<code>Warning</code>, which Microsoft documents as normal. The number to write down is the second one: until resync finishes, the cluster cannot lose the other node, so the resync time is your real window of exposure after any reboot, including every Patch Tuesday.</p>
<h2>The Real Budget Win Is Fewer Moving Parts</h2>
<p>A two-node S2D cluster with a cloud witness has fewer components to fail than a SAN-based equivalent: no fibre switches, no separate storage controller firmware to patch, no HBA driver compatibility matrix to track. The budget saving is not just the purchase price, it is the years of maintenance overhead that never gets billed anywhere but shows up as engineer time regardless.</p>
<h2>References</h2>
<ul><li><a href="https://learn.microsoft.com/en-us/windows-server/storage/storage-spaces/storage-spaces-direct-hardware-requirements">Storage Spaces Direct hardware requirements</a></li>
<li><a href="https://learn.microsoft.com/en-us/windows-server/storage/storage-spaces/deploy-storage-spaces-direct">Deploy Storage Spaces Direct on Windows Server</a></li>
<li><a href="https://learn.microsoft.com/en-us/windows-server/storage/storage-spaces/nested-resiliency">Nested resiliency for Storage Spaces Direct</a></li>
<li><a href="https://learn.microsoft.com/en-us/windows-server/failover-clustering/deploy-quorum-witness">Deploy a quorum witness for a failover cluster</a></li>
<li><a href="https://learn.microsoft.com/en-us/azure/azure-local/manage/maintain-servers?context=/windows-server/context/windows-server-storage">Taking a server offline for maintenance</a> (drain, resume and resync checks)</li>
<li><a href="https://learn.microsoft.com/en-us/powershell/module/failoverclusters/test-cluster">Test-Cluster</a> and <a href="https://learn.microsoft.com/en-us/powershell/module/failoverclusters/set-clusterquorum">Set-ClusterQuorum</a> cmdlet references</li>
</ul>
]]></content:encoded>
      <category>Engineering</category>
    </item>
    <item>
      <title>Data Warehouse: When to Stop Querying Production and Build a Warehouse</title>
      <link>https://www.techcolumnist.com/2026/05/27/data-warehouse-when-to-stop-querying-production-and-build-a-warehouse/</link>
      <guid isPermaLink="true">https://www.techcolumnist.com/2026/05/27/data-warehouse-when-to-stop-querying-production-and-build-a-warehouse/</guid>
      <pubDate>Wed, 27 May 2026 14:00:00 GMT</pubDate>
      <dc:creator>Tom Lasswell</dc:creator>
      <description>How to measure reporting load on a production Postgres database, the cheap fixes to try first, and the signals that mean a separate warehouse is finally justified.</description>
      <content:encoded><![CDATA[<p>Every organization I&apos;ve worked with starts the same way: someone needs a report, someone else knows enough SQL to write a query against the production database, and it works. It keeps working for a surprisingly long time, right up until the day it doesn&apos;t, and the move from &quot;querying production is fine&quot; to &quot;querying production is actively dangerous&quot; is gradual enough that most teams cross it without noticing. Building a warehouse is a real project with real cost, and I&apos;ve seen it justified both far too early and far too late. Here&apos;s how I actually decide, with the queries I use to replace gut feel with evidence. The examples use PostgreSQL because that&apos;s where I see this most often, but the reasoning carries over to any OLTP database.</p>
<h2>The tell isn&apos;t data volume, it&apos;s query shape</h2>
<p>The instinct is to think about warehouses in terms of row counts: &quot;we have ten million rows now, time for a warehouse.&quot; That&apos;s rarely the actual trigger. A well-indexed production table can serve point lookups against ten million rows all day without anyone noticing. What breaks things is query <em>shape</em>: a report that scans a large fraction of a table, joins across several large tables, or aggregates over a long time window. That kind of query competes with the transactional workload for the same buffer cache and the same I/O. A full scan against a hot table during business hours is what shows up as latency spikes for everyone else using the application at that moment.</p>
<h2>Measure it before you argue about it</h2>
<p>The conversation gets much shorter once you can show which queries are doing the work and who is running them. Two built-in tools cover most of it.</p>
<p><strong><code>pg_stat_statements</code></strong> keeps cumulative execution statistics for every normalized statement. It has to be preloaded, which means a restart:</p>
<pre><code class="language-ini"># postgresql.conf
shared_preload_libraries = &apos;pg_stat_statements&apos;
</code></pre>
<p>Then create it in the database you want to watch:</p>
<pre><code class="language-sql">CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
</code></pre>
<p><strong>Slow query logging</strong> catches individual long runs, including the one-off ad hoc query that never repeats often enough to top the cumulative stats. <code>log_min_duration_statement</code> logs every completed statement that ran at least that long. It&apos;s off (<code>-1</code>) by default, and it can be changed with a reload:</p>
<pre><code class="language-sql">ALTER SYSTEM SET log_min_duration_statement = &apos;2s&apos;;
SELECT pg_reload_conf();
</code></pre>
<p>The most useful single step is giving reporting its <strong>own login role</strong>, even if it&apos;s the same people. Every statistic below can then be split by role, and you get a place to hang guardrails. <code>pg_read_all_data</code> (PostgreSQL 14 and later) grants read access to every table, view, and sequence without handing out ownership. <code>ALTER ROLE ... SET</code> puts a hard ceiling on how long any one reporting query can run:</p>
<pre><code class="language-sql">CREATE ROLE reporting LOGIN PASSWORD &apos;&lt;password&gt;&apos;;
GRANT pg_read_all_data TO reporting;
ALTER ROLE reporting SET statement_timeout = &apos;60s&apos;;
ALTER ROLE reporting SET default_transaction_read_only = on;
</code></pre>
<p>With that in place, this query shows how much of the server&apos;s execution time and disk reads each role accounts for since the stats were last reset. Viewing other roles&apos; query text needs superuser or membership in <code>pg_read_all_stats</code>.</p>
<pre><code class="language-sql">SELECT r.rolname,
       sum(s.calls)                                        AS calls,
       round(sum(s.total_exec_time)::numeric / 1000)       AS exec_seconds,
       round((100 * sum(s.total_exec_time) / sum(sum(s.total_exec_time)) OVER ())::numeric, 1) AS pct_exec_time,
       sum(s.shared_blks_read)                             AS blocks_read_from_disk,
       sum(s.temp_blks_written)                            AS temp_blocks_written
FROM pg_stat_statements s
JOIN pg_roles r ON r.oid = s.userid
WHERE s.dbid = (SELECT oid FROM pg_database WHERE datname = current_database())
GROUP BY r.rolname
ORDER BY exec_seconds DESC;
</code></pre>
<p><code>shared_blks_read</code> counts blocks that weren&apos;t already in shared buffers, which is a decent proxy for &quot;this query is pushing the application&apos;s working set out of cache.&quot; <code>temp_blks_written</code> means sorts or hashes spilled to disk, the classic sign of a big aggregate or join.</p>
<p>To catch it in the act, check <code>pg_stat_activity</code> for long-running active queries:</p>
<pre><code class="language-sql">SELECT pid, usename, now() - query_start AS runtime, wait_event_type, wait_event,
       left(query, 100) AS query
FROM pg_stat_activity
WHERE backend_type = &apos;client backend&apos;
  AND state = &apos;active&apos;
  AND now() - query_start &gt; interval &apos;30 seconds&apos;
ORDER BY runtime DESC;
</code></pre>
<h2>A script to run weekly</h2>
<p>I run this every week (cron or a CI schedule) and paste the output into the thread whenever someone asks &quot;is reporting hurting production?&quot; It reports each role&apos;s share of execution time and disk reads, the top statements for the reporting roles, and anything running long right now.</p>
<p>It needs Python 3.10+, <code>psycopg2-binary</code>, the <code>pg_stat_statements</code> extension, and a role with <code>pg_read_all_stats</code>.</p>
<pre><code class="language-python">#!/usr/bin/env python3
&quot;&quot;&quot;
reporting_pressure.py

Summarizes how much of a PostgreSQL database&apos;s execution time and disk reads
come from reporting roles, using pg_stat_statements and pg_stat_activity.

Usage:
    python reporting_pressure.py --dsn &lt;dsn&gt; --reporting-roles reporting,metabase [--top 10]
Needs: pg_stat_statements installed in the database; a role with pg_read_all_stats.
&quot;&quot;&quot;

import argparse
import sys

import psycopg2

DB_FILTER = &quot;s.dbid = (SELECT oid FROM pg_database WHERE datname = current_database())&quot;

SHARE_SQL = f&quot;&quot;&quot;
    SELECT r.rolname = ANY(%s)          AS is_reporting,
           sum(s.total_exec_time)       AS exec_ms,
           sum(s.shared_blks_read)      AS blks_read,
           sum(s.temp_blks_written)     AS temp_written
    FROM pg_stat_statements s
    JOIN pg_roles r ON r.oid = s.userid
    WHERE {DB_FILTER}
    GROUP BY 1
&quot;&quot;&quot;

TOP_SQL = f&quot;&quot;&quot;
    SELECT r.rolname, s.calls,
           round(s.total_exec_time::numeric / 1000, 1) AS total_s,
           round(s.mean_exec_time::numeric, 1)         AS mean_ms,
           s.shared_blks_read,
           left(regexp_replace(s.query, &apos;\\s+&apos;, &apos; &apos;, &apos;g&apos;), 70) AS query
    FROM pg_stat_statements s
    JOIN pg_roles r ON r.oid = s.userid
    WHERE {DB_FILTER} AND r.rolname = ANY(%s)
    ORDER BY s.total_exec_time DESC
    LIMIT %s
&quot;&quot;&quot;

LONG_SQL = &quot;&quot;&quot;
    SELECT pid, usename, date_trunc(&apos;second&apos;, now() - query_start) AS runtime,
           left(regexp_replace(query, &apos;\\s+&apos;, &apos; &apos;, &apos;g&apos;), 70) AS query
    FROM pg_stat_activity
    WHERE backend_type = &apos;client backend&apos; AND state = &apos;active&apos;
      AND now() - query_start &gt; interval &apos;30 seconds&apos;
    ORDER BY runtime DESC
&quot;&quot;&quot;


def pct(part, whole):
    return 0.0 if not whole else 100.0 * float(part) / float(whole)


def main() -&gt; int:
    parser = argparse.ArgumentParser(description=&quot;Measure reporting load on a PostgreSQL database.&quot;)
    parser.add_argument(&quot;--dsn&quot;, required=True)
    parser.add_argument(&quot;--reporting-roles&quot;, required=True, help=&quot;Comma-separated role names&quot;)
    parser.add_argument(&quot;--top&quot;, type=int, default=10)
    args = parser.parse_args()
    roles = [r.strip() for r in args.reporting_roles.split(&quot;,&quot;) if r.strip()]

    conn = psycopg2.connect(args.dsn)
    try:
        with conn, conn.cursor() as cur:
            cur.execute(SHARE_SQL, (roles,))
            totals = {row[0]: row[1:] for row in cur.fetchall()}
            rep = totals.get(True, (0, 0, 0))
            other = totals.get(False, (0, 0, 0))
            print(&quot;Share of work from reporting roles since last stats reset:&quot;)
            for i, label in enumerate((&quot;execution time&quot;, &quot;blocks read from disk&quot;, &quot;temp blocks written&quot;)):
                print(f&quot;  {label:&lt;22} {pct(rep[i], rep[i] + other[i]):5.1f}%&quot;)

            cur.execute(TOP_SQL, (roles, args.top))
            print(f&quot;\nTop {args.top} reporting statements by total time:&quot;)
            for rolname, calls, total_s, mean_ms, blks, query in cur.fetchall():
                print(f&quot;  {rolname:&lt;12} {calls:&gt;8} calls {total_s:&gt;9}s total {mean_ms:&gt;9}ms avg {blks:&gt;10} blks  {query}&quot;)

            cur.execute(LONG_SQL)
            running = cur.fetchall()
            print(f&quot;\nActive queries over 30s right now: {len(running)}&quot;)
            for pid, user, runtime, query in running:
                print(f&quot;  pid {pid} {user} {runtime}  {query}&quot;)
    finally:
        conn.close()
    return 0


if __name__ == &quot;__main__&quot;:
    sys.exit(main())
</code></pre>
<p>Sample output:</p>
<pre><code class="language-text">Share of work from reporting roles since last stats reset:
  execution time          41.3%
  blocks read from disk   67.8%
  temp blocks written     88.2%

Top 10 reporting statements by total time:
  metabase         1440 calls    9312.4s total    6466.9ms avg   48211904 blks  SELECT t.client_id, date_trunc($1, t.created_at) AS month, count(*) ...
  reporting          96 calls    2210.7s total   23028.1ms avg   20113310 blks  SELECT * FROM tickets t JOIN ticket_events e ON e.ticket_id = t.id ...

Active queries over 30s right now: 1
  pid 48122 metabase 0:01:12  SELECT t.client_id, date_trunc($1, t.created_at) AS month, count(*) ...
</code></pre>
<p>Those numbers are illustrative. The pattern to look for is a small number of reporting calls accounting for an outsized share of disk reads and temp spill. That shape means a handful of reports is doing most of the damage.</p>
<h2>Try the cheap fixes first</h2>
<p>Each of these patches one symptom, and each one is much cheaper than a warehouse:</p>
<ul><li><strong>A read replica.</strong> Streaming replication gives you a hot standby that accepts read-only queries. The catch is documented plainly: when replaying WAL on the standby conflicts with a running query (vacuum on the primary removing rows the query can still see, for example), the standby waits up to <code>max_standby_streaming_delay</code> and then cancels the query. Setting <code>hot_standby_feedback = on</code> prevents those cleanup conflicts, but it delays dead-row cleanup on the primary and can cause table bloat there. Long reports on a replica are a trade-off, not a free lunch.</li>
<li><strong>Logical replication of a few tables.</strong> If reports only need <code>tickets</code>, <code>clients</code>, and <code>time_entries</code>, publish just those to a separate reporting database, where you&apos;re free to add indexes and materialized views production would never tolerate:<pre><code class="language-sql">-- on the production (publisher) database; requires wal_level = logical.
-- Each table needs a primary key (or REPLICA IDENTITY), or UPDATE and DELETE on it fail.
-- repuser needs LOGIN, REPLICATION, SELECT on the tables, and a pg_hba.conf entry.
CREATE PUBLICATION reporting_pub FOR TABLE tickets, clients, time_entries;

-- on the reporting (subscriber) database, after creating the same tables
CREATE SUBSCRIPTION reporting_sub
    CONNECTION &apos;host=&lt;prod-host&gt; dbname=app user=repuser password=&lt;password&gt;&apos;
    PUBLICATION reporting_pub;
</code></pre>
<br>The PostgreSQL docs point out that schema and DDL changes are not replicated. Every production migration that touches those tables has to be applied to the subscriber by hand.</li>
<li><strong>Materialized views on the replica or reporting database</strong> for the few heavy aggregates everyone reuses, refreshed on a schedule. <code>REFRESH MATERIALIZED VIEW CONCURRENTLY</code> keeps readers unblocked, but it requires a unique index on the view that uses plain column names and covers all rows.</li>
</ul>
<h2>Schema-for-writes and schema-for-reading are different jobs</h2>
<p>Production schemas are normalized to make writes safe and consistent, which is exactly the wrong shape for the ad hoc, wide, historical queries reporting wants. I&apos;ve watched analysts write eight-way joins to answer a question that a denormalized fact table would answer in one. That&apos;s not an analyst skill problem. It&apos;s a sign the two workloads want different physical layouts of the same data, and serving both from one schema means one of them is always going to be awkward. A replica doesn&apos;t fix this, since it has the same schema. Logical replication into a separate database starts to, because you can reshape the data there.</p>
<h2>Historical questions are a different signal than current-state questions</h2>
<p>Production databases are optimized to answer &quot;what is true right now,&quot; and most are actively hostile to &quot;what was true a year ago.&quot; Old rows get updated in place, soft-deleted, or archived out as normal operational hygiene. Once a question needs trend data, period-over-period comparison, or &quot;what did this record look like before it changed,&quot; you&apos;re asking production for data that no longer exists. No index fixes that.</p>
<p>The honest workaround is to start capturing history yourself, and the moment you do, you&apos;ve started a warehouse. For example, a nightly snapshot of open tickets is enough to answer &quot;how big was the backlog on the first of each month&quot; going forward:</p>
<pre><code class="language-sql">CREATE TABLE IF NOT EXISTS reporting.ticket_daily_snapshot (
    snapshot_date date NOT NULL,
    ticket_id     bigint NOT NULL,
    client_id     bigint,
    status        text,
    priority      text,
    assigned_team text,
    PRIMARY KEY (snapshot_date, ticket_id)
);

INSERT INTO reporting.ticket_daily_snapshot
SELECT current_date, t.id, t.client_id, t.status, t.priority, t.assigned_team
FROM tickets t
WHERE t.status NOT IN (&apos;closed&apos;, &apos;cancelled&apos;)
ON CONFLICT (snapshot_date, ticket_id) DO NOTHING;
</code></pre>
<p>It can&apos;t reconstruct the past, which is exactly why it&apos;s worth starting before anyone asks.</p>
<h2>The actual trigger, in practice</h2>
<p>The point where I stop resisting a warehouse project is when at least two of these are true at once:</p>
<ol><li>Reporting queries show up in the slow query log, or at the top of the <code>pg_stat_statements</code> breakdown, against tables the application also writes to, and the replica or timeout patches have already been tried.</li>
<li>Someone is asking a question that needs data production has already purged or overwritten.</li>
<li>More than one team wants a version of &quot;the same&quot; report with slightly different definitions of the same metric. That&apos;s really a request for a shared, agreed-upon source of truth, not another one-off query.</li>
</ol>
<p>Any one of those alone can usually be patched: a read replica, an archive table, a shared view. All three together mean the patches have stopped being cheaper than the project, and it&apos;s time to build the thing properly instead of adding one more workaround to production.</p>
<p>When it is time, the warehouse doesn&apos;t have to be big. A second Postgres fed by logical replication or scheduled loads works. So does a managed warehouse: BigQuery, for example, doesn&apos;t charge for batch load jobs on its default shared slot pool, gives 1 TiB of on-demand query processing free per month, and lists $6.25 per TiB after that in US regions as of this writing (check the pricing page for your region). The loading side is covered in <a href="https://www.techcolumnist.com/2025/12/17/python-data-warehouse-incremental-loads-from-postgres-to-bigquery/">incremental loads from Postgres to BigQuery</a>. What goes on top of it, when there&apos;s no BI team to own it, is in <a href="https://www.techcolumnist.com/2026/05/20/data-warehouse-building-a-reporting-layer-without-a-bi-team/">building a reporting layer without a BI team</a>.</p>
<h2>References</h2>
<ul><li><a href="https://www.postgresql.org/docs/current/pgstatstatements.html">PostgreSQL: pg_stat_statements</a></li>
<li><a href="https://www.postgresql.org/docs/current/runtime-config-logging.html">PostgreSQL: error reporting and logging (log_min_duration_statement)</a></li>
<li><a href="https://www.postgresql.org/docs/current/monitoring-stats.html">PostgreSQL: the cumulative statistics system (pg_stat_activity)</a></li>
<li><a href="https://www.postgresql.org/docs/current/predefined-roles.html">PostgreSQL: predefined roles (pg_read_all_data, pg_read_all_stats)</a></li>
<li><a href="https://www.postgresql.org/docs/current/hot-standby.html">PostgreSQL: hot standby and handling query conflicts</a></li>
<li><a href="https://www.postgresql.org/docs/current/logical-replication-quick-setup.html">PostgreSQL: logical replication quick setup</a></li>
<li><a href="https://www.postgresql.org/docs/current/logical-replication-restrictions.html">PostgreSQL: logical replication restrictions</a></li>
<li><a href="https://www.postgresql.org/docs/current/sql-refreshmaterializedview.html">PostgreSQL: REFRESH MATERIALIZED VIEW</a></li>
<li><a href="https://cloud.google.com/bigquery/pricing">BigQuery pricing</a></li>
</ul>
]]></content:encoded>
      <category>Engineering</category>
      <category>Strategy</category>
    </item>
    <item>
      <title>Data Warehouse: Building a Reporting Layer Without a BI Team</title>
      <link>https://www.techcolumnist.com/2026/05/20/data-warehouse-building-a-reporting-layer-without-a-bi-team/</link>
      <guid isPermaLink="true">https://www.techcolumnist.com/2026/05/20/data-warehouse-building-a-reporting-layer-without-a-bi-team/</guid>
      <pubDate>Wed, 20 May 2026 14:00:00 GMT</pubDate>
      <dc:creator>Tom Lasswell</dc:creator>
      <description>A practical build for an IT operations reporting layer with no BI team: one Postgres database, raw/staging/marts schemas, an API loader script, and freshness checks.</description>
      <content:encoded><![CDATA[<p>Every infrastructure team eventually piles up data it can&apos;t answer questions with. Ticket volumes live in the PSA, uptime lives in the monitoring platform, change records live in a spreadsheet someone started three years ago and never stopped using. Leadership asks a reasonable question, like &quot;which client&apos;s environment generates the most after-hours tickets,&quot; and the honest answer is that nobody can produce it without a day of manual exporting and VLOOKUPs. A BI team would fix this properly. Most IT organizations I&apos;ve worked with don&apos;t have one and won&apos;t get one budgeted anytime soon. The reporting layer still has to get built, just by whoever&apos;s already in the room.</p>
<p>This post is the build I&apos;d reach for in that situation, with the actual SQL and the loader script. Everything runs on one PostgreSQL database and a scheduler you already have.</p>
<h2>Start with one source of truth, not five</h2>
<p>The instinct when you finally get permission to build something is to connect everything at once (the PSA, the RMM, the monitoring tool, the identity provider) and design a grand unified model. That&apos;s how these projects die before they ship anything. I&apos;ve had better luck picking the single dataset that answers the most urgent recurring question, building a small, ugly, correct pipeline for just that, and shipping a report people actually use within the first month. Momentum and trust come from something working, not from an architecture diagram.</p>
<p>For most IT operations teams that first dataset is tickets. It answers volume, response and resolution time, and backlog questions, and every PSA has some kind of API for it.</p>
<h2>Pick boring tools on purpose</h2>
<p>Without a BI team, there&apos;s no one to maintain a Snowflake instance with a dbt pipeline feeding a Looker deployment. That&apos;s fine, because that stack solves a scale problem a shop this size doesn&apos;t have yet. A single Postgres database (or a managed one: Cloud SQL, Azure Database for PostgreSQL, RDS), a few scheduled scripts doing extract-and-load, and a reporting tool the organization already licenses will carry an IT operations reporting need further than the fancy version. It&apos;s something the same one or two people who built it can actually keep running.</p>
<p>The one structural decision worth making up front is three schemas with three roles, so nobody has to remember which tables are safe to point a dashboard at:</p>
<table><thead><tr><th>Schema</th><th>Holds</th><th>Written by</th><th>Read by</th></tr>
</thead><tbody><tr><td><code>raw</code></td><td>API responses as landed, one row per source record, JSON payload intact</td><td><code>etl_loader</code></td><td><code>transformer</code></td></tr>
<tr><td><code>staging</code></td><td>Views that pull typed, cleaned columns out of <code>raw</code></td><td><code>transformer</code></td><td><code>transformer</code></td></tr>
<tr><td><code>marts</code></td><td>Metric views and tables the dashboards use</td><td><code>transformer</code></td><td><code>report_reader</code></td></tr>
</tbody></table>
<pre><code class="language-sql">CREATE SCHEMA IF NOT EXISTS raw;
CREATE SCHEMA IF NOT EXISTS staging;
CREATE SCHEMA IF NOT EXISTS marts;

CREATE ROLE etl_loader    LOGIN PASSWORD &apos;&lt;password&gt;&apos;;
CREATE ROLE transformer   LOGIN PASSWORD &apos;&lt;password&gt;&apos;;
CREATE ROLE report_reader LOGIN PASSWORD &apos;&lt;password&gt;&apos;;

-- loader owns raw
GRANT USAGE, CREATE ON SCHEMA raw TO etl_loader;

-- transformer reads raw, builds staging and marts
GRANT USAGE ON SCHEMA raw TO transformer;
ALTER DEFAULT PRIVILEGES FOR ROLE etl_loader IN SCHEMA raw GRANT SELECT ON TABLES TO transformer;
GRANT USAGE, CREATE ON SCHEMA staging, marts TO transformer;

-- dashboards see marts only, including views created later
GRANT USAGE ON SCHEMA marts TO report_reader;
ALTER DEFAULT PRIVILEGES FOR ROLE transformer IN SCHEMA marts GRANT SELECT ON TABLES TO report_reader;
ALTER ROLE report_reader SET statement_timeout = &apos;60s&apos;;
</code></pre>
<p><code>ALTER DEFAULT PRIVILEGES ... FOR ROLE</code> applies to objects that role creates in the future. Without it, every new view is invisible to the dashboard account until someone remembers to <code>GRANT</code> it, which is exactly the kind of tribal knowledge that doesn&apos;t survive a handoff. Default privileges don&apos;t reach back to existing objects, so grant those once by hand.</p>
<h2>The extract step is where most of the effort goes</h2>
<p>Nobody warns you that the actual warehouse part, a database with some fact tables, is the easy part. The hard part is getting clean, consistent data out of tools that were never designed to be queried by anything other than their own UI. PSA and RMM APIs paginate inconsistently, rate-limit without clear documentation, and return null in places their own UI quietly fills in a default. Budget twice the time you think you need for extraction and normalization, and assume every source has at least one field that means something different than its name suggests.</p>
<p>Two habits make that manageable:</p>
<ol><li><strong>Land the raw payload untouched.</strong> Store each record&apos;s full JSON in a <code>jsonb</code> column and pull typed columns out later in a view. When you discover the <code>closed_date</code> field means something odd, you fix a view, not a reload of two years of history.</li>
<li><strong>Upsert on the source ID.</strong> Re-running the loader, or overlapping two runs, should never create duplicates.</li>
</ol>
<p>The loader below does both. It&apos;s written against a generic REST API that returns a JSON array per page and supports an <code>updated since</code> filter, and it follows an RFC 8288 <code>Link: &lt;...&gt;; rel=&quot;next&quot;</code> header for pagination. That&apos;s the part you adapt per vendor. It honors <code>429 Too Many Requests</code> with a <code>Retry-After</code> header given in seconds, falling back to exponential backoff otherwise (RFC 6585 says servers <em>may</em> send one), and it writes a row to <code>raw.etl_runs</code> so the pipeline&apos;s health is queryable. It needs Python 3.10+, <code>requests</code>, and <code>psycopg2-binary</code>.</p>
<pre><code class="language-sql">CREATE TABLE IF NOT EXISTS raw.psa_tickets (
    source_id  text PRIMARY KEY,
    payload    jsonb NOT NULL,
    loaded_at  timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE IF NOT EXISTS raw.etl_runs (
    run_id      bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    source      text NOT NULL,
    started_at  timestamptz NOT NULL,
    finished_at timestamptz,
    status      text NOT NULL,
    rows_loaded integer,
    error       text
);
</code></pre>
<pre><code class="language-python">#!/usr/bin/env python3
&quot;&quot;&quot;
load_api_to_raw.py

Pulls records changed since the last successful run from a paginated REST API
and upserts them into a raw jsonb landing table in PostgreSQL. Records every
run (success or failure) in raw.etl_runs.

Usage:
    PSA_TOKEN=... python load_api_to_raw.py --dsn &lt;dsn&gt; --source psa_tickets \
        --url https://psa.example.com/api/v1/tickets --since-param updatedSince
Reads:  the API at --url (bearer token from PSA_TOKEN); raw.etl_runs.
Writes: raw.&lt;source&gt; (upsert on source_id); one row in raw.etl_runs.
&quot;&quot;&quot;

import argparse
import datetime as dt
import os
import sys
import time
from urllib.parse import urljoin

import psycopg2
import requests
from psycopg2 import sql
from psycopg2.extras import Json, execute_values

MAX_RETRIES = 5


def last_success(cur, source):
    cur.execute(
        &quot;SELECT max(started_at) FROM raw.etl_runs WHERE source = %s AND status = &apos;success&apos;&quot;,
        (source,),
    )
    return cur.fetchone()[0]


def fetch_pages(session, url, params):
    &quot;&quot;&quot;Yield one page (a list of records) at a time, following Link rel=next.&quot;&quot;&quot;
    while url:
        for attempt in range(MAX_RETRIES):
            response = session.get(url, params=params, timeout=60)
            if response.status_code != 429:
                break
            retry_after = response.headers.get(&quot;Retry-After&quot;, &quot;&quot;)
            time.sleep(int(retry_after) if retry_after.isdigit() else 2 ** attempt)
        response.raise_for_status()
        yield response.json()
        next_url = response.links.get(&quot;next&quot;, {}).get(&quot;url&quot;)
        url = urljoin(response.url, next_url) if next_url else None  # RFC 8288 allows relative links
        params = None  # the next link already carries the query string


def main() -&gt; int:
    parser = argparse.ArgumentParser(description=&quot;Load changed API records into a raw jsonb table.&quot;)
    parser.add_argument(&quot;--dsn&quot;, required=True)
    parser.add_argument(&quot;--source&quot;, required=True, help=&quot;Raw table name, e.g. psa_tickets&quot;)
    parser.add_argument(&quot;--url&quot;, required=True)
    parser.add_argument(&quot;--since-param&quot;, default=&quot;updatedSince&quot;)
    parser.add_argument(&quot;--id-field&quot;, default=&quot;id&quot;)
    parser.add_argument(&quot;--overlap-minutes&quot;, type=int, default=15)
    args = parser.parse_args()

    session = requests.Session()
    session.headers[&quot;Authorization&quot;] = f&quot;Bearer {os.environ[&apos;PSA_TOKEN&apos;]}&quot;
    started = dt.datetime.now(dt.timezone.utc)
    upsert = sql.SQL(
        &quot;INSERT INTO {table} (source_id, payload) VALUES %s &quot;
        &quot;ON CONFLICT (source_id) DO UPDATE SET payload = EXCLUDED.payload, loaded_at = now()&quot;
    ).format(table=sql.Identifier(&quot;raw&quot;, args.source))

    conn = psycopg2.connect(args.dsn)
    conn.autocommit = True
    rows = 0
    try:
        with conn.cursor() as cur:
            since = last_success(cur, args.source)
            params = {}
            if since:
                params[args.since_param] = (since - dt.timedelta(minutes=args.overlap_minutes)).isoformat()
            for page in fetch_pages(session, args.url, params):
                values = [(str(record[args.id_field]), Json(record)) for record in page]
                if values:
                    execute_values(cur, upsert.as_string(conn), values, page_size=500)
                    rows += len(values)
            cur.execute(
                &quot;INSERT INTO raw.etl_runs (source, started_at, finished_at, status, rows_loaded) &quot;
                &quot;VALUES (%s, %s, now(), &apos;success&apos;, %s)&quot;,
                (args.source, started, rows),
            )
        print(f&quot;{args.source}: {rows} records upserted&quot;)
        return 0
    except Exception as error:
        with conn.cursor() as cur:
            cur.execute(
                &quot;INSERT INTO raw.etl_runs (source, started_at, finished_at, status, rows_loaded, error) &quot;
                &quot;VALUES (%s, %s, now(), &apos;failed&apos;, %s, %s)&quot;,
                (args.source, started, rows, str(error)[:2000]),
            )
        print(f&quot;{args.source}: failed after {rows} records: {error}&quot;, file=sys.stderr)
        return 1
    finally:
        conn.close()


if __name__ == &quot;__main__&quot;:
    sys.exit(main())
</code></pre>
<p>The staging view is where the vendor&apos;s field names become yours, and where the &quot;null means default&quot; surprises get handled once:</p>
<pre><code class="language-sql">CREATE OR REPLACE VIEW staging.stg_tickets AS
SELECT
    source_id                                           AS ticket_id,
    (payload -&gt;&gt; &apos;companyId&apos;)::bigint                   AS client_id,
    lower(trim(payload -&gt;&gt; &apos;status&apos;))                   AS status,
    coalesce(payload -&gt;&gt; &apos;priority&apos;, &apos;p3&apos;)              AS priority,  -- UI shows P3 when unset
    payload -&gt;&gt; &apos;queue&apos;                                 AS queue,
    (payload -&gt;&gt; &apos;createdAt&apos;)::timestamptz              AS created_at,
    (payload -&gt;&gt; &apos;firstResponseAt&apos;)::timestamptz        AS first_response_at,
    (payload -&gt;&gt; &apos;resolvedAt&apos;)::timestamptz             AS resolved_at,
    loaded_at
FROM raw.psa_tickets;
</code></pre>
<p>The JSON field names are placeholders for whatever your PSA returns. The pattern is the point. From here, metric views go in <code>marts</code>. I cover how to keep those consistent in <a href="https://www.techcolumnist.com/2026/08/19/data-warehouse-reusable-sql-models-for-it-operations-metrics/">reusable SQL models for IT operations metrics</a>. The answer to the after-hours question from the intro ends up being one short query against a staging view, instead of a day in Excel:</p>
<pre><code class="language-sql">SELECT client_id,
       count(*) FILTER (
           WHERE extract(isodow FROM created_at AT TIME ZONE &apos;America/Chicago&apos;) IN (6, 7)
              OR (created_at AT TIME ZONE &apos;America/Chicago&apos;)::time NOT BETWEEN &apos;08:00&apos; AND &apos;17:00&apos;
       ) AS after_hours_tickets,
       count(*) AS all_tickets
FROM staging.stg_tickets
WHERE created_at &gt;= now() - interval &apos;90 days&apos;
GROUP BY client_id
ORDER BY after_hours_tickets DESC
LIMIT 10;
</code></pre>
<h2>Ownership has to survive the person who built it</h2>
<p>The real risk in a no-BI-team reporting layer isn&apos;t the initial build. It&apos;s the day the person who built it moves teams or leaves. I&apos;ve inherited more than one of these pipelines as a pile of undocumented scripts running on someone&apos;s forgotten scheduled task, silently failing for months because no alert was ever wired up. Every pipeline needs a runbook, a named backup owner even if that person only touches it twice a year, and monitoring on the pipeline itself, not just the dashboards it feeds, so a failure surfaces before three months of reports quietly go stale.</p>
<p>Put the ownership in the database, next to the data, where the next person will actually find it:</p>
<pre><code class="language-sql">CREATE TABLE IF NOT EXISTS raw.pipeline_owners (
    source          text PRIMARY KEY,
    owner           text NOT NULL,
    backup_owner    text NOT NULL,
    runbook_url     text NOT NULL,
    max_staleness   interval NOT NULL
);

INSERT INTO raw.pipeline_owners VALUES
    (&apos;psa_tickets&apos;, &apos;ops-lead@example.com&apos;, &apos;sysadmin2@example.com&apos;,
     &apos;https://wiki.example.com/reporting/psa-tickets&apos;, interval &apos;2 hours&apos;)
ON CONFLICT (source) DO NOTHING;
</code></pre>
<p>Then a freshness view that turns &quot;is this data current?&quot; into a query any dashboard can show at the top of the page:</p>
<pre><code class="language-sql">CREATE OR REPLACE VIEW marts.pipeline_freshness AS
SELECT o.source,
       o.owner,
       o.backup_owner,
       o.runbook_url,
       max(r.finished_at) FILTER (WHERE r.status = &apos;success&apos;)          AS last_success,
       now() - max(r.finished_at) FILTER (WHERE r.status = &apos;success&apos;)  AS age,
       coalesce(now() - max(r.finished_at) FILTER (WHERE r.status = &apos;success&apos;) &gt; o.max_staleness, true) AS is_stale
FROM raw.pipeline_owners o
LEFT JOIN raw.etl_runs r ON r.source = o.source
GROUP BY o.source, o.owner, o.backup_owner, o.runbook_url, o.max_staleness;
</code></pre>
<p>And a check that fails loudly. Cron mails a job&apos;s output to the <code>MAILTO</code> address, so a script that prints only when something is wrong turns a stale source into an email naming the owner and the runbook:</p>
<pre><code class="language-bash">#!/usr/bin/env bash
# check_freshness.sh: print stale pipelines and exit 1 if any exist.
# Needs psql and READER_DSN (a role that can read marts) in /opt/reporting/env.
set -euo pipefail
source /opt/reporting/env

stale=$(psql &quot;$READER_DSN&quot; --no-align --tuples-only --field-separator=&apos; | &apos; --command \
  &quot;SELECT source, coalesce(age::text, &apos;never&apos;), owner, backup_owner, runbook_url
     FROM marts.pipeline_freshness WHERE is_stale&quot;)

if [[ -n &quot;$stale&quot; ]]; then
  echo &quot;Stale reporting pipelines (source | age | owner | backup | runbook):&quot;
  echo &quot;$stale&quot;
  exit 1
fi
</code></pre>
<p>The env file holds <code>LOADER_DSN</code>, <code>READER_DSN</code>, and <code>PSA_TOKEN</code>, and is readable only by the service account. Keep passwords out of the DSNs and put them in the service account&apos;s <code>~/.pgpass</code> (mode <code>0600</code>): the DSNs end up on the <code>psql</code> and Python command lines, where <code>ps</code> shows them to any local user. A small wrapper runs the loader:</p>
<pre><code class="language-bash">#!/usr/bin/env bash
# run_psa_tickets.sh: load PSA tickets; stays quiet on success, prints errors on failure.
set -euo pipefail
source /opt/reporting/env
export PSA_TOKEN
/opt/reporting/load_api_to_raw.py --dsn &quot;$LOADER_DSN&quot; --source psa_tickets \
    --url https://psa.example.com/api/v1/tickets --since-param updatedSince &gt;/dev/null
</code></pre>
<pre><code class="language-text"># crontab for the reporting service account
MAILTO=reporting-alerts@example.com
*/30 * * * *  /opt/reporting/run_psa_tickets.sh
15 * * * *    /opt/reporting/check_freshness.sh
</code></pre>
<p>The loader&apos;s stdout goes to <code>/dev/null</code> but stderr doesn&apos;t, so failures still reach the mailbox. Create <code>raw.etl_runs</code> and <code>raw.pipeline_owners</code> as <code>etl_loader</code>, so the default privileges above let <code>transformer</code> (which owns the freshness view) read them. It&apos;s crude, and it&apos;s the kind of alerting that still works three years after its author left.</p>
<h2>It doesn&apos;t need to be elegant to be worth it</h2>
<p>The reporting layers that succeed in this kind of environment aren&apos;t the technically impressive ones. They&apos;re the ones that answer the three or four questions leadership actually asks on a regular cadence, reliably enough that people stop pulling manual exports to double-check them. That&apos;s a lower bar than a proper BI team would set for itself, and it&apos;s still a real improvement over the spreadsheet it replaced. If the load on that single database eventually becomes the problem, that&apos;s a good problem, and <a href="https://www.techcolumnist.com/2026/05/27/data-warehouse-when-to-stop-querying-production-and-build-a-warehouse/">when to stop querying production</a> covers how to tell.</p>
<h2>References</h2>
<ul><li><a href="https://www.postgresql.org/docs/current/sql-alterdefaultprivileges.html">PostgreSQL: ALTER DEFAULT PRIVILEGES</a></li>
<li><a href="https://www.postgresql.org/docs/current/sql-alterrole.html">PostgreSQL: ALTER ROLE (per-role settings such as statement_timeout)</a></li>
<li><a href="https://www.postgresql.org/docs/current/functions-json.html">PostgreSQL: JSON functions and operators</a></li>
<li><a href="https://www.postgresql.org/docs/current/sql-expressions.html">PostgreSQL: aggregate expressions and FILTER</a></li>
<li><a href="https://www.psycopg.org/docs/extras.html">psycopg2.extras: execute_values and Json</a></li>
<li><a href="https://www.rfc-editor.org/rfc/rfc6585#section-4">RFC 6585, section 4: 429 Too Many Requests</a></li>
<li><a href="https://www.rfc-editor.org/rfc/rfc8288">RFC 8288: Web Linking (the Link header)</a></li>
<li><a href="https://man7.org/linux/man-pages/man5/crontab.5.html">crontab(5): MAILTO</a></li>
</ul>
]]></content:encoded>
      <category>Engineering</category>
      <category>Strategy</category>
    </item>
    <item>
      <title>Google Cloud: Organization Policy Constraints That Actually Matter</title>
      <link>https://www.techcolumnist.com/2026/05/13/google-cloud-organization-policy-constraints-that-actually-matter/</link>
      <guid isPermaLink="true">https://www.techcolumnist.com/2026/05/13/google-cloud-organization-policy-constraints-that-actually-matter/</guid>
      <pubDate>Wed, 13 May 2026 14:00:00 GMT</pubDate>
      <dc:creator>Tom Lasswell</dc:creator>
      <description>Which Google Cloud organization policy constraints prevent real incidents, with policy YAML, the dry-run workflow, tag-based exemptions, and an audit script.</description>
      <content:encoded><![CDATA[<p>Google Cloud ships a long catalog of Organization Policy constraints, and the temptation the first time you&apos;re handed org-level admin is to enable a defensible-looking chunk of them and call it a security baseline. I did that once, broke three teams&apos; CI pipelines in the same afternoon, and spent the following weeks learning which constraints actually stop a bad day and which ones just make an audit report look thorough.</p>
<p>Two things have changed since then that shape the advice below. First, Google now enforces a small security baseline on every organization created on or after May 3, 2024. Second, most of the constraints worth caring about now have <strong>managed</strong> versions (<code>iam.managed.*</code>, <code>compute.managed.*</code>, <code>sql.managed.*</code>), and those support dry-run mode and tag-based exemptions. The legacy versions mostly don&apos;t.</p>
<h2>Know what you already have</h2>
<p>If your organization is new enough, the baseline is already on. Google&apos;s secure-by-default page lists exactly seven constraints enforced on organizations created on or after May 3, 2024 (and possibly on some created between February and April 2024):</p>
<table><thead><tr><th>Constraint</th><th>Effect</th></tr>
</thead><tbody><tr><td><code>iam.managed.disableServiceAccountKeyCreation</code></td><td>No new service account keys</td></tr>
<tr><td><code>iam.disableServiceAccountKeyUpload</code></td><td>No uploading external public keys to service accounts</td></tr>
<tr><td><code>iam.automaticIamGrantsForDefaultServiceAccounts</code></td><td>Default service accounts don&apos;t get Editor automatically</td></tr>
<tr><td><code>iam.allowedPolicyMemberDomains</code></td><td>Only identities from your own organization can be granted roles</td></tr>
<tr><td><code>essentialcontacts.managed.allowedContactDomains</code></td><td>Essential Contacts limited to your domains</td></tr>
<tr><td><code>compute.managed.restrictProtocolForwardingCreationForTypes</code></td><td>Protocol forwarding restricted to internal IPs</td></tr>
<tr><td><code>storage.uniformBucketLevelAccess</code></td><td>Buckets can&apos;t use per-object ACLs</td></tr>
</tbody></table>
<p>Older organizations have none of these unless someone set them. Either way, check the effective state before adding anything:</p>
<pre><code class="language-bash">gcloud org-policies list --organization=123456789012

gcloud org-policies describe iam.managed.disableServiceAccountKeyCreation \
  --effective --organization=123456789012
</code></pre>
<h2>The handful that earn their keep</h2>
<p><strong>Service account key creation.</strong> <code>iam.managed.disableServiceAccountKeyCreation</code> stops the most common way a service account credential ends up committed to a repository or pasted into a chat, because there&apos;s no long-lived key to leak in the first place. Workloads use an attached service account or Workload Identity Federation instead. If you&apos;re on an older org still using the legacy <code>iam.disableServiceAccountKeyCreation</code>, move to the managed one: Google recommends the managed equivalents for more flexible policies and better insight from Policy Intelligence tools.</p>
<pre><code class="language-yaml"># disable-sa-keys.yaml
name: organizations/123456789012/policies/iam.managed.disableServiceAccountKeyCreation
spec:
  rules:
  - enforce: true
</code></pre>
<p><strong>External IPs on VMs.</strong> Someone forgets <code>--no-address</code> on a one-off VM, and the constraint refuses the create instead of leaving a box exposed until the next audit. The managed <code>compute.managed.vmExternalIpAccess</code> is a boolean: when enforced, it denies creating or updating VMs with IPv4 external addresses (it doesn&apos;t touch IPv6). Exceptions such as a bastion host are handled with tags rather than an instance list. The legacy <code>compute.vmExternalIpAccess</code> is a list constraint that names each allowed instance as <code>projects/PROJECT_ID/zones/ZONE/instances/INSTANCE</code>, which turns every new exception into a policy edit.</p>
<p><strong>Public IP on Cloud SQL.</strong> <code>sql.managed.restrictPublicIp</code> (legacy: <code>sql.restrictPublicIp</code>) closes the same gap for databases, where a public IP is a much bigger blast radius than a stray VM. Both versions are explicitly not retroactive: instances that already have a public IP keep working, so pair the constraint with a one-time sweep. One side effect the Cloud SQL docs call out: <code>gcloud sql connect</code> stops working, because it connects over the public IP. Teams need the Cloud SQL Auth Proxy over private IP instead.</p>
<p><strong>Public buckets.</strong> <code>storage.publicAccessPrevention</code> is the one on this list that <em>is</em> retroactive. It blocks ACLs and IAM grants to <code>allUsers</code> and <code>allAuthenticatedUsers</code>, and the constraint description says public access is revoked for existing buckets and objects once it&apos;s enabled. That&apos;s exactly what you want, but it&apos;s also why this one absolutely goes through the rollout below. Somebody&apos;s static site or public download bucket will stop working.</p>
<h2>The ones that look good and do less</h2>
<p><code>iam.allowedPolicyMemberDomains</code> gets enabled everywhere because it reads well in a compliance deck. It stops identities outside your organization&apos;s Workspace or Cloud Identity account from being granted roles. It&apos;s worth having, and new organizations get it by default, but in my experience it mostly fires on typo&apos;d email addresses during role grants. It&apos;s further down the list than its audit-friendly name suggests. If you do set it, use the managed <code>iam.managed.allowedPolicyMembers</code>, which takes your organization&apos;s principal set as a parameter:</p>
<pre><code class="language-yaml">name: organizations/123456789012/policies/iam.managed.allowedPolicyMembers
spec:
  rules:
  - enforce: true
    parameters:
      allowedPrincipalSets:
      - //cloudresourcemanager.googleapis.com/organizations/123456789012
</code></pre>
<p>Read the fine print before enforcing it. The constraint description warns that it can block folder creation (because of automatic Folder Admin and Folder Editor grants) and project creation (because of the automatic Owner grant) if those principals aren&apos;t covered.</p>
<p>API restriction is the other one that sounds stronger than it is. People reach for <code>serviceuser.services</code>, but it only works as a deny list, and it can only restrict three services: <code>compute.googleapis.com</code>, <code>deploymentmanager.googleapis.com</code>, and <code>dns.googleapis.com</code>. The real allowlist is <code>gcp.restrictServiceUsage</code> (Restrict Resource Service Usage). It works, and it supports dry run, but in a fast-moving engineering org it mostly generates tickets from teams that needed one more API for a legitimate reason. It doesn&apos;t meaningfully shrink the attack surface if IAM is already scoped correctly. I use it on regulated folders and nowhere else.</p>
<h2>The rollout order that avoids breaking things</h2>
<p>The lesson from that first afternoon: never flip a constraint org-wide as your first move. Every constraint I&apos;ve kept in production went through the same three steps.</p>
<p><strong>1. Dry run.</strong> Put the policy in <code>dryRunSpec</code> and watch the violations against real traffic for at least a week. Dry run only works with custom constraints, managed constraints, and a few legacy ones (restrict service usage, restrict endpoint usage, TLS versions, TLS cipher suites). Anything else returns an error, which is another reason to use the managed versions.</p>
<pre><code class="language-yaml"># vm-external-ip.dryrun.yaml
name: organizations/123456789012/policies/compute.managed.vmExternalIpAccess
dryRunSpec:
  rules:
  - enforce: true
</code></pre>
<pre><code class="language-bash">gcloud org-policies set-policy vm-external-ip.dryrun.yaml --update-mask=dryRunSpec
</code></pre>
<p>Dry-run results land in the policy audit log (<code>cloudaudit.googleapis.com%2Fpolicy</code>). This Logs Explorer query shows only the requests the policy <em>would</em> have denied:</p>
<pre><code class="language-text">logName:&quot;cloudaudit.googleapis.com%2Fpolicy&quot;
protoPayload.metadata.dryRunResult=&quot;DENIED&quot;
protoPayload.metadata.liveResult=&quot;ALLOWED&quot;
</code></pre>
<p><strong>2. Tag the legitimate exceptions.</strong> Bastion hosts, NAT instances, and a handful of demo environments all have real reasons for an external IP. Skipping this step guarantees a break. With a managed boolean constraint, the exception is a tag plus a conditional rule. Create the tag and bind it to the projects that are allowed. A project binding exempts every VM in that project, so for a lone bastion in a shared project, bind the tag to the instance instead:</p>
<pre><code class="language-bash">gcloud resource-manager tags keys create external-ip --parent=organizations/123456789012
gcloud resource-manager tags values create allowed --parent=123456789012/external-ip

gcloud resource-manager tags bindings create \
  --tag-value=123456789012/external-ip/allowed \
  --parent=//cloudresourcemanager.googleapis.com/projects/network-edge-prod
</code></pre>
<p><strong>3. Enforce folder by folder.</strong> Start with a low-stakes folder (a sandbox or dev folder, never the one with the CI service accounts in it). Then move the policy up the hierarchy as the violation log goes quiet. A policy with a conditional rule must also have at least one unconditional rule, and for a boolean constraint the conditional rule has to be the opposite of the default:</p>
<pre><code class="language-yaml"># vm-external-ip.yaml
name: folders/456789012345/policies/compute.managed.vmExternalIpAccess
spec:
  rules:
  - condition:
      title: external-ip-allowed
      expression: resource.matchTag(&quot;123456789012/external-ip&quot;, &quot;allowed&quot;)
    enforce: false
  - enforce: true
</code></pre>
<pre><code class="language-bash">gcloud org-policies set-policy vm-external-ip.yaml --update-mask=spec
</code></pre>
<p>Changes can take up to 15 minutes to be enforced, so don&apos;t read a successful VM create in the first few minutes as proof the policy is broken.</p>
<h2>Where the hierarchy actually bites</h2>
<p>The failure mode that costs the most debugging time isn&apos;t a constraint being wrong. It&apos;s a constraint set at the wrong node in the resource hierarchy and inherited somewhere nobody expected. A policy set on the organization applies to every folder and project below it unless something downstream sets its own policy. So when a team reports a violation that &quot;shouldn&apos;t be possible,&quot; I don&apos;t start with the project&apos;s own policy. I start with the effective one, because the constraint that&apos;s actually biting them is almost always three folders up from where they&apos;re looking:</p>
<pre><code class="language-bash">gcloud org-policies describe compute.managed.vmExternalIpAccess \
  --effective --project=team-a-dev
</code></pre>
<p>The two cleanup commands are easy to confuse. <code>gcloud org-policies delete CONSTRAINT --project=PROJECT_ID</code> removes the project&apos;s own policy, so the project goes back to whatever it inherits. <code>gcloud org-policies reset CONSTRAINT --project=PROJECT_ID</code> does something different: it resets the policy to the constraint&apos;s default, which for most constraints means not enforced, whatever the parent says.</p>
<p>To see the whole estate at once, this script prints the effective enforcement of the constraints above for every project the caller can see. It needs <code>roles/orgpolicy.policyViewer</code> at the organization plus <code>resourcemanager.projects.list</code>, for example Browser (<code>roles/browser</code>) on the organization. It uses nothing beyond <code>gcloud</code> and Bash:</p>
<pre><code class="language-bash">#!/usr/bin/env bash
# effective-org-policies.sh
# Prints the effective enforcement of key boolean constraints for every
# project visible to the caller, as CSV on stdout.
# Usage: ./effective-org-policies.sh [PROJECT_FILTER] &gt; effective.csv
#   PROJECT_FILTER is an optional gcloud --filter, e.g. &quot;parent.id=456789012345&quot;
set -euo pipefail

ERR_FILE=$(mktemp)
trap &apos;rm -f &quot;$ERR_FILE&quot;&apos; EXIT

CONSTRAINTS=(
  iam.managed.disableServiceAccountKeyCreation
  iam.disableServiceAccountKeyCreation
  compute.managed.vmExternalIpAccess
  sql.managed.restrictPublicIp
  sql.restrictPublicIp
  storage.publicAccessPrevention
  storage.uniformBucketLevelAccess
)
FILTER=&quot;${1:-lifecycleState=ACTIVE}&quot;

printf &apos;project,%s\n&apos; &quot;$(IFS=,; echo &quot;${CONSTRAINTS[*]}&quot;)&quot;

for project in $(gcloud projects list --filter=&quot;$FILTER&quot; --format=&apos;value(projectId)&apos;); do
  row=&quot;$project&quot;
  for constraint in &quot;${CONSTRAINTS[@]}&quot;; do
    # spec.rules may hold conditional rules; list every enforce value
    if value=$(gcloud org-policies describe &quot;$constraint&quot; --effective \
        --project=&quot;$project&quot; --format=&apos;value(spec.rules[].enforce)&apos; 2&gt;&quot;$ERR_FILE&quot;); then
      [[ -z &quot;$value&quot; ]] &amp;&amp; value=&quot;unset&quot;
    elif grep -q NOT_FOUND &quot;$ERR_FILE&quot;; then
      value=&quot;unset&quot;   # no policy set anywhere in the hierarchy
    else
      value=&quot;error&quot;   # permission denied, API disabled, and so on
    fi
    row+=&quot;,${value//;/|}&quot;
  done
  echo &quot;$row&quot;
done
</code></pre>
<p>Sample output:</p>
<pre><code class="language-text">project,iam.managed.disableServiceAccountKeyCreation,iam.disableServiceAccountKeyCreation,compute.managed.vmExternalIpAccess,sql.managed.restrictPublicIp,sql.restrictPublicIp,storage.publicAccessPrevention,storage.uniformBucketLevelAccess
network-edge-prod,True,unset,False|True,True,unset,True,True
team-a-dev,True,unset,True,True,unset,unset,True
legacy-reporting,unset,unset,unset,unset,unset,unset,unset
</code></pre>
<p>A value like <code>False|True</code> means a conditional rule is in play (here, the tag exemption), <code>unset</code> on every column is the project to go look at first, and <code>error</code> means the lookup itself failed (usually permissions). For &quot;what would break if I enforced this,&quot; Policy Simulator for organization policies answers the question before you commit. It needs <code>roles/policysimulator.orgPolicyAdmin</code>, and it handles custom and managed constraints but not legacy ones.</p>
<h2>The honest summary</h2>
<p>A handful of constraints scoped to real credential and exposure risks, rolled out gradually with dry-run data, does more for your security posture than enabling most of the catalog at once. The value is in the few that close a specific, recurring failure mode (keys, external IPs, public databases, public buckets), not in the count of constraints turned on. If you want to find the service account keys that already exist before you lock creation down, the <a href="https://www.techcolumnist.com/2026/03/04/node-js-gcloud-rotating-service-account-keys-before-they-expire/">service account key rotation script</a> and the <a href="https://www.techcolumnist.com/2026/01/14/python-gcloud-audit-iam-bindings-across-a-gcp-organization/">organization-wide IAM audit</a> are the companion pieces.</p>
<h2>References</h2>
<ul><li><a href="https://docs.cloud.google.com/resource-manager/docs/secure-by-default-organizations">Secure-by-default organization policies</a></li>
<li><a href="https://docs.cloud.google.com/organization-policy/reference/org-policy-constraints">Organization policy constraints reference</a></li>
<li><a href="https://docs.cloud.google.com/organization-policy/create-organization-policies">Create organization policies (YAML, describe, reset, delete)</a></li>
<li><a href="https://docs.cloud.google.com/organization-policy/test-policies">Test organization policies in dry-run mode</a></li>
<li><a href="https://docs.cloud.google.com/resource-manager/docs/organization-policy/tags-organization-policy">Scope organization policies with tags</a></li>
<li><a href="https://docs.cloud.google.com/resource-manager/docs/tags/tags-creating-and-managing">Create and manage tags</a></li>
<li><a href="https://docs.cloud.google.com/organization-policy/restrict-service-accounts">Restrict service account usage</a></li>
<li><a href="https://docs.cloud.google.com/resource-manager/docs/organization-policy/restricting-domains">Restrict identities with domain-restricted sharing</a></li>
<li><a href="https://docs.cloud.google.com/policy-intelligence/docs/test-organization-policies">Policy Simulator for organization policies</a></li>
<li><a href="https://docs.cloud.google.com/sql/docs/mysql/org-policy/configure-org-policy">Cloud SQL organization policies</a></li>
</ul>
]]></content:encoded>
      <category>Engineering</category>
    </item>
    <item>
      <title>Google Cloud: Choosing Between GKE and Cloud Run for an Internal Tool</title>
      <link>https://www.techcolumnist.com/2026/05/06/google-cloud-choosing-between-gke-and-cloud-run-for-an-internal-tool/</link>
      <guid isPermaLink="true">https://www.techcolumnist.com/2026/05/06/google-cloud-choosing-between-gke-and-cloud-run-for-an-internal-tool/</guid>
      <pubDate>Wed, 06 May 2026 14:00:00 GMT</pubDate>
      <dc:creator>Tom Lasswell</dc:creator>
      <description>How to pick GKE Autopilot or Cloud Run for an internal tool: billing models, sidecars, IAP, VPC egress, and team fluency, with deploy scripts for both.</description>
      <content:encoded><![CDATA[<p>Every time an internal tool needs a real home on Google Cloud (an approval workflow, a reporting dashboard, a small API that a handful of other services call), the same question comes up: does this need Kubernetes, or is that reaching for a bigger hammer than the nail requires? Having run both under similar internal tools, my answer has stopped being &quot;it depends&quot; in the vague sense and become a short, concrete checklist. Some of the reasons I used to give for GKE have also stopped being true, so this is the updated version, with the actual deploy commands for each side.</p>
<h2>Start from the traffic shape, not the technology</h2>
<p>Internal tools tend to have one of two traffic shapes: near-constant light load from a fixed set of employees during business hours, or bursty, occasional load triggered by a batch job, a webhook, or a monthly report run.</p>
<p>Cloud Run&apos;s default is <strong>request-based billing</strong>. In Google&apos;s words, instances &quot;are only charged when they process requests, when they start, and when they shut down,&quot; and with no minimum instances the service scales to zero between requests. The cost of idle time is a cold start on the next call. If that cold start bothers people, set a minimum instance count. Under request-based billing, idle minimum instances are billed at a lower rate than active ones. The alternative, <strong>instance-based billing</strong> (<code>--no-cpu-throttling</code>), charges for the whole instance lifecycle and is meant for services that do background work outside requests.</p>
<p>GKE Autopilot is closer than it used to be, but it doesn&apos;t reach zero. General-purpose Autopilot pods use pod-based billing: you&apos;re charged per second for the CPU, memory, and ephemeral storage the running pods <em>request</em>, with no node pool to pay for. But a Deployment keeps at least one replica running around the clock. The standard HorizontalPodAutoscaler doesn&apos;t scale to zero without a feature gate. On top of that, every GKE cluster, Autopilot included, pays a flat cluster management fee of $0.10 per cluster per hour. The GKE free tier gives each billing account $74.40 a month in credits, which is equivalent to one free Autopilot or zonal Standard cluster. So the first internal cluster&apos;s fee is effectively covered, and the second one isn&apos;t.</p>
<p>If the tool sits idle sixteen hours a day, Cloud Run&apos;s model wins by construction. If it&apos;s busy all day, scale-to-zero never triggers and the gap narrows to whatever your pod requests cost versus Cloud Run&apos;s per-instance rates.</p>
<h2>Count the moving parts the tool actually has</h2>
<p>A single container serving HTTP, backed by Cloud SQL or Firestore, is Cloud Run&apos;s design center: deploy a container image, get a URL, done. I used to draw the line at the first sidecar, but that&apos;s outdated. Cloud Run supports multi-container instances with up to 10 containers per instance, one of them the ingress container, so a proxy, a log shipper, or an auth helper next to the app no longer forces a move. The same goes for two other old objections:</p>
<ul><li><strong>Static outbound IP for a partner allowlist.</strong> Direct VPC egress with <code>--vpc-egress=all-traffic</code>, plus Cloud NAT on that VPC, gives a Cloud Run service a fixed egress address. Google warns about slower instance startup with Cloud NAT on Direct VPC (cold starts of 30 seconds or more), which matters if you scale to zero.</li>
<li><strong>Keeping it off the internet.</strong> Ingress settings (<code>all</code>, <code>internal</code>, <code>internal-and-cloud-load-balancing</code>) restrict who can reach the service at the network level. For an employee-facing tool, IAP now attaches directly to a Cloud Run service with <code>--iap</code>, with no load balancer required.</li>
</ul>
<p>What still pushes me toward GKE is a tool that&apos;s really several cooperating services with their own lifecycles: an API, a queue consumer, a scheduler, and a cache that address each other over cluster DNS, share config through ConfigMaps, and get deployed together from one Helm chart or Kustomize overlay. The rule of thumb I use now: if I can draw the architecture as one box (sidecars included), it&apos;s Cloud Run. The moment I&apos;m drawing a second box that needs to know about the first at the infrastructure level rather than just calling an HTTPS endpoint, GKE starts looking more honest than stitching Cloud Run services together.</p>
<h2>What the Cloud Run version actually looks like</h2>
<p>This is the whole deployment for a typical internal dashboard: a dedicated runtime service account, no public invoker, IAP in front for employee sign-in, private egress into the VPC for a database on a private IP, and one warm instance during the day. It needs <code>roles/run.admin</code>, <code>roles/iam.serviceAccountAdmin</code>, and <code>roles/iam.serviceAccountUser</code> on the project, plus <code>roles/iap.admin</code> for the access grant and <code>roles/artifactregistry.reader</code> on the image&apos;s repository.</p>
<pre><code class="language-bash">#!/usr/bin/env bash
# deploy-internal-tool.sh
# Deploys an internal tool to Cloud Run behind IAP with Direct VPC egress.
set -euo pipefail

PROJECT_ID=&quot;my-tools-project&quot;
REGION=&quot;us-central1&quot;
SERVICE=&quot;approvals&quot;
IMAGE=&quot;us-central1-docker.pkg.dev/${PROJECT_ID}/tools/approvals:1.4.2&quot;
NETWORK=&quot;tools-vpc&quot;
SUBNET=&quot;tools-run-subnet&quot;          # Direct VPC needs a /26 or larger
ACCESS_GROUP=&quot;group:approvals-users@example.com&quot;

PROJECT_NUMBER=$(gcloud projects describe &quot;$PROJECT_ID&quot; --format=&apos;value(projectNumber)&apos;)
RUNTIME_SA=&quot;${SERVICE}-run@${PROJECT_ID}.iam.gserviceaccount.com&quot;

gcloud services enable run.googleapis.com iap.googleapis.com --project=&quot;$PROJECT_ID&quot;

# 1. A runtime identity of its own, never the default compute service account
if ! gcloud iam service-accounts describe &quot;$RUNTIME_SA&quot; --project=&quot;$PROJECT_ID&quot; &gt;/dev/null 2&gt;&amp;1; then
  gcloud iam service-accounts create &quot;${SERVICE}-run&quot; \
    --project=&quot;$PROJECT_ID&quot; --display-name=&quot;${SERVICE} Cloud Run runtime&quot;
fi

# 2. Deploy: no unauthenticated invokers, IAP on, private egress, request-based billing
gcloud run deploy &quot;$SERVICE&quot; \
  --project=&quot;$PROJECT_ID&quot; \
  --region=&quot;$REGION&quot; \
  --image=&quot;$IMAGE&quot; \
  --service-account=&quot;$RUNTIME_SA&quot; \
  --no-allow-unauthenticated \
  --iap \
  --network=&quot;$NETWORK&quot; \
  --subnet=&quot;$SUBNET&quot; \
  --vpc-egress=private-ranges-only \
  --cpu-throttling \
  --max-instances=5

# 3. Service-level minimum instances (no new revision needed to change it)
gcloud run services update &quot;$SERVICE&quot; --project=&quot;$PROJECT_ID&quot; --region=&quot;$REGION&quot; --min=1

# 4. Let the IAP service agent invoke the service
gcloud run services add-iam-policy-binding &quot;$SERVICE&quot; \
  --project=&quot;$PROJECT_ID&quot; --region=&quot;$REGION&quot; \
  --member=&quot;serviceAccount:service-${PROJECT_NUMBER}@gcp-sa-iap.iam.gserviceaccount.com&quot; \
  --role=roles/run.invoker

# 5. Decide who gets through IAP
gcloud iap web add-iam-policy-binding \
  --project=&quot;$PROJECT_ID&quot; --region=&quot;$REGION&quot; \
  --resource-type=cloud-run --service=&quot;$SERVICE&quot; \
  --member=&quot;$ACCESS_GROUP&quot; \
  --role=roles/iap.httpsResourceAccessor

gcloud run services describe &quot;$SERVICE&quot; --project=&quot;$PROJECT_ID&quot; --region=&quot;$REGION&quot; --format=&apos;value(status.url)&apos;
</code></pre>
<p>Two caveats from the IAP docs are worth knowing before you pick this pattern. You can&apos;t configure IAP on both a load balancer and the Cloud Run service, so choose one. And because Cloud Run enforces IAP before the IAM invoker check, service-to-service callers such as Pub/Sub push subscriptions can fail against an IAP-protected service. Give machine callers a separate service without IAP, or route them another way.</p>
<p>Because service-level minimum instances change without a new deployment, dropping to <code>--min=0</code> overnight and back to <code>--min=1</code> in the morning is a small scheduled job, if the cold start really matters.</p>
<h2>What the GKE Autopilot version looks like</h2>
<p>For comparison, here&apos;s the minimum for the same tool on Autopilot, assuming the cluster already exists (<code>gcloud container clusters create-auto tools --region=us-central1 --project=my-tools-project</code>). Autopilot bills on the requests, so set them deliberately. It raises values below its minimums and fills in defaults for pods that don&apos;t set them.</p>
<pre><code class="language-yaml"># approvals.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: approvals
  namespace: tools
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: approvals
  namespace: tools
spec:
  replicas: 1
  selector:
    matchLabels:
      app: approvals
  template:
    metadata:
      labels:
        app: approvals
    spec:
      serviceAccountName: approvals
      containers:
      - name: app
        image: us-central1-docker.pkg.dev/my-tools-project/tools/approvals:1.4.2
        ports:
        - containerPort: 8080
        resources:
          requests:
            cpu: 250m
            memory: 512Mi
        readinessProbe:
          httpGet:
            path: /healthz
            port: 8080
---
apiVersion: v1
kind: Service
metadata:
  name: approvals
  namespace: tools
spec:
  selector:
    app: approvals
  ports:
  - port: 8080
    targetPort: 8080
---
apiVersion: networking.gke.io/v1
kind: GCPBackendPolicy
metadata:
  name: approvals-iap
  namespace: tools
spec:
  default:
    iap:
      enabled: true
      clientID: IAP_OAUTH_CLIENT_ID
      oauth2ClientSecret:
        name: approvals-iap-secret
  targetRef:
    group: &quot;&quot;
    kind: Service
    name: approvals
</code></pre>
<p>That&apos;s still not the whole thing. IAP on GKE rides on a load balancer, so you also need a Gateway (<code>gatewayClassName: gke-l7-global-external-managed</code>, which Autopilot always has enabled) with an HTTPS listener and certificate, an HTTPRoute pointing at the Service, a <code>HealthCheckPolicy</code> that sends the load balancer&apos;s health check to <code>/healthz</code> (unlike Ingress, Gateway doesn&apos;t read the readiness probe and checks <code>/</code> by default), an OAuth client ID and a Kubernetes Secret for it, and IAM grants for the pod&apos;s Kubernetes service account (Workload Identity Federation for GKE) for any Google API calls. Every one of those is a thing someone has to understand when it breaks. Compare that with steps 4 and 5 of the Cloud Run script.</p>
<h2>Weigh the team&apos;s Kubernetes fluency honestly</h2>
<p>A GKE cluster is not free to operate even when Google handles the control plane and, with Autopilot, the nodes. Someone owns namespace and RBAC design, someone reviews the Helm chart or Kustomize overlay when it needs a change, and someone gets paged when a pod&apos;s readiness probe starts flapping. For a team that already runs GKE for the product&apos;s primary workloads, adding one more small internal tool to the existing cluster costs little extra: no new cluster fee, and the operational muscle already exists. For a team whose primary stack doesn&apos;t touch Kubernetes, standing up a cluster (or borrowing a namespace in someone else&apos;s) purely to host one internal dashboard buys a maintenance burden that outlives the tool&apos;s original author.</p>
<h2>The decision in practice</h2>
<table><thead><tr><th>Question</th><th>Leans Cloud Run</th><th>Leans GKE Autopilot</th></tr>
</thead><tbody><tr><td>Traffic</td><td>Bursty, idle most of the day</td><td>Busy all day; scale-to-zero never triggers</td></tr>
<tr><td>Shape</td><td>One service, sidecars at most</td><td>Several services deployed and versioned together</td></tr>
<tr><td>Employee sign-in</td><td>IAP with <code>--iap</code>, no load balancer</td><td>IAP through Gateway and <code>GCPBackendPolicy</code></td></tr>
<tr><td>Egress</td><td>Direct VPC egress, Cloud NAT for a fixed IP</td><td>Cluster networking you already run</td></tr>
<tr><td>Team</td><td>No one runs Kubernetes day to day</td><td>Existing cluster and on-call rotation</td></tr>
<tr><td>Cost floor</td><td>Zero with <code>--min=0</code></td><td>Cluster fee (first cluster covered by free tier) plus 24/7 pod requests</td></tr>
</tbody></table>
<p>For a tool with one deployable unit, event-driven or bursty traffic, and no team already running Kubernetes day to day, Cloud Run wins on cost, deploy simplicity, and blast radius: a bad deploy is one <code>gcloud run services update-traffic</code> away from the previous revision. For a tool that&apos;s genuinely multi-service, needs to share infrastructure with workloads already on GKE, or has sustained enough traffic that scale-to-zero never kicks in, GKE&apos;s marginal cost is lower than it looks and the architectural flexibility is worth having. Most internal tools, in my experience, are closer to the first case than teams initially assume. The instinct to reach for Kubernetes because &quot;that&apos;s what we use for everything else&quot; is worth questioning every time a new tool is this small.</p>
<h2>References</h2>
<ul><li><a href="https://docs.cloud.google.com/run/docs/configuring/billing-settings">Cloud Run billing settings (request-based vs instance-based)</a></li>
<li><a href="https://docs.cloud.google.com/run/docs/configuring/min-instances">Cloud Run minimum instances</a></li>
<li><a href="https://docs.cloud.google.com/run/docs/deploying#sidecars">Deploying multi-container (sidecar) services to Cloud Run</a></li>
<li><a href="https://docs.cloud.google.com/run/docs/configuring/vpc-direct-vpc">Direct VPC egress for Cloud Run</a></li>
<li><a href="https://docs.cloud.google.com/run/docs/securing/ingress">Cloud Run ingress settings</a></li>
<li><a href="https://docs.cloud.google.com/run/docs/securing/identity-aware-proxy-cloud-run">Configure IAP for Cloud Run</a></li>
<li><a href="https://cloud.google.com/kubernetes-engine/pricing">GKE pricing (cluster management fee, free tier, Autopilot billing)</a></li>
<li><a href="https://docs.cloud.google.com/kubernetes-engine/docs/concepts/autopilot-overview">GKE Autopilot overview</a></li>
<li><a href="https://docs.cloud.google.com/kubernetes-engine/docs/how-to/configure-gateway-resources">Configure Gateway resources (GCPBackendPolicy and IAP)</a></li>
<li><a href="https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/">Kubernetes Horizontal Pod Autoscaling</a></li>
</ul>
]]></content:encoded>
      <category>Engineering</category>
    </item>
    <item>
      <title>Azure: What We Got Wrong Moving File Servers to Azure Files</title>
      <link>https://www.techcolumnist.com/2026/04/22/azure-what-we-got-wrong-moving-file-servers-to-azure-files/</link>
      <guid isPermaLink="true">https://www.techcolumnist.com/2026/04/22/azure-what-we-got-wrong-moving-file-servers-to-azure-files/</guid>
      <pubDate>Wed, 22 Apr 2026 14:00:00 GMT</pubDate>
      <dc:creator>Tom Lasswell</dc:creator>
      <description>Latency, AD DS Kerberos, and cloud tiering mistakes from moving file servers to Azure Files, with the robocopy migration script and az CLI setup we use now.</description>
      <content:encoded><![CDATA[<p>Azure Files gets pitched as a drop-in replacement for an on-prem file server: same SMB protocol, same NTFS ACLs, one less physical box to patch and back up. Some of that is true. What the pitch leaves out is a set of assumptions baked into every file server that quietly stop holding once the storage is a WAN hop away instead of on the same LAN segment, and we found most of them the hard way across a handful of migrations. This is what went wrong, and the scripts we run now so it does not go wrong again.</p>
<h2>The Latency We Didn&apos;t Plan For</h2>
<p>A local file server answers an SMB request over a LAN. An Azure file share answers it after a round trip to an Azure region, and Microsoft is blunt about what that means: the farther the client is from the service, the slower the latency experience, and even ExpressRoute doesn&apos;t match an application whose compute and storage run in the same region. For a user opening a Word document, that&apos;s invisible. For a line-of-business app that does hundreds of small, chatty file operations per transaction, the kind that does a stat, a lock, a tiny read and a tiny write in a loop instead of one clean read, that latency multiplies into a genuinely slower application. The first anyone hears about it is a help desk ticket saying the app &quot;feels sluggish&quot; with no obvious cause.</p>
<p>Microsoft&apos;s own performance guide shows the arithmetic. Its worked example of a single-threaded app creating a 16 KiB file in six operations comes to about 14 ms per file, so 10,000 files take 140 seconds sequentially, and eight threads bring that down to 17.5 seconds. The per-operation cost is set by distance, so a serial app pays it on every call.</p>
<p>We now profile the I/O pattern of anything latency-sensitive before migrating it, not just how much data it stores. The cheapest way is to put a pilot copy of the share in Azure, point the app at it, and compare two storage metrics. <code>SuccessE2ELatency</code> is the full round trip from the client; <code>SuccessServerLatency</code> is time spent inside Azure Files. Microsoft&apos;s guidance is that the gap between them is network and client time, so a big gap means distance is your problem and a faster tier won&apos;t fix it.</p>
<pre><code class="language-bash">#!/usr/bin/env bash
# share-latency.sh: compare end-to-end and service latency for a pilot share.
set -euo pipefail

SUB=&quot;&lt;subscription-id&gt;&quot;
RG=&quot;&lt;resource-group&gt;&quot;
ACCOUNT=&quot;&lt;storage-account&gt;&quot;
FILE_SERVICE=&quot;/subscriptions/$SUB/resourceGroups/$RG/providers/Microsoft.Storage/storageAccounts/$ACCOUNT/fileServices/default&quot;

# Hourly averages over the last 7 days, split by SMB/REST operation name.
az monitor metrics list \
  --resource &quot;$FILE_SERVICE&quot; \
  --metrics SuccessE2ELatency SuccessServerLatency \
  --dimension ApiName \
  --aggregation Average \
  --interval 1h \
  --offset 7d \
  --output table
</code></pre>
<p>If the app is chatty and the gap is large, the options are to move the app&apos;s compute into the same region as the share, keep a local cache with Azure File Sync, or leave that workload on a file server. Picking a bigger share doesn&apos;t help a serial app that&apos;s waiting on round trips.</p>
<p>It also pays to pick the billing model deliberately. Microsoft now recommends provisioned v2 for new deployments: you provision storage, IOPS and throughput separately and pay for what you provision, with credit-based bursting on a best-effort basis. You can decrease a provisioned value only after 24 hours have passed since the last increase. The per-share limits differ a lot by media tier:</p>
<table><thead><tr><th>Classic file share limit</th><th>HDD provisioned v2</th><th>SSD provisioned v2</th><th>HDD pay-as-you-go</th></tr>
</thead><tbody><tr><td>Maximum share size</td><td>256 TiB</td><td>256 TiB</td><td>100 TiB</td></tr>
<tr><td>Maximum data IOPS</td><td>50,000 (as provisioned)</td><td>102,400 (as provisioned)</td><td>20,000</td></tr>
<tr><td>Maximum IOPS per file</td><td>1,000</td><td>12,000</td><td>1,000</td></tr>
<tr><td>Maximum handles per file or directory</td><td>2,000</td><td>2,000</td><td>2,000</td></tr>
<tr><td>Maximum handles on the share root</td><td>10,000</td><td>10,000</td><td>10,000</td></tr>
</tbody></table>
<p>The handle limits are worth checking against any app that keeps thousands of files open. Here is the storage account, share and private endpoint we deploy for a pilot, using the commands from Microsoft&apos;s provisioned v2 and private endpoint guides:</p>
<pre><code class="language-bash">#!/usr/bin/env bash
# new-files-pilot.sh: HDD provisioned v2 share behind a private endpoint, public endpoint
# denied except for trusted Azure services.
set -euo pipefail

RG=&quot;&lt;resource-group&gt;&quot;
ACCOUNT=&quot;&lt;storage-account&gt;&quot;          # 3-24 lowercase letters and numbers
REGION=&quot;eastus2&quot;
SHARE=&quot;finance&quot;
VNET_RG=&quot;&lt;vnet-resource-group&gt;&quot;
VNET=&quot;&lt;vnet-name&gt;&quot;
SUBNET=&quot;&lt;private-endpoint-subnet&gt;&quot;

az storage account create \
  --resource-group &quot;$RG&quot; --name &quot;$ACCOUNT&quot; --location &quot;$REGION&quot; \
  --kind FileStorage --sku StandardV2_LRS --output none

# Omitting --provisioned-iops and --provisioned-bandwidth-mibps uses the recommended values.
az storage share-rm create \
  --resource-group &quot;$RG&quot; --storage-account &quot;$ACCOUNT&quot; --name &quot;$SHARE&quot; \
  --quota 1024 --enabled-protocols SMB --output none

ACCOUNT_ID=$(az storage account show --resource-group &quot;$RG&quot; --name &quot;$ACCOUNT&quot; --query id --output tsv)
VNET_ID=$(az network vnet show --resource-group &quot;$VNET_RG&quot; --name &quot;$VNET&quot; --query id --output tsv)
SUBNET_ID=$(az network vnet subnet show --resource-group &quot;$VNET_RG&quot; --vnet-name &quot;$VNET&quot; --name &quot;$SUBNET&quot; --query id --output tsv)

az network vnet subnet update --ids &quot;$SUBNET_ID&quot; --disable-private-endpoint-network-policies --output none

PE_ID=$(az network private-endpoint create \
  --resource-group &quot;$RG&quot; --name &quot;$ACCOUNT-pe&quot; --location &quot;$REGION&quot; \
  --subnet &quot;$SUBNET_ID&quot; --private-connection-resource-id &quot;$ACCOUNT_ID&quot; \
  --group-id file --connection-name &quot;$ACCOUNT-conn&quot; --query id --output tsv)

# Private DNS so &lt;account&gt;.file.core.windows.net resolves to the private IP.
ZONE=&quot;privatelink.file.core.windows.net&quot;
az network private-dns zone create --resource-group &quot;$VNET_RG&quot; --name &quot;$ZONE&quot; --output none
az network private-dns link vnet create --resource-group &quot;$VNET_RG&quot; --zone-name &quot;$ZONE&quot; \
  --name &quot;$VNET-files-link&quot; --virtual-network &quot;$VNET_ID&quot; --registration-enabled false --output none

NIC_ID=$(az network private-endpoint show --ids &quot;$PE_ID&quot; --query &quot;networkInterfaces[0].id&quot; --output tsv)
PE_IP=$(az network nic show --ids &quot;$NIC_ID&quot; --query &quot;ipConfigurations[0].privateIPAddress&quot; --output tsv)
az network private-dns record-set a create --resource-group &quot;$VNET_RG&quot; --zone-name &quot;$ZONE&quot; \
  --name &quot;$ACCOUNT&quot; --output none
az network private-dns record-set a add-record --resource-group &quot;$VNET_RG&quot; --zone-name &quot;$ZONE&quot; \
  --record-set-name &quot;$ACCOUNT&quot; --ipv4-address &quot;$PE_IP&quot; --output none

# Deny the public endpoint; AzureServices bypass keeps Azure File Sync working.
az storage account update --resource-group &quot;$RG&quot; --name &quot;$ACCOUNT&quot; \
  --default-action Deny --bypass AzureServices --output none
</code></pre>
<p>On-premises clients need their DNS servers to forward <code>file.core.windows.net</code> lookups into Azure, or they will keep resolving the public IP. Test from a client with <code>Resolve-DnsName &lt;account&gt;.file.core.windows.net</code> and confirm the answer is a CNAME to the <code>privatelink</code> name with your private IP, and always mount by the original name, not the <code>privatelink</code> one.</p>
<h2>Getting Authentication Backwards</h2>
<p>Azure Files supports Kerberos against on-prem Active Directory so NTFS ACLs carry over exactly as they were, which sounds like the safe default. The part we underestimated was how much has to line up for it to work. The storage account has to be registered in AD DS, which creates a computer (or service logon) account that represents it, a different setup from Microsoft Entra Domain Services. Clients need unimpeded network connectivity to a domain controller from wherever they sit. And there are two permission layers: a share-level Azure RBAC role assigned to the user&apos;s synced Entra identity, then the NTFS ACLs enforced against AD DS. Only hybrid identities that exist in both directories work with per-user share permissions.</p>
<p>Get the RBAC layer wrong and users get access denied even though their NTFS permissions are fine, which looks exactly like a Kerberos failure and sends you down the wrong troubleshooting path first. Two things made it worse for us. Share-level permission changes usually take effect within 30 minutes but can take longer, so a fix doesn&apos;t look like a fix right away. And the default share-level permission is <code>None</code>, so nothing works until you assign something. If clients can&apos;t reach a domain controller, for example Entra-joined laptops off the VPN, Microsoft Entra Kerberos is the identity source designed for that case, but a storage account has exactly one identity source, so decide before you set ACLs.</p>
<p>This is the pilot setup we run now, from a domain-joined machine in Windows PowerShell 5.1 with the AzFilesHybrid module (which only supports AES-256 Kerberos):</p>
<pre><code class="language-powershell">&lt;#
.SYNOPSIS
    Registers a storage account in AD DS and grants share-level access to one group.
.DESCRIPTION
    Uses AzFilesHybrid Join-AzStorageAccount to create the computer account that
    represents the storage account, assigns a share-level RBAC role to a synced
    group on one share, and runs the AzFilesHybrid diagnostics.
.PARAMETER SubscriptionId
    Subscription that holds the storage account.
.PARAMETER ResourceGroupName
    Resource group of the storage account.
.PARAMETER StorageAccountName
    Storage account to join.
.PARAMETER SamAccountName
    Name of the AD computer object, 15 characters or less, no trailing $.
.PARAMETER OuDistinguishedName
    OU for the computer object. Use an OU without computer password expiration.
.PARAMETER ShareName
    Share to grant access on.
.PARAMETER GroupObjectId
    Object ID of the synced Entra group that gets Storage File Data SMB Share Contributor.
.EXAMPLE
    .\Join-FilesPilot.ps1 -SubscriptionId &quot;&lt;subscription-id&gt;&quot; -ResourceGroupName &quot;&lt;rg&gt;&quot; -StorageAccountName &quot;&lt;account&gt;&quot; -SamAccountName &quot;&lt;account&gt;&quot; -OuDistinguishedName &quot;OU=AzureFiles,DC=contoso,DC=com&quot; -ShareName &quot;finance&quot; -GroupObjectId &quot;&lt;group-object-id&gt;&quot;
.NOTES
    Author  : Thomas Lasswell (https://www.techcolumnist.com)
    Version : 1.0 (2026-04-22)
    Requires: Windows PowerShell 5.1, Az.Accounts, Az.Storage 8.1.0+, Az.Resources, AzFilesHybrid, ActiveDirectory module
#&gt;
param (
    [Parameter(Mandatory = $true)] [string] $SubscriptionId,
    [Parameter(Mandatory = $true)] [string] $ResourceGroupName,
    [Parameter(Mandatory = $true)] [string] $StorageAccountName,
    [Parameter(Mandatory = $true)] [string] $SamAccountName,
    [Parameter(Mandatory = $true)] [string] $OuDistinguishedName,
    [Parameter(Mandatory = $true)] [string] $ShareName,
    [Parameter(Mandatory = $true)] [string] $GroupObjectId
)

Import-Module -Name AzFilesHybrid
Connect-AzAccount | Out-Null
Select-AzSubscription -SubscriptionId $SubscriptionId | Out-Null

# Create the AD computer account and enable AD DS authentication on the account.
Join-AzStorageAccount `
    -ResourceGroupName $ResourceGroupName `
    -StorageAccountName $StorageAccountName `
    -SamAccountName $SamAccountName `
    -DomainAccountType &quot;ComputerAccount&quot; `
    -OrganizationalUnitDistinguishedName $OuDistinguishedName

# Share-level permission for one synced group, scoped to one share.
$scope = &quot;/subscriptions/$SubscriptionId/resourceGroups/$ResourceGroupName/providers/Microsoft.Storage/storageAccounts/$StorageAccountName/fileServices/default/fileshares/$ShareName&quot;
New-AzRoleAssignment -ObjectId $GroupObjectId -RoleDefinitionName &quot;Storage File Data SMB Share Contributor&quot; -Scope $scope | Out-Null

# Confirm the identity source, then run the built-in checks as the signed-in AD user.
$account = Get-AzStorageAccount -ResourceGroupName $ResourceGroupName -Name $StorageAccountName
$account.AzureFilesIdentityBasedAuth.DirectoryServiceOptions
Debug-AzStorageAccountAuth -StorageAccountName $StorageAccountName -ResourceGroupName $ResourceGroupName -Verbose
</code></pre>
<p>One more trap: the AD object that represents the storage account has a password, and Microsoft&apos;s guidance is to put it in an OU where it won&apos;t hit a maximum password age, or rotate it before it does. If it expires, every mount fails at once.</p>
<h2>Moving the Data Without Losing the ACLs</h2>
<p>Microsoft&apos;s migration guide says to use robocopy, not AzCopy, when an Azure file share is the target: <code>robocopy /MIR</code> mirrors deletions, while <code>azcopy sync</code> doesn&apos;t remove files deleted at the source. Mount the target share with admin-level access (an admin-level RBAC role, or the storage account key), because the <code>/B</code> backup-mode switch needs it. The guide&apos;s command is <code>/MT:20 /R:2 /W:1 /B /MIR /IT /COPY:DATSO /DCOPY:DAT /NP /NFL /NDL /XD &quot;System Volume Information&quot;</code>. <code>/COPY:DATSO</code> carries data, attributes, timestamps, NTFS ACLs and owner (auditing info can&apos;t be stored in Azure Files, so no <code>U</code>), and <code>/IT</code> catches ACL changes that <code>/MIR</code> would otherwise miss.</p>
<p>The pattern is repeated passes: a first bulk pass while users keep working, catch-up passes that only move changes, then a final pass after you block writes to the source. The final pass takes about as long as the previous catch-up pass, which is your downtime estimate. This wrapper runs one pass for every share in a CSV and treats robocopy&apos;s exit codes correctly: 0 to 7 are success variants, 8 or higher means at least one failure.</p>
<pre><code class="language-powershell">&lt;#
.SYNOPSIS
    Runs one robocopy migration pass for every share listed in a CSV.
.DESCRIPTION
    Reads a CSV with Source and Target columns (UNC paths), runs robocopy with the
    switches from Microsoft&apos;s Azure Files migration guide, writes one Unicode log per
    share and pass, and reports any share whose exit code is 8 or higher.
.PARAMETER MappingFile
    CSV with Source and Target columns.
.PARAMETER LogFolder
    Folder for robocopy logs.
.PARAMETER Threads
    Value for /MT. Microsoft suggests 8-20 for the first pass and roughly the core count after.
.PARAMETER ListOnly
    Adds /L so robocopy only lists what it would copy or purge.
.EXAMPLE
    .\Invoke-ShareMigration.ps1 -MappingFile .\shares.csv -LogFolder D:\MigrationLogs -Threads 16
.NOTES
    Author  : Thomas Lasswell (https://www.techcolumnist.com)
    Version : 1.0 (2026-04-22)
    Requires: elevated session, Windows Server 2022 or newer recommended, target shares mounted with admin-level access
#&gt;
param (
    [Parameter(Mandatory = $true)] [string] $MappingFile,
    [Parameter(Mandatory = $true)] [string] $LogFolder,
    [int] $Threads = 16,
    [switch] $ListOnly
)

New-Item -Path $LogFolder -ItemType Directory -Force | Out-Null
$stamp = Get-Date -Format &quot;yyyyMMdd-HHmm&quot;
$results = @()

foreach ($row in (Import-Csv -Path $MappingFile)) {
    $name = ($row.Source.TrimEnd(&quot;\&quot;) -split &quot;\\&quot;)[-1]
    $log = Join-Path -Path $LogFolder -ChildPath &quot;$name-$stamp.log&quot;

    $arguments = @(
        $row.Source, $row.Target,
        &quot;/MT:$Threads&quot;, &quot;/R:2&quot;, &quot;/W:1&quot;, &quot;/B&quot;, &quot;/MIR&quot;, &quot;/IT&quot;,
        &quot;/COPY:DATSO&quot;, &quot;/DCOPY:DAT&quot;, &quot;/NP&quot;, &quot;/NFL&quot;, &quot;/NDL&quot;,
        &quot;/XD&quot;, &quot;System Volume Information&quot;,
        &quot;/UNILOG:$log&quot;
    )
    if ($ListOnly) {
        $arguments += &quot;/L&quot;
    }

    $started = Get-Date
    &amp; robocopy.exe @arguments | Out-Null
    $code = $LASTEXITCODE

    $results += [pscustomobject]@{
        Share    = $name
        ExitCode = $code
        Result   = if ($code -ge 8) { &quot;FAILED&quot; } else { &quot;OK&quot; }
        Minutes  = [math]::Round(((Get-Date) - $started).TotalMinutes, 1)
        Log      = $log
    }
}

$results | Format-Table -AutoSize
if ($results | Where-Object { $_.ExitCode -ge 8 }) {
    Write-Warning &quot;One or more shares had copy failures. Check the logs, then run another pass.&quot;
}
</code></pre>
<p>The <code>shares.csv</code> is two columns under a <code>Source,Target</code> header row, for example <code>\\oldfs01\finance,\\&lt;account&gt;.file.core.windows.net\finance</code>. Keep the source and target at exactly the same folder level: Microsoft warns that <code>/MIR</code> against mismatched levels produces large-scale deletions and recopies. And freeze big namespace changes (mass moves, ACL rewrites) during the migration window, because every catch-up pass has to replay them.</p>
<p>To keep users&apos; paths working after cutover, a DFS Namespace in front of the shares is the cleanest option. Microsoft documents root consolidation for exactly this: a stand-alone namespace named <code>#OldServerName</code> on a member server, folders named after the old shares with the Azure file share as the target, the old name transferred with <code>netdom computername &lt;dfs-server&gt; /add:&lt;old-name&gt;</code>, and a CNAME from the old name to the namespace server. The source server has to be offline for that step, so schedule it with the final robocopy pass.</p>
<h2>Cloud Tiering&apos;s Hidden Cost</h2>
<p>For some sites we used Azure File Sync to keep an on-prem cache in front of the cloud share, with cloud tiering enabled to reclaim local disk. That worked well for weeks, then stalled badly the first time someone opened a folder of large files that had tiered out and hadn&apos;t been touched recently. Every one of those files had to be recalled over the WAN on first read, all at once, and what should have been an instant folder open turned into a multi-minute stall.</p>
<p>The mechanics explain it. Tiering is driven by a volume free space policy and an optional date policy, ranked by a heatmap of last access and modify times. A tiered file keeps its namespace entry locally with a reparse point and the offline and recall-on-data-access attributes, and its content comes down on first read. Microsoft also warns that the agent reserves 10% of memory for persisting recalls, and a burst of recalls against many tiered files can hit that threshold and cause extra egress, slow I/O and hangs.</p>
<p>The fix wasn&apos;t complicated once we knew the knobs existed. Folders with bursty, all-at-once access go on the <code>GhostingExclusionList</code> registry value so they&apos;re never tiered, anything already tiered gets recalled ahead of a known event (a fiscal year archive review, say), and we warn users before those events.</p>
<pre><code class="language-powershell">&lt;#
.SYNOPSIS
    Excludes a folder from cloud tiering and recalls anything in it that is already tiered.
.DESCRIPTION
    Sets the Azure File Sync GhostingExclusionList registry value, restarts FileSyncSvc
    so the exclusion takes effect, then runs Invoke-StorageSyncFileRecall on the folder.
.PARAMETER FolderPath
    Folder under a server endpoint to keep local, for example D:\Shares\Projects\Active.
.EXAMPLE
    .\Set-TieringExclusion.ps1 -FolderPath &quot;D:\Shares\Projects\Active&quot;
.NOTES
    Author  : Thomas Lasswell (https://www.techcolumnist.com)
    Version : 1.0 (2026-04-22)
    Requires: Azure File Sync agent, elevated session. On a failover cluster use the Cluster\StorageSync registry path instead.
#&gt;
param (
    [Parameter(Mandatory = $true)] [string] $FolderPath
)

$key = &quot;HKLM:\SOFTWARE\Microsoft\Azure\StorageSync&quot;
# The value is one pipe-separated string; append instead of overwriting existing exclusions.
$current = (Get-ItemProperty -Path $key -Name &quot;GhostingExclusionList&quot; -ErrorAction SilentlyContinue).GhostingExclusionList
# Paths are stored with doubled backslashes, and ^ $ ( ) [ ] { } + need a backslash escape.
$escaped = $FolderPath.Replace(&quot;\&quot;, &quot;\\&quot;) -replace &apos;([\^\$\(\)\[\]\{\}\+])&apos;, &apos;\$1&apos;
$entries = @($current -split &quot;\|&quot; | Where-Object { $_ }) + $escaped | Select-Object -Unique
Set-ItemProperty -Path $key -Name &quot;GhostingExclusionList&quot; -Value ($entries -join &quot;|&quot;) -Type String

Restart-Service -Name &quot;FileSyncSvc&quot;

# Exclusions don&apos;t apply to files that are already tiered, so recall them now.
Import-Module &quot;C:\Program Files\Azure\StorageSyncAgent\StorageSync.Management.ServerCmdlets.dll&quot;
Invoke-StorageSyncFileRecall -Path $FolderPath -ThreadCount 8 -PerFileRetryCount 3 -PerFileRetryDelaySeconds 10
</code></pre>
<p>Microsoft&apos;s documentation says folder paths in this value use doubled backslashes (<code>D:\\Shares\\Projects</code>), each exclusion is separated by a pipe, and the characters <code>^ $ ( ) [ ] \{ \} +</code> in a path need a backslash escape, which is what the two replace operations do. File name and extension exclusions apply to every server endpoint on the server. You can confirm what the agent picked up in Event ID 9001 in the Telemetry log under <code>Applications and Services\Microsoft\FileSync\Agent</code>. <code>fsutil reparsepoint query &lt;file&gt;</code> showing tag <code>0x8000001e</code> tells you a given file is tiered.</p>
<h2>What We&apos;d Do Differently</h2>
<p>Test the actual applications against the actual latency before committing, not just the file copy throughput, and read the E2E-versus-server latency gap before blaming the tier. Get the AD DS Kerberos path and the share-level RBAC layer working in a pilot before touching production ACLs. Migrate with robocopy in repeated passes and put DFS-N in front so paths survive. And treat cloud tiering as something that needs explicit exclusions for any folder with bursty access patterns, not a set-and-forget setting. None of this makes Azure Files a bad target: for the steady, low-chatter file shares most departments actually use, it has worked well since. But it isn&apos;t the transparent swap the marketing implies, and the gap shows up exactly where you didn&apos;t look for it.</p>
<h2>References</h2>
<ul><li><a href="https://learn.microsoft.com/en-us/azure/storage/files/understand-performance">Understand Azure Files performance</a></li>
<li><a href="https://learn.microsoft.com/en-us/azure/storage/files/storage-files-scale-targets">Azure Files scale and performance targets</a></li>
<li><a href="https://learn.microsoft.com/en-us/azure/storage/files/understanding-billing">Understand Azure Files billing models</a></li>
<li><a href="https://learn.microsoft.com/en-us/azure/storage/files/storage-files-active-directory-overview">Overview of Azure Files identity-based authentication</a></li>
<li><a href="https://learn.microsoft.com/en-us/azure/storage/files/storage-files-identity-ad-ds-enable">Enable AD DS authentication for Azure Files</a></li>
<li><a href="https://learn.microsoft.com/en-us/azure/storage/files/storage-files-identity-assign-share-level-permissions">Assign share-level permissions for Azure Files</a></li>
<li><a href="https://learn.microsoft.com/en-us/azure/storage/files/storage-files-networking-endpoints">Configure Azure Files network endpoints</a></li>
<li><a href="https://learn.microsoft.com/en-us/azure/storage/files/storage-files-migration-robocopy">Migrate to Azure Files using RoboCopy</a></li>
<li><a href="https://learn.microsoft.com/en-us/azure/storage/files/files-manage-namespaces">How to use DFS-N with Azure Files</a></li>
<li><a href="https://learn.microsoft.com/en-us/azure/storage/file-sync/file-sync-how-to-manage-tiered-files">Manage Azure File Sync tiered files</a></li>
</ul>
]]></content:encoded>
      <category>Engineering</category>
    </item>
    <item>
      <title>Azure: Landing Zone Design for a Mid-Size Company, Three Years In</title>
      <link>https://www.techcolumnist.com/2026/04/15/azure-landing-zone-design-for-a-mid-size-company-three-years-in/</link>
      <guid isPermaLink="true">https://www.techcolumnist.com/2026/04/15/azure-landing-zone-design-for-a-mid-size-company-three-years-in/</guid>
      <pubDate>Wed, 15 Apr 2026 14:00:00 GMT</pubDate>
      <dc:creator>Tom Lasswell</dc:creator>
      <description>Three years of running an Azure landing zone: a smaller management group tree, pinned policy versions, and subscription vending, with the Bicep and az CLI to build it.</description>
      <content:encoded><![CDATA[<p>I designed my first Azure landing zone with the Cloud Adoption Framework diagrams open in one window and a blank management group tree in the other, trying to guess how much structure a company our size actually needed. Three years and a few painful lessons later, here is what I would tell that version of myself, along with the code I would now start from instead of the portal.</p>
<h2>Start With Fewer Management Groups Than the Diagram Shows</h2>
<p>The current Azure landing zone reference hierarchy is bigger than most people remember. Under the tenant root it puts an intermediate root with your company prefix, then <code>Platform</code> (with <code>Security</code>, <code>Management</code>, <code>Connectivity</code> and <code>Identity</code> children), <code>Landing zones</code> (with <code>Corp</code>, <code>Online</code> and <code>Local</code> children), <code>Sandboxes</code> and <code>Decommissioned</code>. That is a dozen groups before a single workload lands. I built nearly all of it on day one for a company with maybe fifteen subscriptions, and most of that structure sat empty for two years. A management group with one subscription under it is not governance, it is a folder with extra steps.</p>
<p>The CAF guidance itself backs restraint more than the diagram suggests. It recommends keeping the hierarchy &quot;reasonably flat, ideally with no more than three to four levels&quot;, tells you not to mirror your org chart, and says not to create management groups for production, test and development: separate those by subscription inside the same group. It also recommends pointing new subscriptions at a default management group (a <code>sandbox</code> group is the suggested candidate) so nothing lands under the tenant root by accident, and turning on the hierarchy setting that requires authorization to create management groups, because by default any user in the tenant can create one.</p>
<p>What actually earned its place for us: a <code>Platform</code> group holding the identity, connectivity and management subscriptions directly (no child groups until a platform subscription needed different policy), a <code>Landing zones</code> group split into <code>Corp</code> and <code>Online</code> for internal versus internet-facing workloads, a <code>Sandbox</code> group with policies loose enough that engineers stop provisioning shadow resource groups just to escape the guardrails, and a <code>Decommissioned</code> group to park cancelled subscriptions. Everything else I added later, when a real workload justified it.</p>
<p>Here is that tree as Bicep. Management groups are tenant-level resources, so from a management group deployment each one is declared with <code>scope: tenant()</code> and a <code>details.parent.id</code>, which is the pattern in Microsoft&apos;s Bicep management group deployment docs.</p>
<pre><code class="language-bicep">// mg-hierarchy.bicep: a deliberately small ALZ-style management group tree.
// Deploy at the tenant root group, whose ID is the Microsoft Entra tenant ID.
targetScope = &apos;managementGroup&apos;

@description(&apos;Short company prefix, used as the intermediate root ID.&apos;)
param prefix string = &apos;contoso&apos;

@description(&apos;Display name for the intermediate root.&apos;)
param rootDisplayName string = &apos;Contoso&apos;

resource intRoot &apos;Microsoft.Management/managementGroups@2023-04-01&apos; = {
  scope: tenant()
  name: prefix
  properties: {
    displayName: rootDisplayName
    details: {
      parent: {
        id: managementGroup().id
      }
    }
  }
}

var topLevel = [
  {
    name: &apos;${prefix}-platform&apos;
    displayName: &apos;Platform&apos;
  }
  {
    name: &apos;${prefix}-sandbox&apos;
    displayName: &apos;Sandbox&apos;
  }
  {
    name: &apos;${prefix}-decommissioned&apos;
    displayName: &apos;Decommissioned&apos;
  }
]

resource topGroups &apos;Microsoft.Management/managementGroups@2023-04-01&apos; = [for mg in topLevel: {
  scope: tenant()
  name: mg.name
  properties: {
    displayName: mg.displayName
    details: {
      parent: {
        id: intRoot.id
      }
    }
  }
}]

resource landingZones &apos;Microsoft.Management/managementGroups@2023-04-01&apos; = {
  scope: tenant()
  name: &apos;${prefix}-landingzones&apos;
  properties: {
    displayName: &apos;Landing zones&apos;
    details: {
      parent: {
        id: intRoot.id
      }
    }
  }
}

var workloadTypes = [
  {
    name: &apos;${prefix}-corp&apos;
    displayName: &apos;Corp&apos;
  }
  {
    name: &apos;${prefix}-online&apos;
    displayName: &apos;Online&apos;
  }
]

resource workloadGroups &apos;Microsoft.Management/managementGroups@2023-04-01&apos; = [for mg in workloadTypes: {
  scope: tenant()
  name: mg.name
  properties: {
    displayName: mg.displayName
    details: {
      parent: {
        id: landingZones.id
      }
    }
  }
}]

output landingZonesId string = landingZones.id
</code></pre>
<p>Deploy it, then set the two hierarchy settings. The root management group&apos;s ID is the tenant ID, and only a Global Administrator who has elevated access can grant rights at the root in the first place. Elevation itself only gives you User Access Administrator at root scope, which can&apos;t deploy anything, so use it to assign yourself (or the pipeline identity) Owner on the tenant root group first. This is a one-time bootstrap run by someone with that access.</p>
<pre><code class="language-bash">#!/usr/bin/env bash
# bootstrap-hierarchy.sh: deploy the management group tree and protect the root.
set -euo pipefail

TENANT_ID=&quot;&lt;tenant-id&gt;&quot;          # the tenant root group has the same ID
PREFIX=&quot;contoso&quot;
LOCATION=&quot;eastus&quot;                # where deployment metadata is stored

az deployment mg create \
  --name alz-hierarchy \
  --location &quot;$LOCATION&quot; \
  --management-group-id &quot;$TENANT_ID&quot; \
  --template-file mg-hierarchy.bicep \
  --parameters prefix=&quot;$PREFIX&quot;

# New subscriptions land in Sandbox instead of the tenant root,
# and creating management groups requires write access on the root.
az account management-group hierarchy-settings create \
  --name &quot;$TENANT_ID&quot; \
  --default-management-group &quot;/providers/Microsoft.Management/managementGroups/${PREFIX}-sandbox&quot; \
  --require-authorization-for-group-creation true

# Place the platform subscriptions directly under Platform.
for SUB in &quot;&lt;identity-subscription-id&gt;&quot; &quot;&lt;connectivity-subscription-id&gt;&quot; &quot;&lt;management-subscription-id&gt;&quot;; do
  az account management-group subscription add \
    --name &quot;${PREFIX}-platform&quot; \
    --subscription &quot;$SUB&quot;
done
</code></pre>
<p>If you want the full reference architecture rather than this trimmed tree, Microsoft&apos;s current Bicep path is the ALZ Bicep accelerator built on Azure Verified Modules (AVM), which also uses Azure Deployment Stacks to clean up resources and policies that drop out of the templates. The older ALZ-Bicep modules are now labelled &quot;classic&quot;. I would still start small and let the accelerator&apos;s structure be something you grow into, not something you inherit.</p>
<h2>Policy Assignments Are a Liability the Moment You Stop Reading Them</h2>
<p>Azure Policy is where landing zone design goes to either succeed quietly or fail loudly, and the failure mode is almost always the same: someone assigns a built-in initiative wholesale, it works fine for a year, and then a change to that initiative&apos;s underlying policies alters behaviour nobody voted on. I have had a deny effect I never explicitly configured start blocking a deployment because it was bundled two levels deep in an initiative we assigned once and never opened again.</p>
<p>This is documented behaviour, not bad luck. Built-in definitions are versioned <code>Major.Minor.Patch</code>, and Microsoft lists &quot;adding or moving definitions within an initiative&quot; and &quot;minor rule logic changes&quot; as minor-version changes. An assignment defaults to the latest major version and automatically takes minor and patch updates. You can change that with the assignment&apos;s <code>definitionVersion</code> property: <code>1.*.*</code> follows every minor update, while <code>1.1.*</code> pins the minor version and only takes patches (patches are always applied, and are limited to text changes and break-glass fixes).</p>
<p>The fix that actually worked was boring: prefer individual built-in policies (or custom initiatives you assemble from them) over someone else&apos;s bundle, pin the minor version on anything with a deny or modify effect, and review every assignment on a quarterly cadence rather than when something breaks. Policy changes then come from a pull request, not a platform update. These are the three assignments I put at the intermediate root and landing zone groups on day one, all built-in definitions referenced by their fixed IDs:</p>
<table><thead><tr><th>Built-in policy</th><th>Definition ID</th><th>Why</th></tr>
</thead><tbody><tr><td>Allowed locations</td><td><code>e56962a6-4747-49cd-b67b-bf8b01975c4c</code></td><td>Keeps resources in the regions you have networking and data residency for</td></tr>
<tr><td>Require a tag on resource groups</td><td><code>96670d01-0a4d-4649-9c89-2d3abc0a5025</code></td><td>No resource group without a <code>costCenter</code></td></tr>
<tr><td>Inherit a tag from the resource group if missing</td><td><code>ea3f2387-9b95-492a-a190-fcdc54f7b070</code></td><td>Copies <code>costCenter</code> down to resources (modify effect)</td></tr>
</tbody></table>
<pre><code class="language-bicep">// core-policy.bicep: deploy at the intermediate root management group.
targetScope = &apos;managementGroup&apos;

param allowedLocations array = [
  &apos;eastus&apos;
  &apos;eastus2&apos;
]

param costTagName string = &apos;costCenter&apos;

@description(&apos;Region for the managed identity that the modify assignment needs.&apos;)
param identityLocation string = &apos;eastus&apos;

var builtIn = {
  allowedLocations: tenantResourceId(&apos;Microsoft.Authorization/policyDefinitions&apos;, &apos;e56962a6-4747-49cd-b67b-bf8b01975c4c&apos;)
  requireRgTag: tenantResourceId(&apos;Microsoft.Authorization/policyDefinitions&apos;, &apos;96670d01-0a4d-4649-9c89-2d3abc0a5025&apos;)
  inheritRgTag: tenantResourceId(&apos;Microsoft.Authorization/policyDefinitions&apos;, &apos;ea3f2387-9b95-492a-a190-fcdc54f7b070&apos;)
}

// Contributor, the role the inherit-tag definition declares in roleDefinitionIds.
var contributorRoleId = &apos;b24988ac-6180-42a0-ab88-20f7382dd24c&apos;

// Management group scope limits assignment names to 24 characters.
resource locations &apos;Microsoft.Authorization/policyAssignments@2025-03-01&apos; = {
  name: &apos;allowed-locations&apos;
  properties: {
    displayName: &apos;Allowed locations&apos;
    policyDefinitionId: builtIn.allowedLocations
    definitionVersion: &apos;1.1.*&apos;
    parameters: {
      listOfAllowedLocations: {
        value: allowedLocations
      }
    }
    nonComplianceMessages: [
      {
        message: &apos;Deploy only to approved regions. Request an exemption from the platform team if you need another.&apos;
      }
    ]
  }
}

resource rgTag &apos;Microsoft.Authorization/policyAssignments@2025-03-01&apos; = {
  name: &apos;require-rg-costcenter&apos;
  properties: {
    displayName: &apos;Require ${costTagName} on resource groups&apos;
    policyDefinitionId: builtIn.requireRgTag
    parameters: {
      tagName: {
        value: costTagName
      }
    }
    nonComplianceMessages: [
      {
        message: &apos;Every resource group needs a ${costTagName} tag.&apos;
      }
    ]
  }
}

resource inheritTag &apos;Microsoft.Authorization/policyAssignments@2025-03-01&apos; = {
  name: &apos;inherit-rg-costcenter&apos;
  location: identityLocation
  identity: {
    type: &apos;SystemAssigned&apos;
  }
  properties: {
    displayName: &apos;Inherit ${costTagName} from the resource group&apos;
    policyDefinitionId: builtIn.inheritRgTag
    parameters: {
      tagName: {
        value: costTagName
      }
    }
  }
}

// The modify effect needs its identity to hold the declared role at the assignment scope.
resource inheritTagRole &apos;Microsoft.Authorization/roleAssignments@2022-04-01&apos; = {
  name: guid(managementGroup().id, &apos;inherit-rg-costcenter&apos;, contributorRoleId)
  properties: {
    roleDefinitionId: tenantResourceId(&apos;Microsoft.Authorization/roleDefinitions&apos;, contributorRoleId)
    principalId: inheritTag.identity.principalId
    principalType: &apos;ServicePrincipal&apos;
  }
}
</code></pre>
<p>Two details bit me here. Policy assignment names at management group scope are limited to 24 characters, which is why the names above are terse. And a modify policy only changes resources as they are created or updated; existing resources are marked non-compliant and need a remediation task, which runs as the assignment&apos;s managed identity.</p>
<p>The quarterly review is a script, not a meeting. This one exports every assignment at a management group plus the current content of each built-in initiative it references, so you can commit the output and let <code>git diff</code> tell you what Microsoft changed since last quarter.</p>
<pre><code class="language-bash">#!/usr/bin/env bash
# policy-snapshot.sh &lt;management-group-id&gt; [output-dir]
# Exports assignments at one management group and the member list of every
# built-in initiative they reference. Commit the output; diff it next quarter.
set -euo pipefail

MG=&quot;${1:?usage: policy-snapshot.sh &lt;management-group-id&gt; [output-dir]}&quot;
OUT=&quot;${2:-policy-snapshot}&quot;
mkdir -p &quot;$OUT/assignments&quot; &quot;$OUT/initiatives&quot;

az policy assignment list \
  --management-group &quot;$MG&quot; \
  --filter &quot;atScope()&quot; \
  --query &quot;[].{name:name, definition:policyDefinitionId, version:definitionVersion, enforcement:enforcementMode}&quot; \
  --output json &gt; &quot;$OUT/assignments/$MG.json&quot;

az policy assignment list \
  --management-group &quot;$MG&quot; \
  --filter &quot;atScope()&quot; \
  --query &quot;[].policyDefinitionId&quot; \
  --output tsv |
while read -r defId; do
  case &quot;$defId&quot; in
    /providers/Microsoft.Authorization/policySetDefinitions/*)
      name=&quot;${defId##*/}&quot;
      az policy set-definition show \
        --name &quot;$name&quot; \
        --query &quot;{displayName:displayName, version:version, policies:policyDefinitions[].{ref:policyDefinitionReferenceId, id:policyDefinitionId, version:definitionVersion}}&quot; \
        --output json &gt; &quot;$OUT/initiatives/$name.json&quot;
      ;;
  esac
done

echo &quot;Snapshot written to $OUT. Review with: git diff --stat -- $OUT&quot;
</code></pre>
<h2>Subscription Vending Beats Subscription Requests</h2>
<p>For the first eighteen months, every new subscription meant a ticket, a manual policy pass, and someone remembering to wire up the right network peering and log forwarding. It worked until it did not scale past the two people who understood the whole checklist. Automating subscription creation as a vending process, a pipeline that runs the same governance steps every time, was the single highest-leverage change I made to the landing zone.</p>
<p>CAF now describes exactly this. The vending automation should capture the request (budget, owners, networking, criticality) at intake, place the subscription in the right management group, create the peered virtual network, assign access through Entra groups rather than individuals, tag it for cost reporting, and create a starting budget the application team then adjusts. Microsoft publishes subscription vending modules for Bicep and Terraform (<code>aka.ms/lz-vending/bicep</code> and <code>aka.ms/lz-vending/tf</code>), and notes that creating subscriptions programmatically needs an EA, MCA or MPA agreement, while everything after creation can be automated regardless. New subscriptions come out identical now, and the checklist lives in code review history instead of one person&apos;s memory. For the access side, I also run a periodic check of who holds Owner across every subscription; the script is in <a href="https://www.techcolumnist.com/2025/11/19/powershell-azure-audit-who-has-owner-role-across-all-subscriptions/">Audit Who Has Owner Role Across All Subscriptions</a>.</p>
<h2>Cost Management Should Have Been Day One, Not Year Two</h2>
<p>I treated cost management as an operational nicety and bolted it on well after the platform was live, which meant a year of budget alerts configured inconsistently across subscriptions and no shared tagging standard to slice spend by team or environment. Retrofitting tags onto resources that already existed is much harder than enforcing them at the vending stage, where the <code>require-rg-costcenter</code> assignment above simply blocks the deployment. For the backlog of untagged resources that predate the policy, <a href="https://www.techcolumnist.com/2025/09/24/powershell-azure-tag-every-untagged-resource-in-a-subscription/">Tag Every Untagged Resource in a Subscription</a> is the cleanup pass I used.</p>
<h2>What I Would Keep Doing</h2>
<p>The hub-and-spoke network topology, the centralized Log Analytics workspace in the management subscription, and the decision to build identity first rather than as an afterthought all held up under three years of growth. So did keeping application teams&apos; role assignments at subscription or resource group scope, which is also what CAF recommends: management groups are for policy, and standing RBAC at that level is reserved for platform staff through Privileged Identity Management. Landing zone design rewards restraint on scaffolding and discipline on the few controls that actually govern risk. Everything else can be added later, and usually should be.</p>
<h2>References</h2>
<ul><li><a href="https://learn.microsoft.com/en-us/azure/cloud-adoption-framework/ready/landing-zone/design-area/resource-org-management-groups">Management groups (Cloud Adoption Framework design area)</a></li>
<li><a href="https://learn.microsoft.com/en-us/azure/cloud-adoption-framework/ready/landing-zone/design-area/subscription-vending">Subscription vending (Cloud Adoption Framework)</a></li>
<li><a href="https://learn.microsoft.com/en-us/azure/governance/management-groups/how-to/protect-resource-hierarchy">Protect your resource hierarchy</a></li>
<li><a href="https://learn.microsoft.com/en-us/azure/azure-resource-manager/bicep/deploy-to-management-group">Use Bicep to deploy resources to a management group</a></li>
<li><a href="https://learn.microsoft.com/en-us/azure/governance/policy/concepts/definition-structure-basics">Azure Policy definition structure basics (versioning)</a></li>
<li><a href="https://learn.microsoft.com/en-us/azure/governance/policy/concepts/assignment-structure">Azure Policy assignment structure (definitionVersion)</a></li>
<li><a href="https://learn.microsoft.com/en-us/azure/governance/policy/concepts/effect-modify">Azure Policy modify effect</a></li>
<li><a href="https://learn.microsoft.com/en-us/azure/governance/policy/samples/built-in-policies">Azure Policy built-in policy definitions</a></li>
<li><a href="https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/resource-name-rules">Naming rules for Azure resources (policy assignment name limits)</a></li>
<li><a href="https://azure.github.io/Azure-Landing-Zones/bicep/">Azure landing zones Bicep implementation</a></li>
</ul>
]]></content:encoded>
      <category>Engineering</category>
      <category>Strategy</category>
    </item>
    <item>
      <title>Intune: Autopilot Provisioning Failures and How to Actually Debug Them</title>
      <link>https://www.techcolumnist.com/2026/04/08/intune-autopilot-provisioning-failures-and-how-to-actually-debug-them/</link>
      <guid isPermaLink="true">https://www.techcolumnist.com/2026/04/08/intune-autopilot-provisioning-failures-and-how-to-actually-debug-them/</guid>
      <pubDate>Wed, 08 Apr 2026 14:00:00 GMT</pubDate>
      <dc:creator>Tom Lasswell</dc:creator>
      <description>Debugging Windows Autopilot failures from the evidence: documented error codes, event IDs, ESP tracking and timeouts, log collection, and triage scripts for device and Graph.</description>
      <content:encoded><![CDATA[<p>Autopilot is one of the better ideas Microsoft has shipped for endpoint management, and it&apos;s also one of the easiest things to make look unreliable by debugging it wrong. When a machine fails partway through the enrollment status page, the instinct on most help desks is to reimage it and try again. Sometimes that works, which is exactly the problem: it teaches everyone that Autopilot is flaky instead of teaching anyone what actually went wrong. I&apos;ve found that treating a stuck Autopilot run as a diagnosable event, not a coin flip, is the difference between a five-minute fix and a recurring mystery.</p>
<h2>Read the error code before you touch the machine</h2>
<p>Most Autopilot failures surface a specific code, and almost nobody reads it before they wipe the device. When there is one, record it before you reset anything. The earlier version of this post got two of the most common ones wrong, so here they are as Microsoft documents them:</p>
<table><thead><tr><th>Code</th><th>Where you see it</th><th>What Microsoft says it means</th></tr>
</thead><tbody><tr><td><code>0x800705B4</code></td><td>Self-deploying or pre-provisioning, usually at <strong>Securing your hardware</strong></td><td>A general timeout. The common cause in self-deploying mode is a device that isn&apos;t TPM 2.0 capable, such as a virtual machine. Those can&apos;t use self-deploying mode at all.</td></tr>
<tr><td><code>0x80180014</code></td><td>Re-running Autopilot on a device that was deployed before</td><td>Either the device was previously deployed with self-deploying or pre-provisioning mode and its Intune record has to be deleted (or the device unblocked under <strong>Windows Autopilot &gt; Devices &gt; Unblock device</strong>), or <strong>Windows (MDM)</strong> enrollment is set to Block in a device platform restriction that applies to it.</td></tr>
<tr><td><code>0x801c03ea</code></td><td>Self-deploying</td><td>TPM attestation failed, so the Microsoft Entra join with a device token failed.</td></tr>
<tr><td><code>0x81039001</code></td><td>Self-deploying or pre-provisioning technician flow</td><td><code>E_AUTOPILOT_CLIENT_TPM_MAX_ATTESTATION_RETRY_EXCEEDED</code>, intermittent; a retry may succeed.</td></tr>
<tr><td><code>0xc1036501</code></td><td>Self-deploying</td><td>Automatic MDM enrollment can&apos;t pick an MDM because there are multiple MDM configurations in Entra ID.</td></tr>
<tr><td><code>0x80070774</code></td><td>Hybrid join, during ESP</td><td>Domain mismatch between where the Intune Connector for Active Directory runs and where devices are targeted.</td></tr>
<tr><td><code>0x801C03F3</code></td><td>Pre-provisioning, in the User Device Registration admin log</td><td>Entra ID can&apos;t find the device object, usually because someone deleted it.</td></tr>
<tr><td><code>80180018</code></td><td>&quot;Something went wrong&quot; page</td><td>An Intune enrollment problem, typically a missing license or too many devices enrolled for the user.</td></tr>
</tbody></table>
<p>My original text said <code>0x80180014</code> meant a conflicting Entra ID object from an old enrollment, and that <code>0x800705B4</code> almost always meant waiting on an app scoped to the wrong group. Neither matches Microsoft&apos;s documentation. With <code>0x80180014</code> in particular, the ETW trace shows <code>Enrollment blocked for AP device by SDM One Time Limit Check</code>, which points you straight at the device record, not at Entra ID. None of these get fixed by reimaging alone. They get fixed by looking at the code and correcting the cause; a reset or redeployment may still be needed afterward, but only once the record or configuration is right.</p>
<p>The Autopilot event log (<strong>Applications and Services Logs &gt; Microsoft &gt; Windows &gt; ModernDeployment-Diagnostics-Provider &gt; Autopilot</strong>) adds the profile side of the story. The event IDs I look for first:</p>
<ul><li><strong>807</strong> <code>ZtdDeviceIsNotRegistered</code>: the hardware hash isn&apos;t uploaded or isn&apos;t assigned to a profile.</li>
<li><strong>809</strong> and <strong>815</strong> <code>ZtdDeviceHasNoAssignedProfile</code>: the assigned profile was deleted, or nothing is assigned and there&apos;s no default.</li>
<li><strong>908</strong> <code>SerialNumberMismatch</code> / <code>ProductKeyIdMismatch</code>: the registration doesn&apos;t match the hardware; re-register.</li>
<li><strong>171</strong> and <strong>172</strong>: TPM identity confirmation failed during self-deploying mode.</li>
<li><strong>153</strong> with <code>ProfileState_Available</code>: a profile was downloaded, so the problem is later in the flow.</li>
<li><strong>163</strong>: a profile is already on the device and won&apos;t be downloaded again until it&apos;s reset.</li>
</ul>
<h2>Collect the evidence properly</h2>
<p>Intune already does part of this for you. When a Windows Autopilot deployment fails, the device can automatically capture and upload a diagnostics package, one set per day per device, kept for 28 days. It&apos;s on by default under <strong>Tenant administration &gt; Device diagnostics</strong> and shows up on the device&apos;s <strong>Diagnostics</strong> tab. On Windows 11 user-driven deployments, turning on <strong>Turn on log collection and diagnostics page for end users</strong> in the ESP profile also gives the technician the Autopilot diagnostics page with <strong>Ctrl+Shift+D</strong>.</p>
<p>On the device itself, <strong>Shift+F10</strong> at OOBE opens a command prompt, and this is the collection command Microsoft gives in the Autopilot known issues:</p>
<pre><code class="language-cmd">mdmdiagnosticstool.exe -area &quot;Autopilot;TPM&quot; -cab C:\autopilot.cab
</code></pre>
<p>For enrollment and provisioning problems more broadly, use the areas from the MDM log collection doc; the zip contains <code>MDMDiagHtmlReport.html</code>, <code>MDMDiagReport.xml</code>, a registry dump and the admin event logs:</p>
<pre><code class="language-cmd">mdmdiagnosticstool.exe -area &quot;DeviceEnrollment;DeviceProvisioning;Autopilot&quot; -zip C:\Users\Public\Documents\MDMDiagReport.zip
</code></pre>
<p>To turn that into something readable, Michael Niehaus&apos;s <code>Get-AutopilotDiagnostics</code> script on the PowerShell Gallery parses the live device or a captured archive and lists the profile, ESP tracking, apps, policies and certificates with their status. The gallery page notes it doesn&apos;t work on ARM64:</p>
<pre><code class="language-powershell">Install-Script -Name Get-AutopilotDiagnostics -Force
Get-AutopilotDiagnostics.ps1 -CABFile C:\autopilot.cab
Get-AutopilotDiagnostics.ps1 -Online
</code></pre>
<p><code>-Online</code> looks up additional app and policy details from your tenant, which makes the output far easier to read on a real deployment. The Intune Management Extension logs, which cover Win32 apps and scripts, are in <code>%ProgramData%\Microsoft\IntuneManagementExtension\Logs</code>.</p>
<p>When I&apos;m at the device and want a one-screen answer before digging through archives, I run this from the Shift+F10 prompt (<code>powershell.exe -ExecutionPolicy Bypass -File D:\Get-AutopilotTriage.ps1</code>) or from an elevated session afterwards. It reads the Autopilot profile values Windows stored, pulls the known Autopilot event IDs plus recent errors from the MDM and device registration logs, checks the TPM, prints the device clock, and saves the diagnostics archive:</p>
<pre><code class="language-powershell">&lt;#
.SYNOPSIS
    One-screen Autopilot triage on the affected device.
.DESCRIPTION
    Reads the Autopilot profile values from
    HKLM:\SOFTWARE\Microsoft\Provisioning\Diagnostics\Autopilot, lists the
    documented Autopilot event IDs from the ModernDeployment-Diagnostics-Provider
    log, the latest errors from the DeviceManagement-Enterprise-Diagnostics-Provider
    and User Device Registration admin logs, TPM readiness and the device clock,
    then runs mdmdiagnosticstool to capture an archive for deeper analysis.
.PARAMETER OutputFolder
    Folder for the diagnostics archive. Defaults to C:\AutopilotTriage.
.PARAMETER MaxEvents
    Number of recent errors to show per log. Defaults to 5.
.EXAMPLE
    .\Get-AutopilotTriage.ps1
.NOTES
    Author  : Thomas Lasswell (https://www.techcolumnist.com)
    Version : 1.0 (2026-04-08)
    Requires: Elevated PowerShell on the affected device.
#&gt;

[CmdletBinding()]
param (
    [Parameter()]
    [string]$OutputFolder = &quot;C:\AutopilotTriage&quot;,

    [Parameter()]
    [int]$MaxEvents = 5
)

New-Item -Path $OutputFolder -ItemType Directory -Force | Out-Null

# Profile values Windows received from the Autopilot deployment service.
Write-Host &quot;== Autopilot profile&quot; -ForegroundColor Cyan
$profileKey = &quot;HKLM:\SOFTWARE\Microsoft\Provisioning\Diagnostics\Autopilot&quot;
$apProfile = Get-ItemProperty -Path $profileKey -ErrorAction SilentlyContinue
if ($apProfile) {
    $apProfile | Select-Object -Property CloudAssignedTenantDomain, CloudAssignedTenantId, IsAutopilotDisabled, TenantMatched, CloudAssignedOobeConfig | Format-List
} else {
    Write-Host &quot;No Autopilot profile values found. The device may not be registered, or the profile download failed.&quot;
}

# Documented Autopilot event IDs and what they mean.
$known = @{
    100 = &quot;Profile not found yet (usually transient)&quot;
    153 = &quot;Profile state changed (ProfileState_Available = profile downloaded)&quot;
    163 = &quot;Already provisioned; reset the device to download a new profile&quot;
    171 = &quot;TPM identity confirmation failed (self-deploying)&quot;
    172 = &quot;Could not mark profile available (see 171)&quot;
    807 = &quot;ZtdDeviceIsNotRegistered: hash not uploaded or not assigned&quot;
    809 = &quot;Assigned profile was deleted&quot;
    815 = &quot;No profile assigned and no default profile&quot;
    908 = &quot;Serial number or product key mismatch; re-register&quot;
}
Write-Host &quot;== Autopilot events&quot; -ForegroundColor Cyan
$apEvents = Get-WinEvent -LogName &quot;Microsoft-Windows-ModernDeployment-Diagnostics-Provider/Autopilot&quot; -MaxEvents 200 -ErrorAction SilentlyContinue |
    Where-Object { $known.ContainsKey($_.Id) }
$apEvents | Select-Object -First 15 -Property TimeCreated, Id, @{ Name = &quot;Meaning&quot;; Expression = { $known[$_.Id] } } | Format-Table -AutoSize

# Latest errors from the enrollment and registration logs.
$logs = @(
    &quot;Microsoft-Windows-DeviceManagement-Enterprise-Diagnostics-Provider/Admin&quot;,
    &quot;Microsoft-Windows-User Device Registration/Admin&quot;
)
foreach ($log in $logs) {
    Write-Host &quot;== Errors: $log&quot; -ForegroundColor Cyan
    $errors = Get-WinEvent -FilterHashtable @{ LogName = $log; Level = 2 } -MaxEvents $MaxEvents -ErrorAction SilentlyContinue
    if ($errors) {
        $errors | Select-Object -Property TimeCreated, Id, @{ Name = &quot;Message&quot;; Expression = { ($_.Message -split &quot;`r?`n&quot;)[0] } } | Format-Table -AutoSize -Wrap
    } else {
        Write-Host &quot;No errors (or log not present).&quot;
    }
}

# TPM readiness matters for self-deploying and pre-provisioning.
Write-Host &quot;== TPM&quot; -ForegroundColor Cyan
Get-Tpm | Select-Object -Property TpmPresent, TpmReady, TpmEnabled, TpmActivated, TpmOwned | Format-List

# A large clock offset breaks TPM attestation and can cause ESP timeouts.
Write-Host &quot;== Clock&quot; -ForegroundColor Cyan
Write-Host &quot;Device UTC time: $((Get-Date).ToUniversalTime().ToString(&apos;yyyy-MM-dd HH:mm:ss&apos;)). Compare with a known-good clock.&quot;

# Archive for Get-AutopilotDiagnostics or a support case.
$cab = Join-Path -Path $OutputFolder -ChildPath &quot;autopilot.cab&quot;
&amp; mdmdiagnosticstool.exe -area &quot;Autopilot;TPM&quot; -cab $cab | Out-Null
Write-Host &quot;Diagnostics archive: $cab&quot;
</code></pre>
<p>Trimmed output from a device that failed at <strong>Securing your hardware</strong>:</p>
<pre><code class="language-text">== Autopilot profile
CloudAssignedTenantDomain : contoso.onmicrosoft.com
IsAutopilotDisabled       : 0
TenantMatched             : 1

== Autopilot events
TimeCreated          Id Meaning
-----------          -- -------
4/8/2026 9:14:02 AM 171 TPM identity confirmation failed (self-deploying)
4/8/2026 9:11:40 AM 153 Profile state changed (ProfileState_Available = profile downloaded)

== TPM
TpmPresent : True
TpmReady   : False
</code></pre>
<p>If the device clock is off by more than a few minutes, Microsoft&apos;s documented fix is to go back to the start of OOBE, connect to the network, and run <code>w32tm /resync /force</code> before trying again.</p>
<h2>The enrollment status page tells you less than you think</h2>
<p>The ESP tracks three phases: <strong>Device preparation</strong> (securing the hardware with TPM attestation, joining Entra ID, enrolling in MDM), <strong>Device setup</strong> (device-targeted items), and <strong>Account setup</strong> (user-targeted items). The phase it&apos;s visually stuck on is not always where the real problem is, partly because of what it <em>doesn&apos;t</em> track. Per Microsoft&apos;s ESP documentation:</p>
<ul><li>Security policies such as device restrictions aren&apos;t tracked at all; they install in the background. The only policies ESP tracks are Microsoft Edge, Assigned Access and Kiosk Browser.</li>
<li>Certificates are tracked only for SCEP profiles, and network connections only for VPN and Wi-Fi profiles.</li>
<li>Device setup tracks device-context apps: per-machine LOB MSI, device-context LOB store apps, Win32 and WinGet apps. Account setup tracks user-assigned apps.</li>
<li>Scripts that run in the user context may not execute during ESP. Microsoft&apos;s workaround is to run them as system.</li>
</ul>
<p>So a device &quot;stuck on apps&quot; is often waiting on exactly one Win32 install, and the diagnostics archive shows which. Two of the most common causes are both documented: mixing LOB (MSI) and Win32 apps during ESP (both use TrustedInstaller, so one fails with <em>Another installation is in progress</em>), and Microsoft 365 Apps deployed with the built-in app type installing while another tracked Win32 app is running. Microsoft recommends packaging Microsoft 365 Apps as Win32 for ESP.</p>
<h2>Timeouts are a policy design problem, not a network problem</h2>
<p>A recurring pattern: a machine fails ESP on a slow connection (a home Wi-Fi network, a hotel, a site with a saturated WAN link) and the assumption is &quot;the network is bad.&quot; Sometimes it is. More often the ESP timeout is too aggressive for the payload being pushed during provisioning, and a machine on a fast connection would have hit the same wall a few minutes later. The numbers to design around:</p>
<ul><li><strong>Show an error when installation takes longer than specified number of minutes</strong> defaults to 60.</li>
<li>Hybrid-joined Autopilot adds 40 minutes on top of whatever you set, to give the connector time to create the device object.</li>
<li><strong>Install Windows quality updates</strong> is on by default for new ESP profiles and, per Microsoft, adds 20 to 40 minutes to provisioning with possible restarts.</li>
<li><strong>Block device use until these required apps are installed</strong> accepts up to 100 selected apps. With <strong>Selected</strong>, apps not on that list aren&apos;t tracked, and in user-driven mode Win32 apps not on the list install after ESP completes.</li>
</ul>
<p>The fix isn&apos;t blaming the network, it&apos;s right-sizing what has to finish before the ESP releases the user to the desktop versus what can land afterwards as a background required app. I move anything that isn&apos;t strictly needed for day-one login off the blocking list and let it install after ESP.</p>
<h2>Stale registrations are the silent repeat offender</h2>
<p>When the same device fails more than once, the first thing I check is its registration history: a reseller&apos;s pre-registration, a previous deployment, a motherboard swap. Microsoft is explicit that large hardware changes such as a motherboard replacement need a new hash, and that a device with a hardware change can show <strong>Fix pending</strong> or <strong>Attention required</strong> in the Autopilot devices list. This read-only Graph script pulls everything Intune knows about a serial number in one go: the Autopilot identity (with its enrollment state, group tag and linked IDs) and any managed device records carrying the same serial:</p>
<pre><code class="language-powershell">&lt;#
.SYNOPSIS
    Shows the Autopilot and Intune records for one or more serial numbers.
.DESCRIPTION
    Read-only. Lists windowsAutopilotDeviceIdentities and managedDevices from
    Microsoft Graph v1.0 and matches them by serial number, so duplicate or
    stale records for the same hardware are visible side by side.
.PARAMETER SerialNumber
    One or more device serial numbers.
.EXAMPLE
    .\Get-AutopilotRecord.ps1 -SerialNumber &quot;&lt;serial-number&gt;&quot;
.NOTES
    Author  : Thomas Lasswell (https://www.techcolumnist.com)
    Version : 1.0 (2026-04-08)
    Requires: Microsoft.Graph.Authentication, Microsoft.Graph.DeviceManagement;
              DeviceManagementServiceConfig.Read.All,
              DeviceManagementManagedDevices.Read.All.
#&gt;

[CmdletBinding()]
param (
    [Parameter(Mandatory = $true)]
    [string[]]$SerialNumber
)

Connect-MgGraph -Scopes &quot;DeviceManagementServiceConfig.Read.All&quot;, &quot;DeviceManagementManagedDevices.Read.All&quot; -NoWelcome

# Autopilot identities (v1.0), following paging.
$uri = &quot;https://graph.microsoft.com/v1.0/deviceManagement/windowsAutopilotDeviceIdentities&quot;
$identities = @()
while ($uri) {
    $page = Invoke-MgGraphRequest -Method GET -Uri $uri
    $identities += $page.value
    $uri = $page.&apos;@odata.nextLink&apos;
}

$managed = Get-MgDeviceManagementManagedDevice -All -Property &quot;id,deviceName,serialNumber,enrolledDateTime,lastSyncDateTime,azureADDeviceId&quot;

foreach ($serial in $SerialNumber) {
    Write-Host &quot;== $serial&quot; -ForegroundColor Cyan
    $identities | Where-Object { $_.serialNumber -eq $serial } | ForEach-Object {
        [PSCustomObject]@{
            Record                = &quot;Autopilot&quot;
            Id                    = $_.id
            GroupTag              = $_.groupTag
            EnrollmentState       = $_.enrollmentState
            LastContacted         = $_.lastContactedDateTime
            ManagedDeviceId       = $_.managedDeviceId
            EntraDeviceId         = $_.azureActiveDirectoryDeviceId
        }
    } | Format-List
    $managed | Where-Object { $_.SerialNumber -eq $serial } | ForEach-Object {
        [PSCustomObject]@{
            Record        = &quot;Intune managed device&quot;
            Id            = $_.Id
            DeviceName    = $_.DeviceName
            Enrolled      = $_.EnrolledDateTime
            LastSync      = $_.LastSyncDateTime
            EntraDeviceId = $_.AzureAdDeviceId
        }
    } | Format-List
}
</code></pre>
<p>Two managed device records for one serial, or an Autopilot identity whose <code>managedDeviceId</code> points at a record that no longer matches, is the &quot;works for other devices, fails for this one&quot; pattern that looks like a hardware fault.</p>
<p>The cleanup order matters, and my earlier advice to just delete the stale Autopilot record was too casual. Microsoft&apos;s deregistration procedure is: delete the device from Intune first, then deregister it from Windows Autopilot (unassigning the user if that option is available), then sync. For Entra joined devices, <em>don&apos;t</em> manually delete the Microsoft Entra device object. The object created at registration is Autopilot&apos;s anchor for group membership and profile targeting, and deleting it can cause the join failures above (<code>0x801C03F3</code> among them). For hybrid-joined devices, delete the computer object from on-premises AD instead so it doesn&apos;t sync back. After that, re-register and redeploy.</p>
<p>It&apos;s a five-minute check against an afternoon of chasing ghosts, and it&apos;s the same lesson as the rest of this post: the evidence is on the device and in Graph, and it&apos;s faster to read it than to reimage and hope.</p>
<h2>References</h2>
<ul><li><a href="https://learn.microsoft.com/en-us/autopilot/troubleshooting-faq">Windows Autopilot troubleshooting FAQ</a></li>
<li><a href="https://learn.microsoft.com/en-us/autopilot/known-issues">Windows Autopilot known issues</a></li>
<li><a href="https://learn.microsoft.com/en-us/intune/device-enrollment/windows/setup-status-page">Set up the Enrollment Status Page</a></li>
<li><a href="https://learn.microsoft.com/en-us/intune/device-management/actions/collect-diagnostics">Device action: Collect diagnostics</a></li>
<li><a href="https://learn.microsoft.com/en-us/windows/client-management/mdm-collect-logs">Collect MDM logs</a></li>
<li><a href="https://learn.microsoft.com/en-us/autopilot/registration-overview">Windows Autopilot registration overview (deregister a device)</a></li>
<li><a href="https://learn.microsoft.com/en-us/graph/api/intune-enrollment-windowsautopilotdeviceidentity-list?view=graph-rest-1.0">List windowsAutopilotDeviceIdentities, Graph v1.0</a></li>
<li><a href="https://www.powershellgallery.com/packages/Get-AutopilotDiagnostics">Get-AutopilotDiagnostics (PowerShell Gallery)</a></li>
</ul>
]]></content:encoded>
      <category>Engineering</category>
    </item>
    <item>
      <title>Intune: Migrating From Group Policy to Cloud-Native Management</title>
      <link>https://www.techcolumnist.com/2026/04/01/intune-migrating-from-group-policy-to-cloud-native-endpoint-management/</link>
      <guid isPermaLink="true">https://www.techcolumnist.com/2026/04/01/intune-migrating-from-group-policy-to-cloud-native-endpoint-management/</guid>
      <pubDate>Wed, 01 Apr 2026 14:00:00 GMT</pubDate>
      <dc:creator>Tom Lasswell</dc:creator>
      <description>Moving a Windows estate from Group Policy to Intune: GPO inventory script, Group Policy analytics, Settings catalog migration, MDMWinsOverGP and conflict checks.</description>
      <content:encoded><![CDATA[<p>Group Policy has been the backbone of Windows management for two decades, and it still works, which is exactly why moving off it is uncomfortable. Nobody migrates away from something broken by comparison; they migrate away from something that quietly does its job while the rest of the environment moves toward devices that never touch the corporate network at all. That was the real driver in the environments I&apos;ve helped move to Intune: not that GPO failed, but that it only reaches machines that can see a domain controller, and an increasing share of a modern fleet never does.</p>
<p>This is the sequence I use now, with the scripts that go with each step.</p>
<h2>Inventory before you touch anything</h2>
<p>The first mistake is starting in Intune and working backward. The right first step is exporting every GPO that&apos;s actually linked, not the ones sitting unlinked in the GPO store from a project three reorganizations ago, and cataloging what each setting does, who it affects, and whether it&apos;s still relevant. Every estate I&apos;ve done this in carried dead weight: settings for a VPN client that was decommissioned, drive mappings to a file server that moved, a login script nobody remembers writing. Migrating dead policy is wasted work. Cutting it first shrinks the real migration to something manageable.</p>
<p>The script below does the mechanical half. It needs the <code>GroupPolicy</code> module (RSAT Group Policy Management Tools) and read access to the domain&apos;s GPOs. For every GPO it writes the XML report that Intune&apos;s Group Policy analytics imports, then builds a CSV with link status, which halves are disabled, last modification time, and whether the XML is over the 4 MB import limit.</p>
<pre><code class="language-powershell">&lt;#
.SYNOPSIS
    Exports every GPO in the domain to XML and builds a link inventory CSV.
.DESCRIPTION
    Uses Get-GPO -All and Get-GPOReport -ReportType Xml to write one XML report
    per GPO (the format Intune Group Policy analytics imports), then reads each
    report&apos;s LinksTo entries to record where the GPO is linked and whether the
    link is enabled. Flags unlinked GPOs, GPOs with all settings disabled, and
    reports over the 4 MB Group Policy analytics import limit.
.PARAMETER OutputFolder
    Folder for the XML reports and gpo-inventory.csv.
.PARAMETER Domain
    FQDN of the domain to read. Defaults to the current user&apos;s domain.
.EXAMPLE
    .\Export-GpoInventory.ps1 -OutputFolder C:\GpoExport
.NOTES
    Author  : Thomas Lasswell (https://www.techcolumnist.com)
    Version : 1.0 (2026-04-01)
    Requires: GroupPolicy module (RSAT), read access to GPOs.
#&gt;

[CmdletBinding()]
param (
    [Parameter(Mandatory = $true)]
    [string]$OutputFolder,

    [Parameter()]
    [string]$Domain = $env:USERDNSDOMAIN
)

Import-Module GroupPolicy
New-Item -Path $OutputFolder -ItemType Directory -Force | Out-Null

$maxBytes = 4MB
$inventory = foreach ($gpo in Get-GPO -All -Domain $Domain) {
    $safeName = $gpo.DisplayName -replace &apos;[\\/:*?&quot;&lt;&gt;|]&apos;, &apos;_&apos;
    # Display names aren&apos;t guaranteed unique, so the GUID keeps each file distinct.
    $xmlPath = Join-Path -Path $OutputFolder -ChildPath &quot;$safeName-$($gpo.Id).xml&quot;

    Get-GPOReport -Guid $gpo.Id -ReportType Xml -Domain $Domain -Path $xmlPath
    [xml]$report = Get-Content -Path $xmlPath -Raw

    # Each LinksTo element is one link (SOMPath is the OU or domain path).
    $links = @($report.GPO.LinksTo)
    $enabledLinks = @($links | Where-Object { $_.Enabled -eq &apos;true&apos; })
    $size = (Get-Item -Path $xmlPath).Length

    $candidate = &apos;Migrate or retire&apos;
    if ($enabledLinks.Count -eq 0) {
        $candidate = &apos;Unlinked: review for deletion&apos;
    } elseif ($gpo.GpoStatus -eq &apos;AllSettingsDisabled&apos;) {
        $candidate = &apos;All settings disabled&apos;
    }

    [PSCustomObject]@{
        Name             = $gpo.DisplayName
        Id               = $gpo.Id
        GpoStatus        = $gpo.GpoStatus
        ModificationTime = $gpo.ModificationTime
        LinkCount        = $links.Count
        EnabledLinks     = $enabledLinks.Count
        LinkedTo         = ($enabledLinks | ForEach-Object { $_.SOMPath }) -join &apos;; &apos;
        ReportKB         = [math]::Round($size / 1KB, 1)
        OverImportLimit  = $size -gt $maxBytes
        Candidate        = $candidate
    }
}

$csvPath = Join-Path -Path $OutputFolder -ChildPath &apos;gpo-inventory.csv&apos;
$inventory | Sort-Object -Property EnabledLinks, Name | Export-Csv -Path $csvPath -NoTypeInformation -Encoding utf8
$inventory | Group-Object -Property Candidate | Select-Object -Property Name, Count | Format-Table -AutoSize
Write-Host &quot;Wrote $(@($inventory).Count) reports and $csvPath&quot;
</code></pre>
<p>Typical console output:</p>
<pre><code class="language-text">Name                          Count
----                          -----
Migrate or retire                58
Unlinked: review for deletion    23
All settings disabled             6

Wrote 87 reports and C:\GpoExport\gpo-inventory.csv
</code></pre>
<p>The <code>LinksTo</code>, <code>SOMPath</code> and <code>Enabled</code> element names come from the GPMC XML report format; open one exported file and check them before you trust the counts. The CSV is where the real work starts: every row in the &quot;Migrate or retire&quot; bucket gets an owner and a decision before anything is built in Intune.</p>
<h2>Let Group Policy analytics do the first pass</h2>
<p>Intune&apos;s Group Policy analytics (<strong>Devices &gt; Manage devices &gt; Group Policy analytics &gt; Import</strong>) takes those XML files and tells you, per GPO, what percentage of settings has an MDM equivalent. Microsoft documents GPMC&apos;s <strong>Save Report</strong> as XML as the export method; if a file produced by <code>Get-GPOReport</code> won&apos;t import, re-save that GPO from GPMC. The rules worth knowing before you start:</p>
<ul><li>A single GPO XML must be under 4 MB and correctly Unicode-encoded, or the import fails. The inventory script flags oversize files.</li>
<li>You can import several files at once. The list view shows <strong>MDM Support</strong> (the percentage), <strong>Unknown Settings</strong> (settings in CSPs the tool can&apos;t parse), and <strong>Targeted in AD</strong>, which says whether the GPO is linked to an OU.</li>
<li>Drilling into a GPO shows each setting&apos;s <strong>CSP Name</strong> and <strong>CSP Mapping</strong>, which is the OMA-URI path. That column is useful even when you don&apos;t use the migration feature, because it hands you the exact path for a custom profile.</li>
<li>The migration readiness report (<strong>Reports &gt; Device management &gt; Group policy analytics</strong>) sorts settings into ready for migration, not supported, and deprecated.</li>
<li>The parser covers the Policy, PassportForWork, BitLocker, Firewall and AppLocker CSPs plus Group Policy Preferences. Known issue: only English-language non-ADMX settings are analyzed correctly, so a GPO authored in another language reports a misleading percentage.</li>
</ul>
<p>The <strong>Migrate</strong> button then builds a Settings catalog profile from the settings you tick. Microsoft calls it best effort, and the details matter: AppLocker and firewall settings can&apos;t be migrated this way (build those in Endpoint security), some older Office and Chrome settings map to a newer equivalent rather than the same setting, and if two imported GPOs set the same setting to different values, the wizard stops with &quot;Conflicts are detected for the following settings&quot; until you pick one.</p>
<h2>Settings catalog versus custom OMA-URI</h2>
<p>Once you know what needs to move, most of it maps onto the Settings catalog, which covers most of what a configuration profile can express. A few things have their own policy types instead: security baselines, Windows Update rings, and BitLocker (under <strong>Endpoint security &gt; Disk encryption</strong>). The catalog covers more ground every release, and I&apos;d always rather use it than hand-roll a custom OMA-URI profile, because Microsoft documents and tests the catalog paths and you&apos;re on your own with a raw CSP. The friction shows up in the long tail: printer deployment logic, application-specific registry keys tied to a piece of line-of-business software, and login scripts doing things GPO could do natively but nobody ever moved off a script. Those need Win32 app deployments, PowerShell scripts or Remediations run through Intune, or in a few cases just get retired because the thing they configured stopped mattering years ago. If a login script really was a repair job, a Remediations detect and remediate pair is usually the better fit; the <a href="https://www.techcolumnist.com/2025/09/10/powershell-intune-remediation-script-for-stuck-bitlocker-encryption/">BitLocker remediation post</a> shows the shape of one.</p>
<h2>Running both in parallel is not optional</h2>
<p>I&apos;ve never seen a clean cutover work, and I stopped trying to force one. Two different parallel models get lumped together here, and it&apos;s worth being precise:</p>
<ul><li><strong>Co-management</strong> is Configuration Manager and Intune managing the same device, with workloads moved one at a time: compliance policies, Windows Update policies, resource access, Endpoint Protection, device configuration, Office Click-to-Run apps and client apps. Each workload has a slider, and pilot collections let you move a subset first. This is the cleanest way to shift ownership if you run ConfigMgr.</li>
<li><strong>Group Policy plus Intune</strong> on hybrid-joined devices has no slider. Both engines apply whatever they&apos;re given, so ownership is something you enforce yourself, setting area by setting area.</li>
</ul>
<p>Either way the order I use is the same: Windows Update first (low risk, easy to verify, and Update rings replace a WSUS GPO cleanly), then device restrictions and security settings, then the application and script-based settings last. Each area gets its own pilot group, verify, expand cycle. After moving an area, forcing a check-in on the pilot group shortens the verify step considerably; the <a href="https://www.techcolumnist.com/2025/10/22/powershell-intune-force-a-compliance-policy-re-evaluation-fleet-wide/">fleet-wide sync script</a> does that through Graph. Rushing this is how you end up with conflicting policies fighting silently, which is worse than either source acting alone, because troubleshooting means checking two consoles instead of one.</p>
<h2>Conflict resolution and the settings you&apos;ll fight over</h2>
<p>The earlier version of this section said Windows generally lets GPO win. That&apos;s not what Microsoft documents. When the same setting is configured by both Group Policy and MDM, and the setting isn&apos;t covered by the <code>MDMWinsOverGP</code> policy, Microsoft&apos;s words are that &quot;there will be a race condition and no guarantee which one wins.&quot; Which is worse than a predictable loser, and it explains the afternoons lost to a setting that applies on one reboot and not the next.</p>
<p><code>MDMWinsOverGP</code> (ControlPolicyConflict in the Policy CSP, Windows 10 1803 and later) changes that for settings in scope. With it set to <code>1</code>, any MDM policy that has an equivalent Group Policy blocks the GP version. I deploy it as a custom OMA-URI setting to the same pilot groups as the first migrated profiles:</p>
<table><thead><tr><th>Field</th><th>Value</th></tr>
</thead><tbody><tr><td>OMA-URI</td><td><code>./Device/Vendor/MSFT/Policy/Config/ControlPolicyConflict/MDMWinsOverGP</code></td></tr>
<tr><td>Data type</td><td>Integer</td></tr>
<tr><td>Value</td><td><code>1</code> (MDM policy is used, GP policy is blocked); default <code>0</code></td></tr>
</tbody></table>
<p>The limits are the important part. It applies only to policies in the Policy CSP. Settings defined in other CSPs (Microsoft&apos;s example is the Defender CSP) aren&apos;t covered, so for those the guidance is simply not to configure the same setting in both places. The MDM Diagnostic report lists which GP settings were blocked because an MDM equivalent exists, which is the quickest way to prove what&apos;s happening on a disputed device.</p>
<p>To gather that evidence in one pass, I run this on the device. It produces the Group Policy result report, the MDM diagnostics archive, and a CSV of the values MDM has delivered under <code>HKLM\SOFTWARE\Microsoft\PolicyManager\current\device</code>, along with whether <code>MDMWinsOverGP</code> has arrived:</p>
<pre><code class="language-powershell">&lt;#
.SYNOPSIS
    Collects Group Policy and MDM policy evidence from one Windows device.
.DESCRIPTION
    Runs gpresult for the computer scope (HTML), runs mdmdiagnosticstool to
    produce the MDM diagnostics archive, lists the MDM-delivered policy values
    under HKLM:\SOFTWARE\Microsoft\PolicyManager\current\device, and reports
    whether ControlPolicyConflict/MDMWinsOverGP is present.
.PARAMETER OutputFolder
    Folder for the reports. Defaults to C:\Users\Public\Documents\PolicyEvidence.
.EXAMPLE
    .\Get-PolicySourceEvidence.ps1
.NOTES
    Author  : Thomas Lasswell (https://www.techcolumnist.com)
    Version : 1.0 (2026-04-01)
    Requires: Elevated PowerShell on the device.
#&gt;

[CmdletBinding()]
param (
    [Parameter()]
    [string]$OutputFolder = &quot;C:\Users\Public\Documents\PolicyEvidence&quot;
)

New-Item -Path $OutputFolder -ItemType Directory -Force | Out-Null

# Group Policy resultant set for the computer.
$gpReport = Join-Path -Path $OutputFolder -ChildPath &quot;gpresult-computer.html&quot;
&amp; gpresult.exe /scope computer /h $gpReport /f | Out-Null

# MDM diagnostics archive (includes MDMDiagHtmlReport.html and the admin event log).
$mdmZip = Join-Path -Path $OutputFolder -ChildPath &quot;MDMDiagReport.zip&quot;
&amp; mdmdiagnosticstool.exe -area &quot;DeviceEnrollment;DeviceProvisioning&quot; -zip $mdmZip | Out-Null

# Values MDM has delivered, one row per area and setting.
$root = &quot;HKLM:\SOFTWARE\Microsoft\PolicyManager\current\device&quot;
$rows = foreach ($area in Get-ChildItem -Path $root -ErrorAction SilentlyContinue) {
    $values = Get-ItemProperty -Path $area.PSPath
    foreach ($property in $values.PSObject.Properties) {
        if ($property.Name -notlike &apos;PS*&apos;) {
            [PSCustomObject]@{
                Area    = $area.PSChildName
                Setting = $property.Name
                Value   = $property.Value
            }
        }
    }
}
$csv = Join-Path -Path $OutputFolder -ChildPath &quot;mdm-policies.csv&quot;
$rows | Export-Csv -Path $csv -NoTypeInformation -Encoding utf8

$conflict = Get-ItemProperty -Path &quot;$root\ControlPolicyConflict&quot; -Name &quot;MDMWinsOverGP&quot; -ErrorAction SilentlyContinue
$mdmWins = if ($conflict) { $conflict.MDMWinsOverGP } else { &quot;not delivered&quot; }

Write-Host &quot;MDM policy values : $(@($rows).Count) in $(@($rows | Select-Object -Property Area -Unique).Count) areas -&gt; $csv&quot;
Write-Host &quot;MDMWinsOverGP     : $mdmWins&quot;
Write-Host &quot;gpresult          : $gpReport&quot;
Write-Host &quot;MDM diagnostics   : $mdmZip&quot;
</code></pre>
<p>Compare the areas in <code>mdm-policies.csv</code> with the computer settings in the gpresult report. Any setting configured in both, outside the Policy CSP, is one you need to remove from one side.</p>
<h2>What made the difference in practice</h2>
<p>The migrations that went smoothly were the ones where I resisted the urge to modernize everything at once. Moving a legacy GPO setting into Intune exactly as-is, verifying it, and only then considering whether a cloud-native equivalent (Windows Update rings instead of a WSUS GPO, for instance) is actually a better fit kept the risk contained to one variable at a time. The migrations that went badly were the ones where &quot;let&apos;s finally fix this while we&apos;re in there&quot; turned one change into three, and when something broke nobody could say which of the three caused it.</p>
<p>The last step is the one people skip: once an area is fully owned by Intune and verified, unlink the GPO rather than leaving it in place &quot;just in case.&quot; A GPO that still applies is a second source of truth, and the whole point was to have one.</p>
<h2>References</h2>
<ul><li><a href="https://learn.microsoft.com/en-us/intune/device-configuration/import-group-policy-analytics">Import and analyze group policies with Group Policy analytics</a></li>
<li><a href="https://learn.microsoft.com/en-us/intune/device-configuration/migrate-group-policy">Migrate imported GPOs to a Settings catalog policy</a></li>
<li><a href="https://learn.microsoft.com/en-us/windows/client-management/mdm/policy-csp-controlpolicyconflict">ControlPolicyConflict Policy CSP (MDMWinsOverGP)</a></li>
<li><a href="https://learn.microsoft.com/en-us/powershell/module/grouppolicy/get-gporeport">Get-GPOReport</a></li>
<li><a href="https://learn.microsoft.com/en-us/intune/configmgr/comanage/workloads">Co-management workloads</a></li>
<li><a href="https://learn.microsoft.com/en-us/windows/client-management/mdm-collect-logs">Collect MDM logs (mdmdiagnosticstool)</a></li>
<li><a href="https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/gpresult">gpresult</a></li>
</ul>
]]></content:encoded>
      <category>Engineering</category>
      <category>Strategy</category>
    </item>
    <item>
      <title>Talos Linux: What Immutable Infrastructure Buys You in Production</title>
      <link>https://www.techcolumnist.com/2026/03/25/talos-linux-what-immutable-infrastructure-actually-buys-you-in-production/</link>
      <guid isPermaLink="true">https://www.techcolumnist.com/2026/03/25/talos-linux-what-immutable-infrastructure-actually-buys-you-in-production/</guid>
      <pubDate>Wed, 25 Mar 2026 14:00:00 GMT</pubDate>
      <dc:creator>Tom Lasswell</dc:creator>
      <description>Where an immutable, API-managed OS pays off under Kubernetes and where it bites: drift, upgrades, try-mode config changes, and debugging without SSH.</description>
      <content:encoded><![CDATA[<p>I&apos;ve spent enough years patching Ubuntu and RHEL nodes under Kubernetes clusters to be skeptical of any pitch that starts with &quot;just don&apos;t SSH into it.&quot; Talos Linux makes that pitch literally: there&apos;s no shell, no SSH daemon, no package manager, not even busybox, and the entire OS is managed through a gRPC API and a declarative machine configuration. After running it under a few production clusters, the skepticism was partly warranted, but the parts of the pitch that hold up are worth more than I expected.</p>
<p>Everything below is written against Talos 1.14.</p>
<h2>What &quot;immutable&quot; actually removes</h2>
<p>Talos&apos; philosophy page is specific about what immutability means. The root filesystem is a read-only SquashFS image, signed and delivered as a single versioned file, and Talos runs from that image even when installed to disk. There are a few controlled writable locations, and the main writable partition is deliberately called <code>EPHEMERAL</code> to remind everyone not to keep anything unique there. PID 1 is Talos&apos; own <code>machined</code>, not systemd. User space is a ground-up rewrite in Go, not a trimmed-down distribution.</p>
<p>The obvious sell is security surface: no shell means no shell-based lateral movement, and no accumulated cruft from an admin who SSH&apos;d in at 2am and left a fix in place that never made it back into config management. That&apos;s real, but the bigger day-to-day win is different. There&apos;s no longer a category of incident where the node&apos;s actual state has quietly drifted from what your infrastructure-as-code says it should be. On a normal distro, drift is a slow leak: a manual <code>apt install</code> here, a kernel parameter tweaked to fix an incident there, none of it ever reverted. On Talos the only way to change a node is to change its machine config through the API, and the running config is a resource you can read back.</p>
<p>That last property is what makes drift <em>checkable</em>, not just unlikely. The running config comes back with <code>talosctl get machineconfig v1alpha1 -o jsonpath=&apos;{.spec}&apos;</code>. If you manage clusters the way Sidero Labs now recommends (a <code>secrets.yaml</code> bundle plus small patch files, with full configs regenerated on demand rather than committed), you can regenerate what each node <em>should</em> be running and compare. This is the script I run weekly and before every upgrade:</p>
<pre><code class="language-python">#!/usr/bin/env python3
&quot;&quot;&quot;
talos_drift_report.py

Compares the machine configuration running on each Talos node with the
configuration regenerated from secrets.yaml + patches (the declared state).
Both sides are parsed and normalized (documents keyed by kind/name, keys
sorted) so comment and ordering noise doesn&apos;t show up as drift.

Exit code 0 when every node matches, 1 when any node has drifted.

Requires: talosctl on PATH, PyYAML (pip install pyyaml).
Output can contain machine config values: keep the report private.
&quot;&quot;&quot;

import argparse
import difflib
import subprocess
import sys
import tempfile
from pathlib import Path

import yaml


def normalize(text):
    &quot;&quot;&quot;Return the config as sorted YAML, one entry per (kind, name) document.&quot;&quot;&quot;
    docs = {}
    for doc in yaml.safe_load_all(text):
        if not doc:
            continue
        key = f&quot;{doc.get(&apos;kind&apos;, &apos;v1alpha1&apos;)}/{doc.get(&apos;name&apos;, &apos;&apos;)}&quot;
        docs[key] = doc
    return yaml.safe_dump(docs, sort_keys=True, default_flow_style=False).splitlines()


def declared_config(args, node_name):
    &quot;&quot;&quot;Regenerate the node&apos;s controlplane config the same way it was created.&quot;&quot;&quot;
    with tempfile.TemporaryDirectory() as tmp:
        out = Path(tmp) / f&quot;{node_name}.yaml&quot;
        cmd = [
            &quot;talosctl&quot;, &quot;gen&quot;, &quot;config&quot;, args.cluster_name, args.endpoint,
            &quot;--with-secrets&quot;, args.secrets,
            &quot;--kubernetes-version&quot;, args.kubernetes_version,
            &quot;--talos-version&quot;, args.talos_contract,
            &quot;--with-docs=false&quot;, &quot;--with-examples=false&quot;,
            &quot;--output-types&quot;, &quot;controlplane&quot;,
            &quot;--output&quot;, str(out),
        ]
        for patch in (&quot;common.yaml&quot;, &quot;controlplane.yaml&quot;, f&quot;nodes/{node_name}.yaml&quot;):
            cmd += [&quot;--config-patch&quot;, f&quot;@{Path(args.patch_dir) / patch}&quot;]
        subprocess.run(cmd, check=True, capture_output=True, text=True)
        return out.read_text()


def live_config(ip):
    &quot;&quot;&quot;Fetch the running config: the .spec of the MachineConfig resource.&quot;&quot;&quot;
    result = subprocess.run(
        [&quot;talosctl&quot;, &quot;--nodes&quot;, ip, &quot;get&quot;, &quot;machineconfig&quot;, &quot;v1alpha1&quot;, &quot;-o&quot;, &quot;jsonpath={.spec}&quot;],
        check=True, capture_output=True, text=True,
    )
    return result.stdout


def main():
    parser = argparse.ArgumentParser(description=&quot;Report drift between declared and running Talos configs.&quot;)
    parser.add_argument(&quot;--cluster-name&quot;, required=True)
    parser.add_argument(&quot;--endpoint&quot;, required=True, help=&quot;Kubernetes endpoint, e.g. https://10.10.20.10:6443&quot;)
    parser.add_argument(&quot;--secrets&quot;, default=&quot;secrets.yaml&quot;)
    parser.add_argument(&quot;--patch-dir&quot;, default=&quot;patches&quot;)
    parser.add_argument(&quot;--kubernetes-version&quot;, required=True, help=&quot;Version the cluster runs now&quot;)
    parser.add_argument(&quot;--talos-contract&quot;, required=True, help=&quot;Talos version contract used at creation, e.g. v1.14&quot;)
    parser.add_argument(&quot;--node&quot;, action=&quot;append&quot;, required=True, metavar=&quot;NAME=IP&quot;,
                        help=&quot;Node name (matching patches/nodes/NAME.yaml) and IP; repeatable&quot;)
    args = parser.parse_args()

    drifted = 0
    for entry in args.node:
        name, ip = entry.split(&quot;=&quot;, 1)
        try:
            declared = normalize(declared_config(args, name))
            live = normalize(live_config(ip))
        except subprocess.CalledProcessError as exc:
            print(f&quot;[{name}] ERROR: {&apos; &apos;.join(exc.cmd[:3])} failed: {exc.stderr.strip()}&quot;)
            drifted += 1
            continue

        diff = list(difflib.unified_diff(declared, live, fromfile=f&quot;{name} declared&quot;, tofile=f&quot;{name} running&quot;, lineterm=&quot;&quot;))
        if diff:
            drifted += 1
            print(f&quot;[{name}] DRIFT ({ip}):&quot;)
            print(&quot;\n&quot;.join(diff))
        else:
            print(f&quot;[{name}] in sync ({ip})&quot;)

    sys.exit(1 if drifted else 0)


if __name__ == &quot;__main__&quot;:
    main()
</code></pre>
<p>Run it with the same inputs you used to build the cluster:</p>
<pre><code class="language-bash">python3 talos_drift_report.py \
    --cluster-name lab \
    --endpoint https://10.10.20.10:6443 \
    --kubernetes-version 1.37.0 \
    --talos-contract v1.14 \
    --node talos-cp1=10.10.20.11 \
    --node talos-cp2=10.10.20.12 \
    --node talos-cp3=10.10.20.13
</code></pre>
<pre><code class="language-text">[talos-cp1] in sync (10.10.20.11)
[talos-cp2] DRIFT (10.10.20.12):
--- talos-cp2 declared
+++ talos-cp2 running
@@ -41,6 +41,8 @@
   kind: KubeNodeConfig
   labels:
     node-role.kubernetes.io/control-plane: &apos;&apos;
+    topology.kubernetes.io/zone: rack-b
[talos-cp3] in sync (10.10.20.13)
</code></pre>
<p>In that example someone ran <code>talosctl patch machineconfig</code> to add a label and never wrote a patch file for it. The fix is a one-line patch in Git, not an archaeology session. Pass the Kubernetes version the cluster runs <em>now</em>: <code>talosctl upgrade-k8s</code> updates component images in the live configs, which is exactly the kind of drift the reproducible-configuration guide warns about if you regenerate with an older version.</p>
<p>The layout and bootstrap flow this assumes are in <a href="https://www.techcolumnist.com/2026/03/18/talos-linux-bootstrapping-a-three-node-kubernetes-cluster-from-bare-metal/">Talos Linux: Bootstrapping a Three-Node Cluster on Bare Metal</a>.</p>
<h2>Where it actually saves operational time</h2>
<p>Patching is the concrete thing people ask about. Upgrading Talos is an API call that hands the node an installer image. The node cordons and drains itself, stops its services, unmounts its filesystems, writes the new image, and sets the bootloader to boot the new version <em>once</em>. Only after it comes back and verifies itself does it make that choice permanent, rejoin, and uncordon. Upgrades use an A-B scheme that keeps the previous kernel and OS image, so a node that fails to boot the new version falls back to the old one on the next reboot. If the node boots fine but your workloads don&apos;t like it, <code>talosctl rollback</code> switches back to the previous image. There&apos;s no apt or yum transaction that can half-complete, and no reboot that comes back into a broken initramfs because a kernel module got orphaned. Talos also refuses to upgrade a control plane node when doing so would cost etcd quorum. I haven&apos;t had a single &quot;the patch broke the box and now I&apos;m on the iDRAC console at midnight&quot; incident on Talos nodes. On traditional distros at similar fleet sizes that was a recurring event, and it&apos;s a category of pager alert that simply stopped.</p>
<p>Configuration changes got safer in a way I didn&apos;t expect. In Talos 1.14, config changes are applied to the running node without a reboot. <code>--mode=try</code> applies a change and reverts it automatically after a timeout (one minute by default) if no further configuration update is applied. That&apos;s the right tool for anything that could cut off your own access, like a network change. I use it as a rehearsal: try the change, check from a second session that the node is still reachable and healthy, let it revert, then apply it for real:</p>
<pre><code class="language-bash"># Rehearse an MTU change; Talos reverts it after 2 minutes
talosctl -n 10.10.20.12 patch machineconfig --mode=try --timeout 2m -p @patches/mtu-9000.yaml

# Preview what the real change will do, then apply it in the default mode
talosctl -n 10.10.20.12 patch machineconfig --dry-run -p @patches/mtu-9000.yaml
talosctl -n 10.10.20.12 patch machineconfig -p @patches/mtu-9000.yaml
</code></pre>
<p>The patch itself is an ordinary document:</p>
<pre><code class="language-yaml">apiVersion: v1alpha1
kind: LinkConfig
name: net0
mtu: 9000
</code></pre>
<p>Talos&apos; <a href="https://docs.siderolabs.com/talos/v1.14/configure-your-talos-cluster/system-configuration/patching">configuration patching docs</a> are explicit that &quot;Talos supports patching multi-document machine configuration,&quot; and list <code>talosctl patch</code> as the way to patch a running node&apos;s configuration, so a per-topic document like this one is a complete patch on its own.</p>
<p>One caveat from the same guide: a few settings are only read when a long-running service starts. etcd settings are the notable one, and Talos deliberately doesn&apos;t restart etcd on a config change, so those still need an explicit <code>talosctl reboot</code>, sequenced like any other control plane maintenance.</p>
<h2>Where the trade-off actually bites</h2>
<p>The cost is that every troubleshooting habit built over a career of <code>ssh</code> and grep stops working. When a node is behaving strangely you don&apos;t tail a log file. You pull what you need through the API, and it pays to have the equivalents memorized before the incident, not during it:</p>
<pre><code class="language-bash"># Text UI with node overview, logs and real-time metrics
talosctl -n 10.10.20.12 dashboard

# Service logs (Talos services), and Kubernetes container logs via the cri namespace
talosctl -n 10.10.20.12 logs kubelet --tail 200
talosctl -n 10.10.20.12 containers --namespace cri
talosctl -n 10.10.20.12 logs --namespace cri &quot;$CONTAINER_ID&quot;

# Kernel log, streaming
talosctl -n 10.10.20.12 dmesg --follow

# Service state, including etcd on control plane nodes
talosctl -n 10.10.20.12 service etcd

# Listening sockets with owning processes (note: -n is --nodes in talosctl, not &quot;numeric&quot;)
talosctl -n 10.10.20.12 netstat --tcp --listening --programs

# Packet capture streamed to your workstation&apos;s tcpdump (physical link name from talosctl get links)
talosctl -n 10.10.20.12 pcap --interface enp1s0 --duration 30s -o - | tcpdump -nn -r -

# Read a file under /proc or /sys
talosctl -n 10.10.20.12 read /proc/cmdline

# Everything above plus COSI resources, bundled for a support case
talosctl -n 10.10.20.12 support --output support-talos-cp2.zip
</code></pre>
<p>If the thing you need to inspect isn&apos;t exposed, you&apos;re stuck, or at least slowed down. I hit exactly this with a NIC firmware quirk that would have been a five-minute <code>ethtool</code> session on a normal box and instead took an afternoon of working around the API&apos;s more limited surface. The surface has grown since then. <code>talosctl get ethernetstatus &lt;link&gt; -o yaml</code> shows ring sizes and offload features in <code>ethtool</code> terms, and the <code>EthernetConfig</code> document can change them declaratively. <code>talosctl debug &lt;image&gt;</code> runs a debug container on the node from an image reference or a local tarball, so you can bring your own tools for the rare case that needs them. Any team adopting Talos still needs to budget real time for this relearning, and needs to accept that a certain class of &quot;let me just poke at it directly&quot; debugging is gone for good, not just discouraged.</p>
<h2>Where I&apos;d actually recommend it</h2>
<p>Talos earns its keep on infrastructure where the node&apos;s only job is to run Kubernetes: bare metal or VM pools dedicated to a cluster, no other tenancy, no other reason for a human to touch the box directly. It&apos;s a worse fit for mixed-use infrastructure where a node also needs to run something outside Kubernetes, or for a team that isn&apos;t already comfortable operating Kubernetes without SSH-shaped crutches. The immutability isn&apos;t a security feature bolted onto a Linux distro. It&apos;s a constraint the whole operating model is built around, and it only pays off when the rest of your operations already fit that constraint.</p>
<h2>The honest tradeoff</h2>
<p>Immutable infrastructure doesn&apos;t remove operational risk, it relocates it: from &quot;did the sysadmin&apos;s manual fix get documented&quot; to &quot;do our secrets bundle and patches in version control actually represent what we want running.&quot; That&apos;s a better place for the risk to live, and the drift report above makes it measurable, but it still needs the same discipline: patch review, staged rollouts, a backed-up <code>secrets.yaml</code>, and someone who owns the machine config the way they used to own the runbook. Talos didn&apos;t make operations easier so much as it made the easy parts easier and the hard parts more honest about being hard.</p>
<h2>References</h2>
<ul><li><a href="https://docs.siderolabs.com/talos/v1.14/learn-more/philosophy">Philosophy</a> (SquashFS root, no shell or SSH, ephemeral partition)</li>
<li><a href="https://docs.siderolabs.com/talos/v1.14/configure-your-talos-cluster/lifecycle-management/upgrading-talos">Upgrading Talos Linux</a> (A-B images, upgrade sequence, rollback, quorum protection)</li>
<li><a href="https://docs.siderolabs.com/talos/v1.14/configure-your-talos-cluster/system-configuration/editing-machine-configuration">Edit Machine Configuration</a> (apply modes, <code>--mode=try</code>, changes that still need a reboot)</li>
<li><a href="https://docs.siderolabs.com/talos/v1.14/configure-your-talos-cluster/system-configuration/reproducible-machine-configuration">Reproducible Machine Configuration</a></li>
<li><a href="https://docs.siderolabs.com/talos/v1.14/configure-your-talos-cluster/system-configuration/patching">Configuration Patches</a></li>
<li><a href="https://docs.siderolabs.com/talos/v1.14/networking/advanced/ethernet-config">Ethernet Configuration</a></li>
<li><a href="https://docs.siderolabs.com/talos/v1.14/reference/cli">talosctl CLI reference</a> (<code>dashboard</code>, <code>logs</code>, <code>dmesg</code>, <code>netstat</code>, <code>pcap</code>, <code>read</code>, <code>debug</code>, <code>support</code>)</li>
</ul>
]]></content:encoded>
      <category>Engineering</category>
      <category>Strategy</category>
    </item>
    <item>
      <title>Talos Linux: Bootstrapping a Three-Node Cluster on Bare Metal</title>
      <link>https://www.techcolumnist.com/2026/03/18/talos-linux-bootstrapping-a-three-node-kubernetes-cluster-from-bare-metal/</link>
      <guid isPermaLink="true">https://www.techcolumnist.com/2026/03/18/talos-linux-bootstrapping-a-three-node-kubernetes-cluster-from-bare-metal/</guid>
      <pubDate>Wed, 18 Mar 2026 14:00:00 GMT</pubDate>
      <dc:creator>Tom Lasswell</dc:creator>
      <description>Bringing up a three-node Talos Kubernetes cluster on bare metal: secrets, per-node patches, a Layer 2 VIP, apply-config, a single bootstrap, and a full script.</description>
      <content:encoded><![CDATA[<p>Bringing up a Kubernetes cluster on three bare-metal boxes used to mean an afternoon of installing a base OS, patching it, disabling swap, installing a container runtime, and then finally running kubeadm and hoping the CNI came up clean. Talos Linux collapses most of that into a single step: there&apos;s no shell to install anything into, because there isn&apos;t a shell. The OS is an immutable, API-managed image whose only job is to run Kubernetes. The first time you bootstrap a cluster this way, the absence of familiar steps is more disorienting than the process itself.</p>
<p>This is the sequence I use for a three-node cluster where every node is both control plane and worker, written against Talos 1.14 (the current release, whose <code>talosctl gen config</code> defaults to Kubernetes 1.37.0). Talos 1.14 generates a multi-document machine config, so the patches below use the new per-topic documents (<code>LinkConfig</code>, <code>Layer2VIPConfig</code>, <code>KubeNodeConfig</code>, <code>UnattendedInstallConfig</code>) rather than the older <code>machine.network</code> and <code>machine.install</code> fields. The addressing plan is a single VLAN, <code>10.10.20.0/24</code>: nodes on <code>.11</code>, <code>.12</code> and <code>.13</code>, a shared API address on <code>.10</code>, gateway on <code>.1</code>.</p>
<h2>Boot into maintenance mode and look before you configure</h2>
<p>Download an ISO from the <a href="https://factory.talos.dev/">Image Factory</a>. If the hardware needs extra drivers or you want system extensions, build a schematic there first, because the installer image you upgrade with later has to carry the same schematic. Boot each machine from it. Until it receives a config, the node runs entirely in RAM in maintenance mode and doesn&apos;t touch its disks. Sidero Labs is explicit that the maintenance API is unauthenticated by design: anyone who can reach port 50000 can push a config with <code>--insecure</code>, so keep that VLAN closed while nodes sit in this state.</p>
<p>Before writing any patches, ask each node what hardware it actually has:</p>
<pre><code class="language-bash">talosctl get disks --insecure --nodes 10.10.20.11
talosctl get links --insecure --nodes 10.10.20.11
</code></pre>
<p>Note each node&apos;s system disk serial and its NIC&apos;s MAC address. I match both by stable properties instead of <code>/dev/sda</code> and <code>enp1s0</code>, because device names on bare metal change when someone adds a disk or a firmware update renumbers PCI devices. The production notes say the same thing about disks: prefer <code>disk.serial</code> or <code>disk.wwid</code> over the <code>/dev/sd*</code> name.</p>
<h2>Secrets first, then patches, never a hand-edited config</h2>
<p>The part I got wrong on my first cluster was treating <code>controlplane.yaml</code> as the thing to keep. Talos&apos; own guidance has since become explicit: generate a secrets bundle once, keep small patch files in version control, and regenerate the full machine configs whenever you need them instead of committing them. The reason is drift. <code>talosctl upgrade-k8s</code> rewrites component image versions in the live config on each node, so a full <code>controlplane.yaml</code> in Git goes stale after the first Kubernetes upgrade, and re-applying it later can quietly downgrade components.</p>
<p>The inputs that make a config reproducible, per the reproducible machine configuration guide, are the <code>secrets.yaml</code> bundle, the patches, the cluster name and endpoint, the Kubernetes version, and a fixed <code>--talos-version</code> contract. <code>secrets.yaml</code> holds the cluster CAs and bootstrap tokens: it belongs in a secrets manager or an encrypted store, not in plain Git.</p>
<p>The repository layout is small:</p>
<pre><code class="language-text">cluster-lab/
  bootstrap-cluster.sh
  secrets.yaml            # not committed in plain text
  patches/
    common.yaml
    controlplane.yaml
    nodes/
      talos-cp1.yaml
      talos-cp2.yaml
      talos-cp3.yaml
</code></pre>
<p><code>patches/common.yaml</code> holds what every node shares, DNS and time:</p>
<pre><code class="language-yaml">apiVersion: v1alpha1
kind: ResolverConfig
nameservers:
  - address: 10.10.20.2
  - address: 10.10.20.3
---
apiVersion: v1alpha1
kind: TimeSyncConfig
ntp:
  servers:
    - ntp1.example.internal
    - ntp2.example.internal
</code></pre>
<p><code>patches/controlplane.yaml</code> holds the two decisions that make this a three-node, all-in-one cluster. The first document is a Layer 2 virtual IP for the Kubernetes API. The control plane nodes elect an owner through etcd and that node answers for <code>10.10.20.10</code> with gratuitous ARP, so there&apos;s no external load balancer to build. The second removes the default <code>NoSchedule</code> taint from control plane nodes so workloads can run on them, using the <code>$patch: delete</code> form from Talos&apos; &quot;workloads on control plane&quot; guide:</p>
<pre><code class="language-yaml">apiVersion: v1alpha1
kind: Layer2VIPConfig
name: 10.10.20.10
link: net0
---
apiVersion: v1alpha1
kind: KubeNodeConfig
taints:
  node-role.kubernetes.io/control-plane:
    $patch: delete
</code></pre>
<p>If you plan to run MetalLB or another load balancer that should use these nodes as backends, also delete the <code>node.kubernetes.io/exclude-from-external-load-balancers</code> label the same way; Talos adds it to control plane nodes by default.</p>
<p>Each node then gets its own patch with a hostname, a link alias pinned to its MAC, a static address, and its install disk selected by serial. This is <code>patches/nodes/talos-cp1.yaml</code>; the other two differ only in the values:</p>
<pre><code class="language-yaml">apiVersion: v1alpha1
kind: HostnameConfig
hostname: talos-cp1
auto: off
---
apiVersion: v1alpha1
kind: LinkAliasConfig
name: net0
selector:
  match: mac(link.permanent_addr) == &quot;3c:ec:ef:10:20:11&quot;
---
apiVersion: v1alpha1
kind: LinkConfig
name: net0
addresses:
  - address: 10.10.20.11/24
routes:
  - gateway: 10.10.20.1
---
apiVersion: v1alpha1
kind: UnattendedInstallConfig
provisioning:
  diskSelector:
    match: disk.serial == &quot;S6XXNX0T100011&quot;
</code></pre>
<p>The alias is what lets <code>controlplane.yaml</code> refer to <code>net0</code> on all three machines even if the kernel names the NIC differently on each: Talos treats a link alias as interchangeable with the physical name anywhere in the network configuration.</p>
<h2>Why the VIP is for Kubernetes only</h2>
<p>Two details from the VIP documentation shape the rest of the process. The VIP only comes alive after etcd is bootstrapped, because the election runs through etcd. And Sidero Labs warns not to use the VIP as an endpoint in <code>talosconfig</code>: if etcd or the API server is what&apos;s broken, the VIP is gone too, and you&apos;d lose the Talos API access you need to fix it. So the Kubernetes endpoint is <code>https://10.10.20.10:6443</code>, while <code>talosctl</code> talks to the three node addresses directly. The failover is quick when the owner shuts down gracefully and takes up to about a minute after a crash or power loss, which is fine for <code>kubectl</code> and irrelevant to pods, since in-cluster clients reach the API server through KubePrism rather than the VIP.</p>
<h2>Apply, then bootstrap exactly once</h2>
<p>Applying configuration is a single <code>talosctl apply-config --insecure</code> per node, pointed at that node&apos;s maintenance-mode address with its generated file. The node validates the config, installs Talos to the selected disk, and reboots into the installed system. If the config is invalid it&apos;s rejected over the API with the reason, which is a better failure mode than a kubeadm join hanging on a firewall rule you forgot. I also run <code>talosctl validate --mode metal --strict</code> on every generated file first, because a typo in a CEL expression is cheaper to find on a laptop.</p>
<p>Applying configuration to all three nodes gets you three machines whose etcd services sit in a join loop, waiting for a peer. That&apos;s where <code>talosctl bootstrap</code> comes in. You run it against one control plane node, once. It tells that node to stop waiting and start etcd as a single-member cluster; the other two join once Kubernetes is up on the first. The docs put it in capitals: run it once, on a single node. Skip it and every etcd service stays stuck; Talos&apos; troubleshooting guide lists &quot;all etcd services are stuck in Pre state&quot; with the fix &quot;make sure that a single member was bootstrapped.&quot; Bootstrap is also the command you&apos;d use later for disaster recovery, with <code>--recover-from</code> pointing at an etcd snapshot, which is one more reason to treat it as a deliberate act rather than something a retry loop fires twice.</p>
<p>Once it settles, <code>talosctl kubeconfig</code> pulls an admin kubeconfig from the node and <code>talosctl health</code> confirms etcd, the control plane components, and node readiness. Nodes show <code>NotReady</code> until the CNI (Flannel by default) is running, then flip to <code>Ready</code>.</p>
<h2>The whole sequence as one script</h2>
<p>This is the script I run from the repository root. It generates the talosconfig and one config per node, validates them, applies them, waits for the installed systems to answer on the authenticated API, bootstraps the first node, and waits for health. It assumes DHCP reservations hand each node the same address in maintenance mode that its <code>LinkConfig</code> makes permanent; if yours differ, keep a second map of maintenance addresses for step 4.</p>
<pre><code class="language-bash">#!/usr/bin/env bash
# bootstrap-cluster.sh
#
# Generates one machine config per node from secrets.yaml + patches, applies
# each config to a node in maintenance mode, bootstraps etcd once, then pulls
# a kubeconfig and waits for the cluster to report healthy.
#
# Needs: talosctl matching the Talos version on the ISO, the patches/ tree
# described above, and DHCP reservations that give each node the same address
# in maintenance mode that its LinkConfig patch assigns permanently.
set -euo pipefail

CLUSTER_NAME=&quot;lab&quot;
ENDPOINT=&quot;https://10.10.20.10:6443&quot;   # the Layer 2 VIP from patches/controlplane.yaml
TALOS_CONTRACT=&quot;v1.14&quot;                 # keep fixed for reproducible configs
K8S_VERSION=&quot;1.37.0&quot;
BOOTSTRAP_NODE=&quot;talos-cp1&quot;
OUT=&quot;_out&quot;                             # generated files: never commit this directory

declare -A NODES=(
    [talos-cp1]=&quot;10.10.20.11&quot;
    [talos-cp2]=&quot;10.10.20.12&quot;
    [talos-cp3]=&quot;10.10.20.13&quot;
)

mkdir -p &quot;$OUT&quot;
export TALOSCONFIG=&quot;$OUT/talosconfig&quot;

# 1. Cluster secrets: generated once, then stored somewhere safer than this repo.
if [[ ! -f secrets.yaml ]]; then
    talosctl gen secrets --output-file secrets.yaml
fi

# 2. The talosctl client config, with every control plane node as an endpoint.
talosctl gen config &quot;$CLUSTER_NAME&quot; &quot;$ENDPOINT&quot; \
    --with-secrets secrets.yaml \
    --talos-version &quot;$TALOS_CONTRACT&quot; \
    --output-types talosconfig \
    --output &quot;$TALOSCONFIG&quot; \
    --force
talosctl config endpoint &quot;${NODES[@]}&quot;

# 3. One controlplane config per node, validated before anything touches hardware.
for name in &quot;${!NODES[@]}&quot;; do
    talosctl gen config &quot;$CLUSTER_NAME&quot; &quot;$ENDPOINT&quot; \
        --with-secrets secrets.yaml \
        --kubernetes-version &quot;$K8S_VERSION&quot; \
        --talos-version &quot;$TALOS_CONTRACT&quot; \
        --config-patch @patches/common.yaml \
        --config-patch @patches/controlplane.yaml \
        --config-patch &quot;@patches/nodes/${name}.yaml&quot; \
        --output-types controlplane \
        --output &quot;$OUT/${name}.yaml&quot; \
        --force
    talosctl validate --config &quot;$OUT/${name}.yaml&quot; --mode metal --strict
done

# 4. Apply over the unauthenticated maintenance API. This is the only --insecure step.
for name in &quot;${!NODES[@]}&quot;; do
    echo &quot;applying $OUT/${name}.yaml to ${NODES[$name]}&quot;
    talosctl apply-config --insecure --nodes &quot;${NODES[$name]}&quot; --file &quot;$OUT/${name}.yaml&quot;
done

# 5. Wait for every node to install, reboot and answer on the authenticated API.
for name in &quot;${!NODES[@]}&quot;; do
    ip=&quot;${NODES[$name]}&quot;
    for attempt in $(seq 1 60); do
        if talosctl --nodes &quot;$ip&quot; version &gt;/dev/null 2&gt;&amp;1; then
            echo &quot;$name ($ip) is up&quot;
            break
        fi
        if [[ $attempt -eq 60 ]]; then
            echo &quot;$name ($ip) did not come up after 10 minutes&quot; &gt;&amp;2
            exit 1
        fi
        sleep 10
    done
done

# 6. Bootstrap etcd exactly once, on exactly one node.
talosctl bootstrap --nodes &quot;${NODES[$BOOTSTRAP_NODE]}&quot;

# 7. Kubeconfig to a separate file, then wait for the whole cluster.
talosctl kubeconfig &quot;$OUT/kubeconfig&quot; --nodes &quot;${NODES[$BOOTSTRAP_NODE]}&quot; --merge=false --force
talosctl health \
    --nodes &quot;${NODES[$BOOTSTRAP_NODE]}&quot; \
    --control-plane-nodes &quot;$(IFS=,; echo &quot;${NODES[*]}&quot;)&quot; \
    --wait-timeout 15m

KUBECONFIG=&quot;$OUT/kubeconfig&quot; kubectl get nodes
</code></pre>
<p>On a healthy run, the last lines look like this:</p>
<pre><code class="language-text">waiting for all k8s nodes to report ready: OK
waiting for all control plane static pods to be running: OK
waiting for all control plane components to be ready: OK
waiting for kube-proxy to report ready: OK
waiting for coredns to report ready: OK
waiting for all k8s nodes to report schedulable: OK
NAME        STATUS   ROLES           AGE   VERSION
talos-cp1   Ready    control-plane   6m    v1.37.0
talos-cp2   Ready    control-plane   5m    v1.37.0
talos-cp3   Ready    control-plane   5m    v1.37.0
</code></pre>
<p>Two follow-ups belong on day one rather than &quot;later.&quot; Take the first etcd snapshot (<code>talosctl -n 10.10.20.11 etcd snapshot db.snapshot</code>) and schedule them; the disaster recovery guide recommends snapshots on a schedule so you can restore the latest one. And unplug the USB stick or unmount the ISO. The production notes suggest doing it before applying configs, so the installer can&apos;t mistake the boot media for the install disk; either way, the nodes should boot from their own disks from here on.</p>
<h2>What immutability actually buys you here</h2>
<p>The payoff isn&apos;t visible on day one. It shows up months later when a node needs to be reimaged after a hardware swap: boot the ISO, update the MAC and disk serial in that node&apos;s patch, regenerate, apply. The process is identical to the first bootstrap, because there was never any drift to reconcile. The inputs are the only source of truth, applied the same way every time. Compare that to a traditional bare-metal node where six months of ad hoc <code>apt install</code> and manual kubelet flag tweaks make a &quot;clean rebuild&quot; a multi-hour archaeology project. Talos trades the flexibility of a general-purpose OS for a much smaller, much more predictable surface, and for a cluster whose only job is running Kubernetes, that trade is an easy one to make.</p>
<p>Once the cluster is up, <a href="https://www.techcolumnist.com/2026/02/04/python-talos-health-checking-a-kubernetes-cluster-from-a-cron-job/">Python: Talos – Health-Checking a Kubernetes Cluster from a Cron Job</a> covers keeping an eye on it, and <a href="https://www.techcolumnist.com/2026/08/26/talos-linux-upgrading-a-cluster-without-a-maintenance-window/">Talos Linux: Upgrading a Cluster Without a Maintenance Window</a> covers the first upgrade.</p>
<h2>References</h2>
<ul><li><a href="https://docs.siderolabs.com/talos/v1.14/getting-started/getting-started">Getting Started</a> (maintenance mode, <code>apply-config --insecure</code>, bootstrap once)</li>
<li><a href="https://docs.siderolabs.com/talos/v1.14/getting-started/prodnotes">Production Clusters</a> (<code>gen secrets</code>, endpoints, install disk selection)</li>
<li><a href="https://docs.siderolabs.com/talos/v1.14/configure-your-talos-cluster/system-configuration/reproducible-machine-configuration">Reproducible Machine Configuration</a></li>
<li><a href="https://docs.siderolabs.com/talos/v1.14/configure-your-talos-cluster/system-configuration/patching">Configuration Patches</a></li>
<li><a href="https://docs.siderolabs.com/talos/v1.14/networking/advanced/vip">Virtual (shared) IP</a></li>
<li><a href="https://docs.siderolabs.com/talos/v1.14/networking/configuration/aliases">Link Aliases</a> and <a href="https://docs.siderolabs.com/talos/v1.14/networking/configuration/static">Static Addressing</a></li>
<li><a href="https://docs.siderolabs.com/talos/v1.14/deploy-and-manage-workloads/workloads-on-controlplane">Enable workloads on your control plane nodes</a></li>
<li><a href="https://docs.siderolabs.com/talos/v1.14/reference/configuration/runtime/unattendedinstallconfig">UnattendedInstallConfig reference</a></li>
<li><a href="https://docs.siderolabs.com/talos/v1.14/reference/cli">talosctl CLI reference</a></li>
<li><a href="https://docs.siderolabs.com/talos/v1.14/troubleshooting/troubleshooting">Troubleshooting</a></li>
</ul>
]]></content:encoded>
      <category>Engineering</category>
    </item>
    <item>
      <title>Node.js: Discovery – Diffing Two Network Scans to Flag New Hosts</title>
      <link>https://www.techcolumnist.com/2026/03/11/node-js-discovery-diffing-two-network-scans-to-flag-new-hosts/</link>
      <guid isPermaLink="true">https://www.techcolumnist.com/2026/03/11/node-js-discovery-diffing-two-network-scans-to-flag-new-hosts/</guid>
      <pubDate>Wed, 11 Mar 2026 14:00:00 GMT</pubDate>
      <dc:creator>Tom Lasswell</dc:creator>
      <description>A dependency-free Node.js script that diffs two nmap XML scans and flags new, missing and moved hosts plus port changes, with an exit code for cron or CI.</description>
      <content:encoded><![CDATA[<p>A single network scan tells you what&apos;s out there today. It&apos;s the second scan, compared against the first, that tells you something changed: a rogue device showed up on a subnet it shouldn&apos;t be on, a host that was supposed to be decommissioned is still answering, or a service quietly opened a new port. I run a scheduled <code>nmap</code> sweep against the office and datacenter subnets and keep the XML output from each run; this script diffs any two of those XML files and reports new hosts, hosts that dropped off, hosts that moved to a different IP, and hosts whose open-port set changed, without pulling in an XML parsing dependency.</p>
<p>It&apos;s the &quot;keep it current&quot; half of the <a href="https://www.techcolumnist.com/2026/07/15/infrastructure-a-discovery-first-approach-to-documenting-an-undocumented-network/">discovery-first approach to documenting an undocumented network</a>: the first scan feeds the inventory, and every scan after that feeds a change report.</p>
<h2>Requirements</h2>
<ul><li>A supported Node.js LTS release (22 or later). No <code>npm install</code>; only the core <code>fs</code> and <code>path</code> modules.</li>
<li>nmap on the scanning host, run as root or Administrator if you want SYN scans (<code>-sS</code>), OS detection, and MAC addresses. Unprivileged nmap falls back to connect scans, and MAC addresses only appear in the XML for targets on the local Ethernet segment.</li>
<li>Two scans taken with the same profile and port range, so the diff is meaningful. Comparing a top-1000-ports scan against a full <code>-p-</code> scan reports a lot of &quot;new ports&quot; that are only new to the scan.</li>
<li>Written authorization for every range in the schedule.</li>
</ul>
<h2>Usage</h2>
<p>Take a baseline and a follow-up scan with an identical command. <code>-oX</code> writes XML; <code>--top-ports 1000</code> keeps a daily /24 run short; <code>--reason</code> records why each port got its state, which helps when a diff looks wrong:</p>
<pre><code class="language-bash">sudo nmap -sS --top-ports 1000 -T4 --reason -oX baseline.xml 10.0.20.0/24
# ...next day...
sudo nmap -sS --top-ports 1000 -T4 --reason -oX current.xml 10.0.20.0/24
</code></pre>
<p>Diff them and print a summary plus the JSON report:</p>
<pre><code class="language-bash">node diff-scans.js baseline.xml current.xml
</code></pre>
<pre><code class="language-text">Baseline: baseline.xml (Tue Mar 10 02:00:01 2026)  Current: current.xml (Wed Mar 11 02:00:01 2026)
New hosts: 1, removed: 1, moved: 1, port changes: 2

  NEW      10.0.20.87   (unknown)            mac 3c:22:fb:4e:91:07  ports: tcp/22, tcp/5900
  REMOVED  10.0.20.31   print-2f.corp.example.internal
  MOVED    b8:ca:3a:6d:12:a5  10.0.20.44 -&gt; 10.0.20.46
  PORTS    10.0.20.10   +tcp/8080 (http-proxy)
  PORTS    10.0.20.12   -tcp/3389 (ms-wbt-server)
</code></pre>
<p>Write the report to a file for a scheduled job, and fail the job when anything new shows up:</p>
<pre><code class="language-bash">node diff-scans.js baseline.xml current.xml --output diff-report.json --fail-on-new
</code></pre>
<p>A nightly wrapper that rotates the files (cron runs it as root):</p>
<pre><code class="language-bash">#!/usr/bin/env bash
# nightly-scan.sh: scan, diff against yesterday, keep a dated copy.
set -euo pipefail
cd /var/lib/netscan
TARGETS=&quot;10.0.20.0/24 10.0.30.0/24&quot;
nmap -sS --top-ports 1000 -T4 --reason -oX current.xml $TARGETS
cp current.xml &quot;archive/scan-$(date +%F).xml&quot;
if [ -f baseline.xml ]; then
    node /opt/netscan/diff-scans.js baseline.xml current.xml --output &quot;archive/diff-$(date +%F).json&quot; --fail-on-new \
        || echo &quot;New hosts detected: see archive/diff-$(date +%F).json&quot; | mail -s &quot;Network scan: new hosts&quot; netops@example.com
fi
mv current.xml baseline.xml
</code></pre>
<h2>Script</h2>
<pre><code class="language-javascript">#!/usr/bin/env node
/**
 * diff-scans.js
 *
 * Diff two nmap XML scans (nmap -oX output) and report hosts that appeared,
 * disappeared, moved to a new IP (same MAC), or changed their open ports.
 *
 * Reads: two nmap XML files given as CLI arguments.
 * Writes: a JSON report to stdout, or to --output if given.
 * Exit code: 2 when --fail-on-new is set and new hosts were found.
 *
 * Dependency-free: it parses the regular subset of nmap&apos;s XML it needs with
 * regular expressions. Point it at your own scan output, not untrusted XML.
 */

&apos;use strict&apos;;

const fs = require(&apos;fs&apos;);
const path = require(&apos;path&apos;);

function parseArgs(argv) {
  const args = { output: null, failOnNew: false, files: [] };
  for (let i = 0; i &lt; argv.length; i += 1) {
    const arg = argv[i];
    if (arg === &apos;--output&apos;) {
      args.output = argv[i + 1];
      i += 1;
    } else if (arg === &apos;--fail-on-new&apos;) {
      args.failOnNew = true;
    } else {
      args.files.push(arg);
    }
  }
  if (args.files.length !== 2) {
    throw new Error(&apos;Usage: diff-scans.js &lt;baseline.xml&gt; &lt;current.xml&gt; [--output report.json] [--fail-on-new]&apos;);
  }
  return args;
}

function decode(value) {
  return value
    .replace(/&amp;lt;/g, &apos;&lt;&apos;).replace(/&amp;gt;/g, &apos;&gt;&apos;)
    .replace(/&amp;quot;/g, &apos;&quot;&apos;).replace(/&amp;apos;/g, &quot;&apos;&quot;).replace(/&amp;amp;/g, &apos;&amp;&apos;);
}

function attr(tag, name) {
  const match = tag.match(new RegExp(`\\s${name}=&quot;([^&quot;]*)&quot;`));
  return match ? decode(match[1]) : null;
}

function parseScan(xml) {
  const runTag = (xml.match(/&lt;nmaprun\s[^&gt;]*&gt;/) || [&apos;&apos;])[0];
  const hosts = new Map();

  // &quot;&lt;host &quot; or &quot;&lt;host&gt;&quot; only: nmap&apos;s DTD also allows &lt;hosthint&gt; elements, which a
  // looser /&lt;host[\s\S]*?&lt;\/host&gt;/ pattern would swallow along with the next host.
  const hostBlocks = xml.match(/&lt;host[\s&gt;][\s\S]*?&lt;\/host&gt;/g) || [];

  for (const block of hostBlocks) {
    const statusTag = (block.match(/&lt;status\s[^&gt;]*&gt;/) || [&apos;&apos;])[0];
    if (attr(statusTag, &apos;state&apos;) !== &apos;up&apos;) {
      continue;
    }

    let ip = null;
    let mac = null;
    let vendor = null;
    for (const addressTag of block.match(/&lt;address\s[^&gt;]*&gt;/g) || []) {
      const type = attr(addressTag, &apos;addrtype&apos;);
      if (type === &apos;mac&apos;) {
        mac = attr(addressTag, &apos;addr&apos;).toLowerCase();
        vendor = attr(addressTag, &apos;vendor&apos;);
      } else if (!ip) {
        ip = attr(addressTag, &apos;addr&apos;);
      }
    }
    if (!ip) {
      continue;
    }

    const hostnameTag = (block.match(/&lt;hostname\s[^&gt;]*&gt;/) || [&apos;&apos;])[0];
    const openPorts = {};
    for (const portBlock of block.match(/&lt;port\s[^&gt;]*&gt;[\s\S]*?&lt;\/port&gt;/g) || []) {
      const portTag = portBlock.match(/&lt;port\s[^&gt;]*&gt;/)[0];
      const stateTag = (portBlock.match(/&lt;state\s[^&gt;]*&gt;/) || [&apos;&apos;])[0];
      const serviceTag = (portBlock.match(/&lt;service\s[^&gt;]*&gt;/) || [&apos;&apos;])[0];
      if (attr(stateTag, &apos;state&apos;) === &apos;open&apos;) {
        openPorts[`${attr(portTag, &apos;protocol&apos;)}/${attr(portTag, &apos;portid&apos;)}`] = attr(serviceTag, &apos;name&apos;) || &apos;&apos;;
      }
    }

    hosts.set(ip, { ip, hostname: attr(hostnameTag, &apos;name&apos;), mac, vendor, openPorts });
  }

  return { started: attr(runTag, &apos;startstr&apos;), hosts };
}

function diffScans(baseline, current) {
  const newHosts = [];
  const removedHosts = [];
  const movedHosts = [];
  const changedPorts = [];

  const baselineByMac = new Map([...baseline.values()].filter((h) =&gt; h.mac).map((h) =&gt; [h.mac, h]));
  const currentByMac = new Map([...current.values()].filter((h) =&gt; h.mac).map((h) =&gt; [h.mac, h]));
  // Current IP -&gt; baseline host for moved hosts, so their ports get compared too.
  const movedFrom = new Map();

  for (const [ip, host] of current) {
    if (baseline.has(ip)) {
      continue;
    }
    const previous = host.mac ? baselineByMac.get(host.mac) : null;
    if (previous &amp;&amp; !current.has(previous.ip)) {
      movedHosts.push({ mac: host.mac, from: previous.ip, to: ip, hostname: host.hostname });
      movedFrom.set(ip, previous);
    } else {
      newHosts.push(host);
    }
  }

  for (const [ip, host] of baseline) {
    if (current.has(ip)) {
      continue;
    }
    const moved = host.mac &amp;&amp; currentByMac.has(host.mac) &amp;&amp; !baseline.has(currentByMac.get(host.mac).ip);
    if (!moved) {
      removedHosts.push(host);
    }
  }

  for (const [ip, currentHost] of current) {
    const baselineHost = baseline.get(ip) || movedFrom.get(ip);
    if (!baselineHost) {
      continue;
    }
    const added = Object.keys(currentHost.openPorts).filter((p) =&gt; !(p in baselineHost.openPorts));
    const dropped = Object.keys(baselineHost.openPorts).filter((p) =&gt; !(p in currentHost.openPorts));
    if (added.length || dropped.length) {
      changedPorts.push({
        ip,
        hostname: currentHost.hostname,
        addedPorts: added.map((p) =&gt; ({ port: p, service: currentHost.openPorts[p] })),
        droppedPorts: dropped.map((p) =&gt; ({ port: p, service: baselineHost.openPorts[p] })),
      });
    }
  }

  return { newHosts, removedHosts, movedHosts, changedPorts };
}

function printSummary(report) {
  const { newHosts, removedHosts, movedHosts, changedPorts } = report;
  console.error(`Baseline: ${report.baseline} (${report.baselineStarted})  Current: ${report.current} (${report.currentStarted})`);
  console.error(`New hosts: ${newHosts.length}, removed: ${removedHosts.length}, moved: ${movedHosts.length}, port changes: ${changedPorts.length}\n`);
  for (const h of newHosts) {
    const mac = h.mac ? `mac ${h.mac}` : &apos;&apos;;
    console.error(`  NEW      ${h.ip.padEnd(12)} ${(h.hostname || &apos;(unknown)&apos;).padEnd(20)} ${mac}  ports: ${Object.keys(h.openPorts).join(&apos;, &apos;) || &apos;none open&apos;}`);
  }
  for (const h of removedHosts) {
    console.error(`  REMOVED  ${h.ip.padEnd(12)} ${h.hostname || &apos;&apos;}`);
  }
  for (const m of movedHosts) {
    console.error(`  MOVED    ${m.mac}  ${m.from} -&gt; ${m.to}`);
  }
  for (const c of changedPorts) {
    const parts = [
      ...c.addedPorts.map((p) =&gt; `+${p.port} (${p.service})`),
      ...c.droppedPorts.map((p) =&gt; `-${p.port} (${p.service})`),
    ];
    console.error(`  PORTS    ${c.ip.padEnd(12)} ${parts.join(&apos; &apos;)}`);
  }
}

function main() {
  const args = parseArgs(process.argv.slice(2));
  const [baselinePath, currentPath] = args.files;

  const baseline = parseScan(fs.readFileSync(path.resolve(baselinePath), &apos;utf8&apos;));
  const current = parseScan(fs.readFileSync(path.resolve(currentPath), &apos;utf8&apos;));
  const diff = diffScans(baseline.hosts, current.hosts);

  const report = {
    baseline: baselinePath,
    baselineStarted: baseline.started,
    current: currentPath,
    currentStarted: current.started,
    summary: {
      newHosts: diff.newHosts.length,
      removedHosts: diff.removedHosts.length,
      movedHosts: diff.movedHosts.length,
      hostsWithPortChanges: diff.changedPorts.length,
    },
    ...diff,
  };

  printSummary(report);
  const output = JSON.stringify(report, null, 2);
  if (args.output) {
    fs.writeFileSync(args.output, output, &apos;utf8&apos;);
    console.error(`\nReport written to ${args.output}`);
  } else {
    console.log(output);
  }

  if (args.failOnNew &amp;&amp; diff.newHosts.length &gt; 0) {
    process.exitCode = 2;
  }
}

main();
</code></pre>
<h2>Notes</h2>
<ul><li><strong>Bug fixed from the first version: <code>&lt;hosthint&gt;</code>.</strong> nmap&apos;s DTD allows <code>&lt;hosthint&gt;</code> elements (a status, address and hostnames block) as siblings of <code>&lt;host&gt;</code>. The original <code>/&lt;host[\s\S]*?&lt;\/host&gt;/</code> pattern matched <code>&lt;hosthint&gt;</code> too, so one match could span a hint and the following real host and attribute the wrong ports to an address. The pattern now requires whitespace or <code>&gt;</code> after <code>host</code>.</li>
<li><strong>Only up hosts count.</strong> The DTD defines host states <code>up</code>, <code>down</code>, <code>unknown</code> and <code>skipped</code>, and the first version counted any <code>&lt;host&gt;</code> element as present. The script now checks <code>&lt;status state=&quot;up&quot;&gt;</code> before counting a host.</li>
<li><strong>MAC-based &quot;moved&quot;.</strong> On DHCP subnets a device that got a new lease shows up as one &quot;new&quot; and one &quot;removed&quot; host. When both scans include the MAC (root scan, local segment), the script pairs them, reports a move instead, and compares the moved host&apos;s ports against its old address. Across routers there&apos;s no MAC in the XML and the pairing doesn&apos;t happen.</li>
<li><strong>IPv6 works</strong> as long as both scans used <code>-6</code> against the same targets; the first non-MAC <code>&lt;address&gt;</code> is used as the key.</li>
<li><strong>&quot;Removed&quot; is not &quot;gone&quot;.</strong> A host missing from the current scan may just not have answered discovery probes that night. <code>-T4</code> already allows up to 6 retransmissions (<code>--max-retries 6</code>); if a host flaps every run, check it for power management or a host firewall that drops discovery probes before assuming it was decommissioned.</li>
<li><strong>Parsing trade-off.</strong> Regex parsing keeps this dependency-free and works on nmap&apos;s own consistently formatted output. It is not a general XML parser; if you already have a dependency budget, an XML library is the more robust choice. The discovery-first essay uses Python&apos;s <code>xml.etree.ElementTree</code> for the same file.</li>
</ul>
<h2>References</h2>
<ul><li><a href="https://nmap.org/book/man-output.html">Nmap output options (<code>-oX</code>, <code>-oA</code>)</a></li>
<li><a href="https://svn.nmap.org/nmap/docs/nmap.dtd">Nmap XML DTD (<code>host</code>, <code>hosthint</code>, <code>status</code>, <code>address</code>, <code>port</code>, <code>service</code>)</a></li>
<li><a href="https://nmap.org/book/man-performance.html">Nmap timing and performance (<code>-T4</code>, <code>--max-retries</code>)</a></li>
<li><a href="https://nmap.org/book/man-port-scanning-techniques.html">Nmap port scanning techniques (<code>-sS</code> privileges, <code>-sT</code> fallback)</a></li>
<li><a href="https://nmap.org/book/man-host-discovery.html">Nmap host discovery (ARP on local Ethernet)</a></li>
<li><a href="https://nodejs.org/api/fs.html#fsreadfilesyncpath-options">Node.js <code>fs.readFileSync</code></a></li>
</ul>
]]></content:encoded>
      <category>Scripts</category>
      <category>Engineering</category>
    </item>
    <item>
      <title>Node.js: gcloud – Rotating Service Account Keys Before They Expire</title>
      <link>https://www.techcolumnist.com/2026/03/04/node-js-gcloud-rotating-service-account-keys-before-they-expire/</link>
      <guid isPermaLink="true">https://www.techcolumnist.com/2026/03/04/node-js-gcloud-rotating-service-account-keys-before-they-expire/</guid>
      <pubDate>Wed, 04 Mar 2026 14:00:00 GMT</pubDate>
      <dc:creator>Tom Lasswell</dc:creator>
      <description>A Node.js script that finds aging Google Cloud service account keys, mints one replacement, and disables the old keys once it is deployed.</description>
      <content:encoded><![CDATA[<p>Service account keys are the credential everyone forgets about until a security review flags one that is four years old and still active. By default a user-managed key never expires, and once the JSON file is downloaded Google can&apos;t give it to you again, so the only copy lives wherever someone saved it. This script follows Google&apos;s rotation order in two runs. The first finds keys past an age threshold on a service account, mints one replacement, and hands it off through a local file or Secret Manager. Once the new key is deployed wherever the old one was used, a second run with <code>--disable-old</code> disables rather than deletes the old keys, so anything still referencing them fails loudly, with a one-command rollback.</p>
<h2>Before you rotate: can you delete the key instead?</h2>
<p>Google&apos;s key-management guidance is to pick a more secure alternative &quot;whenever possible,&quot; and it lists them: an attached service account for code on Compute Engine, GKE, Cloud Run, and similar; Workload Identity Federation for workloads outside Google Cloud (GitHub Actions, AWS, Azure, on-premises OIDC or SAML providers). Rotation is the fallback for the keys you genuinely can&apos;t remove, such as a third-party SaaS tool that only accepts a JSON key.</p>
<p>Two organization policy facts change how this script behaves in practice:</p>
<ul><li>Organizations created on or after May 3, 2024 enforce <code>iam.managed.disableServiceAccountKeyCreation</code> by default (the older equivalent is <code>iam.disableServiceAccountKeyCreation</code>). In those orgs <code>keys.create</code> fails until the project is exempted, which is the point: every key becomes a conscious exception.</li>
<li><code>iam.serviceAccountKeyExpiryHours</code> makes new keys expire automatically. It accepts only allowed values: <code>1h</code>, <code>8h</code>, <code>24h</code>, <code>168h</code>, <code>336h</code>, <code>720h</code>, <code>1440h</code>, <code>2160h</code> (90 days), and applies only to keys created after the policy is set. Google recommends expiry for temporary access rather than production workloads, but a 90-day cap is a good backstop under a rotation job like this one.</li>
</ul>
<p>A GitHub Actions deployment, for example, doesn&apos;t need a key at all. The Workload Identity Federation setup from Google&apos;s deployment-pipeline guide replaces it (the attribute condition is mandatory for GitHub, to stop tokens from other GitHub organizations being accepted):</p>
<pre><code class="language-bash">gcloud iam workload-identity-pools create github \
  --project=my-project --location=global --display-name=&quot;GitHub Actions&quot;

gcloud iam workload-identity-pools providers create-oidc my-org \
  --project=my-project --location=global --workload-identity-pool=github \
  --issuer-uri=&quot;https://token.actions.githubusercontent.com/&quot; \
  --attribute-mapping=&quot;google.subject=assertion.sub,attribute.repository=assertion.repository,attribute.repository_owner=assertion.repository_owner&quot; \
  --attribute-condition=&quot;assertion.repository_owner==&apos;my-org&apos;&quot;

gcloud iam service-accounts add-iam-policy-binding deployer@my-project.iam.gserviceaccount.com \
  --role=roles/iam.workloadIdentityUser \
  --member=&quot;principalSet://iam.googleapis.com/projects/123456789012/locations/global/workloadIdentityPools/github/attribute.repository/my-org/my-repo&quot;
</code></pre>
<h2>Requirements</h2>
<ul><li>A supported Node.js LTS release (22 or later) and the <code>googleapis</code> package (<code>npm install googleapis</code>).</li>
<li>Application Default Credentials: <code>gcloud auth application-default login</code> interactively, or, on a schedule, the service account a Cloud Run job runs as (Cloud Scheduler only triggers the job; it doesn&apos;t lend the script an identity).</li>
<li><code>roles/iam.serviceAccountKeyAdmin</code> on the project (or on the service account). It covers listing, creating, disabling, and deleting user-managed keys.</li>
<li>For <code>--secret</code>: an existing secret in the same project and <code>roles/secretmanager.secretVersionAdder</code> on it. Create the secret once with <code>gcloud secrets create sa-reporting-key --replication-policy=automatic --project=my-project</code>. Whoever collects the key from it needs <code>roles/secretmanager.secretAccessor</code> on that secret.</li>
<li>If the organization enforces <code>iam.managed.disableServiceAccountKeyCreation</code> or <code>iam.disableServiceAccountKeyCreation</code>, an exemption for this project, or the create call is refused.</li>
</ul>
<h2>Parameters</h2>
<table><thead><tr><th>Parameter</th><th>Required</th><th>Description</th></tr>
</thead><tbody><tr><td><code>--project</code></td><td>Yes</td><td>Project ID that owns the service account.</td></tr>
<tr><td><code>--service-account</code></td><td>Yes</td><td>Service account email.</td></tr>
<tr><td><code>--max-age-days</code></td><td>No</td><td>Keys older than this (by <code>validAfterTime</code>) are rotated. Default 90.</td></tr>
<tr><td><code>--secret</code></td><td>One of</td><td>Secret ID in the same project; the new key is added as a new version.</td></tr>
<tr><td><code>--output</code></td><td>One of</td><td>Local path for the new key file, written with mode <code>0600</code> (also applied to an existing file).</td></tr>
<tr><td><code>--disable-old</code></td><td>No</td><td>Second run: create nothing, disable the keys over the threshold. Refuses if no enabled key within the threshold is left.</td></tr>
<tr><td><code>--dry-run</code></td><td>No</td><td>Report what would happen; creates and disables nothing.</td></tr>
</tbody></table>
<h2>Usage</h2>
<p>See what would be rotated without making changes:</p>
<pre><code class="language-bash">node rotate-sa-keys.js --project my-project \
  --service-account reporting@my-project.iam.gserviceaccount.com \
  --max-age-days 90 --dry-run
</code></pre>
<p>Mint a replacement for keys older than 90 days and store it as a Secret Manager version:</p>
<pre><code class="language-bash">node rotate-sa-keys.js --project my-project \
  --service-account reporting@my-project.iam.gserviceaccount.com \
  --max-age-days 90 --secret sa-reporting-key
</code></pre>
<p>Sample output (illustrative):</p>
<pre><code class="language-text">Found 3 user-managed key(s) on reporting@my-project.iam.gserviceaccount.com
Key 3f9a1c2b... is 142 days old, exceeds 90-day threshold
Key 77d0e4aa... is already disabled (SERVICE_ACCOUNT_KEY_DISABLE_REASON_USER_INITIATED)
Key ef567890... is 12 days old, within threshold
Created key 0b1c2d3e..., stored in Secret Manager version projects/123456789012/secrets/sa-reporting-key/versions/4
Old key(s) left enabled. Deploy the new key, then rerun with --disable-old.
</code></pre>
<p>Google doesn&apos;t recommend Secret Manager as the place a workload reads its service account key from: anything that can authenticate to Secret Manager already has an identity and should use it directly. Treat the secret as a hand-off point for the key&apos;s real destination, the out-of-cloud system that can&apos;t use an attached service account or federation. The person updating that system collects it once:</p>
<pre><code class="language-bash">gcloud secrets versions access latest --secret=sa-reporting-key --project=my-project &gt; new-key.json
</code></pre>
<p>Once the new key is in place there, disable the old ones:</p>
<pre><code class="language-bash">node rotate-sa-keys.js --project my-project \
  --service-account reporting@my-project.iam.gserviceaccount.com \
  --max-age-days 90 --disable-old
</code></pre>
<pre><code class="language-text">Found 4 user-managed key(s) on reporting@my-project.iam.gserviceaccount.com
Key 3f9a1c2b... is 142 days old, exceeds 90-day threshold
Key 77d0e4aa... is already disabled (SERVICE_ACCOUNT_KEY_DISABLE_REASON_USER_INITIATED)
Key ef567890... is 13 days old, within threshold
Key 0b1c2d3e... is 1 days old, within threshold
Disabled old key 3f9a1c2b...
</code></pre>
<h2>Script</h2>
<pre><code class="language-javascript">#!/usr/bin/env node
/**
 * rotate-sa-keys.js
 *
 * Finds user-managed Google Cloud service account keys older than a threshold
 * and creates one replacement key. After the replacement is deployed, a second
 * run with --disable-old disables (not deletes) the old ones so anything still
 * depending on them fails loudly and can be rolled back.
 *
 * Reads:  service account key metadata via the IAM API (iam.googleapis.com).
 * Writes: the new key either as a new Secret Manager version (--secret) or to
 *         a local file with mode 0600 (--output); with --disable-old, disables
 *         old keys in place.
 *
 * Usage:
 *   node rotate-sa-keys.js --project &lt;project-id&gt; \
 *     --service-account &lt;sa&gt;@&lt;project-id&gt;.iam.gserviceaccount.com \
 *     --max-age-days 90 (--secret &lt;secret-id&gt; | --output ./new-key.json | --disable-old) [--dry-run]
 */

const fs = require(&apos;fs&apos;);
const { google } = require(&apos;googleapis&apos;);

const MAX_KEYS_PER_ACCOUNT = 10;
const DAY_MS = 24 * 60 * 60 * 1000;

function parseArgs(argv) {
    const args = {
        project: null,
        serviceAccount: null,
        maxAgeDays: 90,
        output: null,
        secret: null,
        disableOld: false,
        dryRun: false,
    };

    for (let i = 0; i &lt; argv.length; i += 1) {
        switch (argv[i]) {
            case &apos;--project&apos;:
                args.project = argv[++i];
                break;
            case &apos;--service-account&apos;:
                args.serviceAccount = argv[++i];
                break;
            case &apos;--max-age-days&apos;:
                args.maxAgeDays = Number(argv[++i]);
                break;
            case &apos;--output&apos;:
                args.output = argv[++i];
                break;
            case &apos;--secret&apos;:
                args.secret = argv[++i];
                break;
            case &apos;--disable-old&apos;:
                args.disableOld = true;
                break;
            case &apos;--dry-run&apos;:
                args.dryRun = true;
                break;
            default:
                throw new Error(`Unknown argument: ${argv[i]}`);
        }
    }

    if (!args.project || !args.serviceAccount) {
        throw new Error(&apos;--project and --service-account are required&apos;);
    }
    if (!Number.isFinite(args.maxAgeDays) || args.maxAgeDays &lt; 1) {
        throw new Error(&apos;--max-age-days must be a positive number&apos;);
    }
    if (args.disableOld &amp;&amp; (args.output || args.secret)) {
        throw new Error(&apos;--disable-old creates no key; drop --secret/--output&apos;);
    }
    if (!args.dryRun &amp;&amp; !args.disableOld &amp;&amp; !args.output === !args.secret) {
        throw new Error(&apos;Specify exactly one of --secret or --output&apos;);
    }

    return args;
}

function ageInDays(validAfterTime) {
    return Math.floor((Date.now() - new Date(validAfterTime).getTime()) / DAY_MS);
}

async function storeKey(args, auth, privateKeyData) {
    if (args.secret) {
        // privateKeyData is already base64, which is what SecretPayload.data expects.
        const secretManager = google.secretmanager({ version: &apos;v1&apos;, auth });
        const { data } = await secretManager.projects.secrets.addVersion({
            parent: `projects/${args.project}/secrets/${args.secret}`,
            requestBody: { payload: { data: privateKeyData } },
        });
        return `Secret Manager version ${data.name}`;
    }

    const json = Buffer.from(privateKeyData, &apos;base64&apos;).toString(&apos;utf8&apos;);
    const fd = fs.openSync(args.output, &apos;w&apos;, 0o600);
    try {
        fs.fchmodSync(fd, 0o600); // open&apos;s mode only applies when it creates the file
        fs.writeSync(fd, json);
    } finally {
        fs.closeSync(fd);
    }
    return args.output;
}

async function main() {
    const args = parseArgs(process.argv.slice(2));
    const auth = new google.auth.GoogleAuth({
        scopes: [&apos;https://www.googleapis.com/auth/cloud-platform&apos;],
    });
    const iam = google.iam({ version: &apos;v1&apos;, auth });
    const accountName = `projects/${args.project}/serviceAccounts/${args.serviceAccount}`;

    const { data } = await iam.projects.serviceAccounts.keys.list({
        name: accountName,
        keyTypes: [&apos;USER_MANAGED&apos;],
    });
    const keys = data.keys || [];
    console.log(`Found ${keys.length} user-managed key(s) on ${args.serviceAccount}`);

    const expired = [];
    let current = 0;
    for (const key of keys) {
        const keyId = key.name.split(&apos;/&apos;).pop();
        const days = ageInDays(key.validAfterTime);
        const expiry = key.validBeforeTime &amp;&amp; !key.validBeforeTime.startsWith(&apos;9999&apos;)
            ? `, expires ${key.validBeforeTime}`
            : &apos;&apos;;

        if (key.disabled) {
            console.log(`Key ${keyId.slice(0, 8)}... is already disabled (${key.disableReason || &apos;no reason&apos;})`);
        } else if (days &gt; args.maxAgeDays) {
            console.log(`Key ${keyId.slice(0, 8)}... is ${days} days old${expiry}, exceeds ${args.maxAgeDays}-day threshold`);
            expired.push(key);
        } else {
            console.log(`Key ${keyId.slice(0, 8)}... is ${days} days old${expiry}, within threshold`);
            current += 1;
        }
    }

    if (expired.length === 0) {
        console.log(&apos;No keys required rotation.&apos;);
        return;
    }

    if (args.disableOld) {
        if (current === 0) {
            throw new Error(&apos;No enabled key within the threshold; run without --disable-old to create one first&apos;);
        }
        if (args.dryRun) {
            console.log(`Dry run: would disable ${expired.length} key(s).`);
            return;
        }
        for (const key of expired) {
            await iam.projects.serviceAccounts.keys.disable({ name: key.name });
            console.log(`Disabled old key ${key.name.split(&apos;/&apos;).pop().slice(0, 8)}...`);
        }
        return;
    }

    if (keys.length &gt;= MAX_KEYS_PER_ACCOUNT) {
        throw new Error(`Account already has ${keys.length} keys (limit ${MAX_KEYS_PER_ACCOUNT}); delete disabled keys first`);
    }
    if (args.dryRun) {
        console.log(&apos;Dry run: would create 1 replacement key.&apos;);
        return;
    }

    const created = await iam.projects.serviceAccounts.keys.create({
        name: accountName,
        requestBody: { privateKeyType: &apos;TYPE_GOOGLE_CREDENTIALS_FILE&apos; },
    });
    const newKeyId = created.data.name.split(&apos;/&apos;).pop();
    const location = await storeKey(args, auth, created.data.privateKeyData);
    console.log(`Created key ${newKeyId.slice(0, 8)}..., stored in ${location}`);
    console.log(&apos;Old key(s) left enabled. Deploy the new key, then rerun with --disable-old.&apos;);
}

main().catch((error) =&gt; {
    console.error(error.message);
    process.exitCode = 1;
});
</code></pre>
<h2>Notes</h2>
<ul><li>Before disabling anything, check whether the old key is still in use. Activity Analyzer reports the last authentication per key: <code>gcloud policy-intelligence query-activity --activity-type=serviceAccountKeyLastAuthentication --project=my-project --query-filter=&apos;activities.full_resource_name=&quot;//iam.googleapis.com/projects/my-project/serviceAccounts/reporting@my-project.iam.gserviceaccount.com/keys/KEY_ID&quot;&apos;</code>. It needs <code>roles/policyanalyzer.activityAnalysisViewer</code>, and recent events may not be included yet; check the <code>observationPeriod</code> in the result.</li>
<li>Disable, wait, then delete. A disabled key can be re-enabled if something breaks (<code>gcloud iam service-accounts keys enable KEY_ID --iam-account=reporting@my-project.iam.gserviceaccount.com</code>). I run a separate cleanup a week later with <code>gcloud iam service-accounts keys delete KEY_ID --iam-account=...</code>, which is permanent. The API doesn&apos;t record when a key was disabled, so the cleanup works from a list, not a timestamp.</li>
<li>Disabling a key does not revoke short-lived access tokens already minted from it. If the key leaked, the docs say to disable or delete the service account itself (or at least treat those tokens as live until they expire).</li>
<li>One replacement per run, regardless of how many expired keys the account has. The goal is a single current credential. Nothing is disabled in that run: Google&apos;s order is create, replace in every application, then disable and monitor, so <code>--disable-old</code> is a separate step you take after the deploy.</li>
<li>A service account can hold at most 10 keys. The script refuses to create an eleventh; delete disabled keys first.</li>
<li>Keys disabled by Google carry a <code>disableReason</code> of <code>SERVICE_ACCOUNT_KEY_DISABLE_REASON_EXPOSED</code> or <code>..._COMPROMISE_DETECTED</code>. Google scans public repositories for leaked keys, and since June 16, 2024 it disables exposed keys by default unless <code>iam.serviceAccountKeyExposureResponse</code> has been set to <code>WAIT_FOR_ABUSE</code> (Google recommends <code>DISABLE_KEY</code>). Treat those as incidents, not rotation candidates.</li>
<li>The script lists <code>USER_MANAGED</code> keys only. <code>SYSTEM_MANAGED</code> keys are rotated by Google and can&apos;t be downloaded.</li>
<li><code>privateKeyData</code> comes back base64-encoded. Secret Manager&apos;s <code>payload.data</code> also expects base64, so the script passes it through unchanged; only the file path decodes it.</li>
</ul>
<h2>References</h2>
<ul><li><a href="https://docs.cloud.google.com/iam/docs/best-practices-for-managing-service-account-keys">Best practices for managing service account keys</a></li>
<li><a href="https://docs.cloud.google.com/iam/docs/keys-create-delete">Create and delete service account keys</a></li>
<li><a href="https://docs.cloud.google.com/iam/docs/keys-disable-enable">Disable and enable service account keys</a></li>
<li><a href="https://docs.cloud.google.com/organization-policy/restrict-service-accounts">Restrict service account usage (key constraints and expiry values)</a></li>
<li><a href="https://docs.cloud.google.com/resource-manager/docs/secure-by-default-organizations">Secure-by-default organization policies</a></li>
<li><a href="https://docs.cloud.google.com/iam/docs/workload-identity-federation-with-deployment-pipelines">Workload Identity Federation with deployment pipelines</a></li>
<li><a href="https://docs.cloud.google.com/policy-intelligence/docs/activity-analyzer-service-account-authentication">Activity Analyzer: service account key authentication</a></li>
<li><a href="https://cloud.google.com/blog/products/identity-security/automatically-disabling-leaked-service-account-keys-what-you-need-to-know">Automatically disabling leaked service account keys (Google Cloud blog)</a></li>
<li><a href="https://docs.cloud.google.com/secret-manager/docs/access-control">Secret Manager access control</a></li>
<li><a href="https://iam.googleapis.com/$discovery/rest?version=v1">IAM API discovery document (ServiceAccountKey fields, keys methods)</a></li>
</ul>
]]></content:encoded>
      <category>Scripts</category>
      <category>Engineering</category>
    </item>
    <item>
      <title>Node.js: Data Warehouse – Streaming ETL Rows Without Buffering Them</title>
      <link>https://www.techcolumnist.com/2026/02/25/node-js-data-warehouse-streaming-etl-rows-without-loading-them-all-in-memory/</link>
      <guid isPermaLink="true">https://www.techcolumnist.com/2026/02/25/node-js-data-warehouse-streaming-etl-rows-without-loading-them-all-in-memory/</guid>
      <pubDate>Wed, 25 Feb 2026 14:00:00 GMT</pubDate>
      <dc:creator>Tom Lasswell</dc:creator>
      <description>A Node.js script that streams Postgres rows through a cursor, a transform and COPY FROM STDIN with backpressure, so memory tracks batch size, not table size.</description>
      <content:encoded><![CDATA[<p>The failure mode I keep seeing in hand-rolled ETL jobs is the same one every time: <code>SELECT * FROM source_table</code>, load the whole result set into an array, transform it in memory, then loop over the array and insert rows one at a time into the destination. It works fine in development against a few thousand rows and falls over in production, either by exhausting the process&apos;s memory or by taking so long on row-by-row inserts that the job never finishes inside its window. Node&apos;s streams solve both problems if you actually use them as streams rather than as a <code>.on(&apos;data&apos;)</code> handler that pushes into an array.</p>
<p>This script pulls rows from a source Postgres table through a cursor, transforms them one at a time, and bulk-loads them into a destination Postgres table (a staging table in a warehouse, say) with <code>COPY ... FROM STDIN</code>. Three details make it correct rather than just fast:</p>
<ul><li><strong>Backpressure end to end.</strong> <code>pipeline()</code> from <code>node:stream/promises</code> connects the cursor, the transform, and the <code>COPY</code> stream. When <code>COPY</code> falls behind, the cursor stops fetching.</li>
<li><strong>Raw text in, raw text out.</strong> By default <code>pg</code> turns <code>timestamptz</code> into a JavaScript <code>Date</code> and <code>json</code>/<code>jsonb</code> into an object. Written back with <code>String(value)</code>, a date becomes <code>Tue Feb 24 2026 ...</code> and an object becomes <code>[object Object]</code>. That is an easy bug to ship, because nothing fails until the load hits a <code>timestamptz</code> or <code>jsonb</code> column. This version tells the cursor to skip type parsing, so every value stays the text Postgres sent, which <code>COPY</code> reads back as-is.</li>
<li><strong>An explicit column list.</strong> <code>COPY table FROM STDIN</code> without a column list assumes the table&apos;s physical column order. The script reads the destination&apos;s writable (non-generated) columns from <code>information_schema.columns</code>, names them in the <code>COPY</code>, and fails on the first row if the transform doesn&apos;t produce every one of them.</li>
</ul>
<h2>Requirements</h2>
<ul><li>A supported Node.js LTS release (22 or later).</li>
<li><code>pg</code>, <code>pg-query-stream</code>, and <code>pg-copy-streams</code> 6 or later (<code>npm install pg pg-query-stream pg-copy-streams</code>). Both stream modules only work with the pure JavaScript client, not <code>pg-native</code>.</li>
<li>A source role with <code>SELECT</code> on the source table, and a destination role with <code>INSERT</code> (plus <code>TRUNCATE</code> if you use <code>--truncate</code>) on the destination table. Each role also needs <code>USAGE</code> on the table&apos;s schema if it doesn&apos;t own it.</li>
<li>The destination table created ahead of time. For the default transform below it needs every source column plus a <code>loaded_at timestamptz</code> column:<pre><code class="language-sql">CREATE TABLE staging.stg_orders (
    id          bigint PRIMARY KEY,
    customer_id bigint,
    status      text,
    total       numeric(12,2),
    metadata    jsonb,
    created_at  timestamptz,
    updated_at  timestamptz,
    loaded_at   timestamptz NOT NULL
);
</code></pre>
</li>
</ul>
<h2>Usage</h2>
<p>Set the connection strings and run the job. <code>--truncate</code> empties the destination in the same transaction as the <code>COPY</code>, so readers never see a half-loaded table. <code>TRUNCATE</code> takes an <code>ACCESS EXCLUSIVE</code> lock, so readers wait until the commit, and it isn&apos;t MVCC-safe: a transaction whose snapshot predates the commit and hadn&apos;t yet touched the table sees it empty. If that matters, load a staging table and swap it in.</p>
<pre><code class="language-bash">export SOURCE_DATABASE_URL=&quot;postgres://etl_reader:&lt;password&gt;@&lt;source-host&gt;:5432/app&quot;
export DEST_DATABASE_URL=&quot;postgres://etl_writer:&lt;password&gt;@&lt;warehouse-host&gt;:5432/warehouse&quot;
node stream_etl.js --source-table public.orders --dest-table staging.stg_orders --truncate --log-every 50000
</code></pre>
<p>Sample output:</p>
<pre><code class="language-text">Streaming public.orders -&gt; staging.stg_orders (8 columns)
Processed 50,000 rows (heap 21 MB)
Processed 100,000 rows (heap 23 MB)
Done: 137,412 rows in 38.6s, committed
</code></pre>
<p>The heap figure is <code>process.memoryUsage().heapUsed</code> at that moment. What matters is that it stays roughly flat as the row count climbs; if it grows with the row count, something in the transform is holding onto rows.</p>
<h2>Script</h2>
<pre><code class="language-javascript">/**
 * stream_etl.js
 *
 * Streams rows from a source Postgres table through a cursor, applies a
 * per-row transform, and bulk-loads the result into a destination table with
 * COPY ... FROM STDIN, without buffering the result set in memory.
 *
 * Reads:  SOURCE_DATABASE_URL, --source-table (SELECT *).
 *         DEST_DATABASE_URL, information_schema.columns for --dest-table.
 * Writes: --dest-table via COPY, inside one transaction (optionally after TRUNCATE).
 *
 * Usage: node stream_etl.js --source-table &lt;schema.table&gt; --dest-table &lt;schema.table&gt;
 *                           [--truncate] [--batch-size 1000] [--log-every 50000]
 */

&quot;use strict&quot;;

const { Pool } = require(&quot;pg&quot;);
const QueryStream = require(&quot;pg-query-stream&quot;);
const { from: copyFrom } = require(&quot;pg-copy-streams&quot;);
const { Transform } = require(&quot;node:stream&quot;);
const { pipeline } = require(&quot;node:stream/promises&quot;);

// Skip pg&apos;s type parsing: every non-null value arrives as the text Postgres sent.
const RAW_TEXT = { getTypeParser: () =&gt; (value) =&gt; value };

function parseArgs(argv) {
    const args = { truncate: false, &quot;batch-size&quot;: &quot;1000&quot;, &quot;log-every&quot;: &quot;50000&quot; };
    for (let i = 0; i &lt; argv.length; i += 1) {
        const token = argv[i];
        if (!token.startsWith(&quot;--&quot;)) {
            throw new Error(`Unexpected argument: ${token}`);
        }
        const key = token.slice(2);
        if (key === &quot;truncate&quot;) {
            args.truncate = true;
        } else {
            args[key] = argv[i + 1];
            i += 1;
        }
    }
    if (!args[&quot;source-table&quot;] || !args[&quot;dest-table&quot;]) {
        throw new Error(&quot;Usage: node stream_etl.js --source-table &lt;schema.table&gt; --dest-table &lt;schema.table&gt; [--truncate]&quot;);
    }
    const batchSize = Number(args[&quot;batch-size&quot;]);
    const logEvery = Number(args[&quot;log-every&quot;]);
    if (!Number.isInteger(batchSize) || batchSize &lt; 1 || !Number.isInteger(logEvery) || logEvery &lt; 1) {
        throw new Error(&quot;--batch-size and --log-every must be positive integers&quot;);
    }
    return {
        sourceTable: args[&quot;source-table&quot;],
        destTable: args[&quot;dest-table&quot;],
        truncate: args.truncate,
        batchSize,
        logEvery,
    };
}

function splitName(name) {
    const parts = name.split(&quot;.&quot;);
    return parts.length === 2 ? parts : [&quot;public&quot;, parts[0]];
}

function quoteName(client, name) {
    return splitName(name).map((part) =&gt; client.escapeIdentifier(part)).join(&quot;.&quot;);
}

async function destinationColumns(client, name) {
    const [schema, table] = splitName(name);
    const { rows } = await client.query(
        `SELECT column_name
           FROM information_schema.columns
          WHERE table_schema = $1 AND table_name = $2
            AND is_generated = &apos;NEVER&apos;
          ORDER BY ordinal_position`,
        [schema, table],
    );
    if (rows.length === 0) {
        throw new Error(`Destination table ${name} not found or not visible to this role`);
    }
    return rows.map((row) =&gt; row.column_name);
}

// One row in, one row out. Values are Postgres text (or null). Extend this for
// renames, filtering, or derived columns; never hold a reference to past rows.
function transformRow(row, loadedAt) {
    return { ...row, loaded_at: loadedAt };
}

// COPY text format: tab-delimited, \N for null, and backslash, newline,
// carriage return, and the delimiter escaped with a backslash.
function toCopyField(value) {
    if (value === null || value === undefined) {
        return &quot;\\N&quot;;
    }
    return String(value)
        .replace(/\\/g, &quot;\\\\&quot;)
        .replace(/\t/g, &quot;\\t&quot;)
        .replace(/\n/g, &quot;\\n&quot;)
        .replace(/\r/g, &quot;\\r&quot;);
}

async function run() {
    const { sourceTable, destTable, truncate, batchSize, logEvery } = parseArgs(process.argv.slice(2));

    const sourcePool = new Pool({ connectionString: process.env.SOURCE_DATABASE_URL, max: 1 });
    const destPool = new Pool({ connectionString: process.env.DEST_DATABASE_URL, max: 1 });
    const sourceClient = await sourcePool.connect();
    const destClient = await destPool.connect();

    const startedAt = Date.now();
    const loadedAt = new Date().toISOString();
    let rowCount = 0;

    try {
        const columns = await destinationColumns(destClient, destTable);
        const columnList = columns.map((c) =&gt; destClient.escapeIdentifier(c)).join(&quot;, &quot;);
        console.log(`Streaming ${sourceTable} -&gt; ${destTable} (${columns.length} columns)`);

        await destClient.query(&quot;BEGIN&quot;);
        if (truncate) {
            await destClient.query(`TRUNCATE ${quoteName(destClient, destTable)}`);
        }

        const source = sourceClient.query(
            new QueryStream(`SELECT * FROM ${quoteName(sourceClient, sourceTable)}`, [], {
                batchSize,
                types: RAW_TEXT,
            }),
        );

        const toCopyLines = new Transform({
            writableObjectMode: true,
            readableObjectMode: false,
            transform(row, _encoding, callback) {
                const out = transformRow(row, loadedAt);
                if (rowCount === 0) {
                    const missing = columns.filter((c) =&gt; !(c in out));
                    if (missing.length &gt; 0) {
                        callback(new Error(`Transform does not produce destination column(s): ${missing.join(&quot;, &quot;)}`));
                        return;
                    }
                }
                rowCount += 1;
                if (rowCount % logEvery === 0) {
                    const heapMb = Math.round(process.memoryUsage().heapUsed / 1024 / 1024);
                    console.log(`Processed ${rowCount.toLocaleString()} rows (heap ${heapMb} MB)`);
                }
                callback(null, columns.map((c) =&gt; toCopyField(out[c])).join(&quot;\t&quot;) + &quot;\n&quot;);
            },
        });

        const sink = destClient.query(
            copyFrom(`COPY ${quoteName(destClient, destTable)} (${columnList}) FROM STDIN`),
        );

        // Propagates backpressure and destroys every stream if any one fails;
        // destroying the COPY stream sends CopyFail so the server aborts the COPY.
        await pipeline(source, toCopyLines, sink);
        await destClient.query(&quot;COMMIT&quot;);

        const seconds = ((Date.now() - startedAt) / 1000).toFixed(1);
        console.log(`Done: ${rowCount.toLocaleString()} rows in ${seconds}s, committed`);
    } catch (error) {
        await destClient.query(&quot;ROLLBACK&quot;).catch(() =&gt; {});
        throw error;
    } finally {
        sourceClient.release();
        destClient.release();
        await Promise.all([sourcePool.end(), destPool.end()]);
    }
}

run().catch((error) =&gt; {
    console.error(&quot;ETL job failed:&quot;, error.message);
    process.exitCode = 1;
});
</code></pre>
<h2>Notes</h2>
<ul><li><strong>Where the memory bound comes from.</strong> <code>pg-query-stream</code> wraps <code>pg-cursor</code>, which fetches <code>batchSize</code> rows per round trip instead of the whole result set. The readable side&apos;s <code>highWaterMark</code> defaults to the same <code>batchSize</code>, so the stream buffers about one batch before it stops pulling. The package README describes it as keeping &quot;only a low number of rows in memory&quot;, which is the property you want. The bound is on rows, not bytes: the working set is roughly <code>--batch-size</code> times the average row width, plus the transform&apos;s and COPY stream&apos;s own small buffers, whatever the table size. A table with wide rows (large <code>text</code>, <code>jsonb</code> or <code>bytea</code> values) holds far more memory per batch than one of narrow rows, so lower <code>--batch-size</code> for those.</li>
<li><strong>Why <code>pipeline()</code> and not <code>.pipe()</code>.</strong> Node&apos;s docs say <code>stream.pipeline()</code> calls <code>stream.destroy(err)</code> on every stream in the chain when one fails. Hand-wired <code>.pipe()</code> calls don&apos;t do that, which is how a failed transform leaves a source cursor open or a <code>COPY</code> hanging. With pg-copy-streams 6 and later, destroying the <code>COPY</code> stream sends <code>CopyFail</code>, which aborts the <code>COPY</code>. The explicit <code>BEGIN</code>/<code>ROLLBACK</code> around it also undoes the <code>TRUNCATE</code>.</li>
<li><strong>Detecting the end of the COPY.</strong> Since pg-copy-streams 4.0, a <code>COPY FROM</code> stream signals completion with the standard <code>finish</code> event, not <code>end</code>. <code>pipeline()</code> already waits for <code>finish</code>, so the <code>COMMIT</code> only runs after the server has accepted every row.</li>
<li><strong>Don&apos;t use <code>pool.query()</code> for COPY.</strong> The pg-copy-streams README is explicit: the pool&apos;s convenience method returns a Promise and doesn&apos;t support custom query objects. Take a client with <code>pool.connect()</code> and call <code>client.query()</code> on it, as the script does.</li>
<li><strong>Failed COPYs leave dead space.</strong> PostgreSQL stops a <code>COPY FROM</code> at the first bad row. Rows already sent aren&apos;t visible, but they still take disk space until <code>VACUUM</code> reclaims it. A large load that fails near the end is worth a manual <code>VACUUM</code> on the destination table.</li>
<li><strong>Raw text has one catch.</strong> Because values are Postgres text, the transform works with strings: <code>&quot;12.50&quot;</code>, not <code>12.5</code>, and <code>&quot;t&quot;</code>/<code>&quot;f&quot;</code> for booleans. Parse only the columns you actually compute on, and turn them back into strings Postgres accepts before returning. That&apos;s also why no conversion is needed on the way out: the COPY docs define text-format values as the strings produced by each type&apos;s output function, or accepted by its input function.</li>
<li><strong>Consistent snapshot.</strong> A single <code>SELECT</code> sees one snapshot of the source for its whole run, even while the table keeps changing. The cost is that a long read on a busy primary holds back cleanup of dead rows until it finishes. Run big extracts against a replica, or use the <a href="https://www.techcolumnist.com/2025/12/17/python-data-warehouse-incremental-loads-from-postgres-to-bigquery/">watermark approach</a> so each run only reads recent changes.</li>
</ul>
<h2>References</h2>
<ul><li><a href="https://github.com/brianc/node-postgres/tree/master/packages/pg-query-stream">pg-query-stream README</a></li>
<li><a href="https://github.com/brianc/node-pg-copy-streams">pg-copy-streams README</a></li>
<li><a href="https://node-postgres.com/features/types">node-postgres: data types and type parsing</a></li>
<li><a href="https://nodejs.org/api/stream.html">Node.js stream docs: <code>stream.pipeline()</code> and backpressure</a></li>
<li><a href="https://www.postgresql.org/docs/current/sql-copy.html">PostgreSQL: COPY (text format and escaping rules)</a></li>
<li><a href="https://www.postgresql.org/docs/current/infoschema-columns.html">PostgreSQL: information_schema.columns</a></li>
</ul>
]]></content:encoded>
      <category>Scripts</category>
      <category>Engineering</category>
    </item>
    <item>
      <title>Node.js: Azure – A Slack Bot for Resource Group Budget Alerts</title>
      <link>https://www.techcolumnist.com/2026/02/18/node-js-azure-a-slack-bot-for-resource-group-budget-alerts/</link>
      <guid isPermaLink="true">https://www.techcolumnist.com/2026/02/18/node-js-azure-a-slack-bot-for-resource-group-budget-alerts/</guid>
      <pubDate>Wed, 18 Feb 2026 14:00:00 GMT</pubDate>
      <dc:creator>Tom Lasswell</dc:creator>
      <description>A Node.js script that queries month-to-date Azure cost per resource group, projects month-end spend, and posts Block Kit messages to Slack for groups over budget.</description>
      <content:encoded><![CDATA[<p>Azure&apos;s built-in budget alerts are fine, but out of the box they email a distribution list, which means they get filtered into a folder nobody checks (wiring them to Slack takes more plumbing, covered below). What actually gets attention on my teams is a Slack message in the channel where the engineers who provisioned the resources already live. This script queries Azure Cost Management for month-to-date spend on a list of resource groups, projects where each one will land at month end, compares both against a configured budget, and posts a single Slack message covering everything over the line. I run it as a scheduled task, but it&apos;s plain enough to drop into an Azure Function on a timer trigger. It is the budget half of <a href="https://www.techcolumnist.com/2026/08/12/azure-cost-governance-without-killing-developer-velocity/">Azure: Cost Governance Without Killing Developer Velocity</a>; the anomaly half is <a href="https://www.techcolumnist.com/2025/12/24/python-azure-automate-cost-anomaly-alerts-with-the-cost-management-api/">Python: Azure – Cost Anomaly Alerts from the Cost Management API</a>.</p>
<h2>Requirements</h2>
<ul><li>A Node.js LTS release (20 or later) for the built-in <code>fetch</code>.</li>
<li><code>@azure/identity</code> (<code>npm install @azure/identity</code>). The script uses <code>DefaultAzureCredential</code>, so the same code works with a managed identity in Azure, a service principal from <code>AZURE_TENANT_ID</code> / <code>AZURE_CLIENT_ID</code> / <code>AZURE_CLIENT_SECRET</code>, or an <code>az login</code> session while testing.</li>
<li><strong>Cost Management Reader</strong> on each resource group being queried (or once at the subscription or management group above them). Resource group scope is a supported Cost Management scope, so the identity doesn&apos;t need anything wider.</li>
<li>A Slack incoming webhook URL for the channel that should receive alerts.</li>
<li>A small JSON config file listing the resource groups to watch and their monthly budgets.</li>
</ul>
<h2>Parameters</h2>
<table><thead><tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr>
</thead><tbody><tr><td><code>--config</code></td><td>String</td><td>Yes</td><td>Path to the JSON config (array of <code>subscriptionId</code>, <code>resourceGroup</code>, <code>monthlyBudget</code>, optional <code>owner</code>).</td></tr>
<tr><td><code>--threshold-percent</code></td><td>Number</td><td>No</td><td>Alert when actual or projected spend reaches this percentage of budget. Default <code>80</code>.</td></tr>
<tr><td><code>--dry-run</code></td><td>Switch</td><td>No</td><td>Print the Slack payload instead of posting it.</td></tr>
<tr><td><code>SLACK_WEBHOOK_URL</code></td><td>Env var</td><td>Yes</td><td>Incoming webhook URL. Treat it as a secret.</td></tr>
</tbody></table>
<h2>Usage</h2>
<p>Create a <code>budgets.json</code> config next to the script. <code>owner</code> is optional text that ends up in the message, such as a Slack handle or team name:</p>
<pre><code class="language-json">[
  { &quot;subscriptionId&quot;: &quot;&lt;subscription-id&gt;&quot;, &quot;resourceGroup&quot;: &quot;rg-prod-app&quot;, &quot;monthlyBudget&quot;: 4000, &quot;owner&quot;: &quot;@app-team&quot; },
  { &quot;subscriptionId&quot;: &quot;&lt;subscription-id&gt;&quot;, &quot;resourceGroup&quot;: &quot;rg-prod-data&quot;, &quot;monthlyBudget&quot;: 2500, &quot;owner&quot;: &quot;@data-team&quot; },
  { &quot;subscriptionId&quot;: &quot;&lt;subscription-id&gt;&quot;, &quot;resourceGroup&quot;: &quot;rg-shared-network&quot;, &quot;monthlyBudget&quot;: 800 }
]
</code></pre>
<p>Set the environment and run it. With a service principal:</p>
<pre><code class="language-bash">export AZURE_TENANT_ID=&quot;&lt;tenant-id&gt;&quot;
export AZURE_CLIENT_ID=&quot;&lt;client-id&gt;&quot;
export AZURE_CLIENT_SECRET=&quot;&lt;client-secret&gt;&quot;
export SLACK_WEBHOOK_URL=&quot;&lt;slack-webhook-url&gt;&quot;

node budget-alert-bot.js --config budgets.json --threshold-percent 80
</code></pre>
<pre><code class="language-text">rg-prod-app: 2,961.40 of 4,000.00 USD (74.0%), projected 4,877.60 (121.9%) ALERT
rg-prod-data: 1,104.77 of 2,500.00 USD (44.2%), projected 1,819.62 (72.8%)
rg-shared-network: 702.15 of 800.00 USD (87.8%), projected 1,156.48 (144.6%) ALERT
2 of 3 resource group(s) at or over 80%. Posted 1 Slack message(s).
</code></pre>
<p>Schedule it daily. Budgets and cost data only refresh a few times a day, and Microsoft recommends calling the cost APIs no more than once per day:</p>
<pre><code class="language-bash">0 8 * * * cd /opt/budget-bot &amp;&amp; node budget-alert-bot.js --config budgets.json --threshold-percent 80 &gt;&gt; /var/log/budget-bot.log 2&gt;&amp;1
</code></pre>
<h2>Script</h2>
<pre><code class="language-javascript">#!/usr/bin/env node
/**
 * budget-alert-bot.js
 *
 * Queries Azure Cost Management for month-to-date actual cost on a list of
 * resource groups, projects month-end spend with a straight-line run rate,
 * and posts Slack Block Kit messages (20 groups each) listing every resource group whose
 * actual or projected spend reached the threshold percentage of its budget.
 *
 * Reads:  a JSON config file (--config) of { subscriptionId, resourceGroup,
 *         monthlyBudget, owner? } entries, and the Cost Management Query API.
 * Writes: nothing locally; posts to the Slack incoming webhook in
 *         SLACK_WEBHOOK_URL (or prints the payload with --dry-run).
 *
 * Auth:   DefaultAzureCredential (managed identity, AZURE_* environment
 *         variables for a service principal, or an Azure CLI login).
 */

const fs = require(&apos;fs&apos;);
const { DefaultAzureCredential } = require(&apos;@azure/identity&apos;);

const ARM = &apos;https://management.azure.com&apos;;
const API_VERSION = &apos;2025-03-01&apos;;
const TOKEN_SCOPE = &apos;https://management.azure.com/.default&apos;;
const QPU_RETRY_HEADER = &apos;x-ms-ratelimit-microsoft.costmanagement-qpu-retry-after&apos;;
const MAX_ATTEMPTS = 4;
const SECTIONS_PER_MESSAGE = 20;

const sleep = (ms) =&gt; new Promise((resolve) =&gt; setTimeout(resolve, ms));

function parseArgs(argv) {
    const args = { configPath: null, thresholdPercent: 80, dryRun: false };

    for (let i = 0; i &lt; argv.length; i++) {
        if (argv[i] === &apos;--config&apos;) {
            args.configPath = argv[++i];
        } else if (argv[i] === &apos;--threshold-percent&apos;) {
            args.thresholdPercent = Number(argv[++i]);
        } else if (argv[i] === &apos;--dry-run&apos;) {
            args.dryRun = true;
        }
    }

    if (!args.configPath || !Number.isFinite(args.thresholdPercent)) {
        throw new Error(&apos;Usage: node budget-alert-bot.js --config &lt;path&gt; [--threshold-percent &lt;n&gt;] [--dry-run]&apos;);
    }
    return args;
}

function loadConfig(path) {
    const entries = JSON.parse(fs.readFileSync(path, &apos;utf8&apos;));
    if (!Array.isArray(entries) || entries.length === 0) {
        throw new Error(`${path} must be a non-empty JSON array.`);
    }
    for (const entry of entries) {
        if (!entry.subscriptionId || !entry.resourceGroup || !(Number(entry.monthlyBudget) &gt; 0)) {
            throw new Error(`Invalid config entry: ${JSON.stringify(entry)}`);
        }
    }
    return entries;
}

function monthProgress(now = new Date()) {
    const daysInMonth = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 0)).getUTCDate();
    // Cost data lags, so count only completed UTC days (minimum 1) toward the run rate.
    const daysElapsed = Math.max(now.getUTCDate() - 1, 1);
    return { daysElapsed, daysInMonth };
}

async function queryMonthToDate(token, subscriptionId, resourceGroup) {
    const scope = `/subscriptions/${subscriptionId}/resourceGroups/${resourceGroup}`;
    const url = `${ARM}${scope}/providers/Microsoft.CostManagement/query?api-version=${API_VERSION}`;
    const body = JSON.stringify({
        type: &apos;ActualCost&apos;,
        timeframe: &apos;MonthToDate&apos;,
        dataset: {
            granularity: &apos;None&apos;,
            aggregation: { totalCost: { name: &apos;PreTaxCost&apos;, function: &apos;Sum&apos; } },
        },
    });

    let response;
    for (let attempt = 1; attempt &lt;= MAX_ATTEMPTS; attempt++) {
        response = await fetch(url, {
            method: &apos;POST&apos;,
            headers: { Authorization: `Bearer ${token}`, &apos;Content-Type&apos;: &apos;application/json&apos; },
            body,
        });
        if (![429, 503].includes(response.status) || attempt === MAX_ATTEMPTS) {
            break;
        }
        const wait = Number(response.headers.get(QPU_RETRY_HEADER) || response.headers.get(&apos;retry-after&apos;) || 30);
        console.error(`${resourceGroup}: throttled (${response.status}), retrying in ${wait}s`);
        await sleep(wait * 1000);
    }

    if (!response.ok) {
        throw new Error(`${resourceGroup}: Cost Management query failed ${response.status} ${await response.text()}`);
    }
    if (response.status === 204) {
        // 204 No Content is a documented success: nothing to report yet.
        return { spend: 0, currency: &apos;&apos; };
    }

    const { properties } = await response.json();
    const costIndex = properties.columns.findIndex((col) =&gt; col.type === &apos;Number&apos;);
    const currencyIndex = properties.columns.findIndex((col) =&gt; col.name === &apos;Currency&apos;);
    const row = properties.rows[0];

    // No rows means no cost yet this month.
    return {
        spend: row ? Number(row[costIndex]) : 0,
        currency: row &amp;&amp; currencyIndex &gt;= 0 ? row[currencyIndex] : &apos;&apos;,
    };
}

function formatAmount(value) {
    return value.toLocaleString(&apos;en-US&apos;, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

function buildSlackMessages(alerts, thresholdPercent) {
    const messages = [];
    for (let i = 0; i &lt; alerts.length; i += SECTIONS_PER_MESSAGE) {
        const chunk = alerts.slice(i, i + SECTIONS_PER_MESSAGE);
        const blocks = [
            {
                type: &apos;header&apos;,
                text: { type: &apos;plain_text&apos;, text: `Azure budget alert: ${alerts.length} resource group(s) at or over ${thresholdPercent}%` },
            },
        ];
        for (const a of chunk) {
            blocks.push({
                type: &apos;section&apos;,
                text: { type: &apos;mrkdwn&apos;, text: `*${a.resourceGroup}*${a.owner ? `  ${a.owner}` : &apos;&apos;}` },
                fields: [
                    { type: &apos;mrkdwn&apos;, text: `*Month to date*\n${formatAmount(a.spend)} ${a.currency} (${a.percentUsed.toFixed(1)}%)` },
                    { type: &apos;mrkdwn&apos;, text: `*Budget*\n${formatAmount(a.monthlyBudget)} ${a.currency}` },
                    { type: &apos;mrkdwn&apos;, text: `*Projected month end*\n${formatAmount(a.projected)} ${a.currency} (${a.projectedPercent.toFixed(1)}%)` },
                    { type: &apos;mrkdwn&apos;, text: `*Subscription*\n\`${a.subscriptionId}\`` },
                ],
            });
        }
        blocks.push({ type: &apos;context&apos;, elements: [{ type: &apos;mrkdwn&apos;, text: &apos;Actual cost from Azure Cost Management; data can lag by a day or more.&apos; }] });

        messages.push({
            // Top-level text is the notification and fallback when blocks can&apos;t be shown.
            text: `Azure budget alert: ${chunk.map((a) =&gt; a.resourceGroup).join(&apos;, &apos;)}`,
            blocks,
        });
    }
    return messages;
}

async function postToSlack(webhookUrl, message) {
    let response;
    for (let attempt = 1; attempt &lt;= MAX_ATTEMPTS; attempt++) {
        response = await fetch(webhookUrl, {
            method: &apos;POST&apos;,
            headers: { &apos;Content-Type&apos;: &apos;application/json&apos; },
            body: JSON.stringify(message),
        });
        if (response.status !== 429 || attempt === MAX_ATTEMPTS) {
            break;
        }
        const wait = Number(response.headers.get(&apos;retry-after&apos;) || 1);
        await sleep(wait * 1000);
    }
    if (!response.ok) {
        // Slack returns a short error string such as invalid_payload, no_text or channel_is_archived.
        throw new Error(`Slack webhook post failed: ${response.status} ${await response.text()}`);
    }
}

async function main() {
    const args = parseArgs(process.argv.slice(2));
    const webhookUrl = process.env.SLACK_WEBHOOK_URL;
    if (!webhookUrl &amp;&amp; !args.dryRun) {
        throw new Error(&apos;SLACK_WEBHOOK_URL is not set.&apos;);
    }

    const config = loadConfig(args.configPath);
    const { token } = await new DefaultAzureCredential().getToken(TOKEN_SCOPE);
    const { daysElapsed, daysInMonth } = monthProgress();

    const alerts = [];
    let failures = 0;

    // Serial on purpose: Query API quotas are per tenant.
    for (const entry of config) {
        try {
            const { spend, currency } = await queryMonthToDate(token, entry.subscriptionId, entry.resourceGroup);
            const monthlyBudget = Number(entry.monthlyBudget);
            const projected = (spend / daysElapsed) * daysInMonth;
            const result = {
                ...entry,
                monthlyBudget,
                spend,
                currency,
                projected,
                percentUsed: (spend / monthlyBudget) * 100,
                projectedPercent: (projected / monthlyBudget) * 100,
            };
            const isAlert = result.percentUsed &gt;= args.thresholdPercent || result.projectedPercent &gt;= args.thresholdPercent;

            console.log(
                `${entry.resourceGroup}: ${formatAmount(spend)} of ${formatAmount(monthlyBudget)} ${currency} ` +
                `(${result.percentUsed.toFixed(1)}%), projected ${formatAmount(projected)} ` +
                `(${result.projectedPercent.toFixed(1)}%)${isAlert ? &apos; ALERT&apos; : &apos;&apos;}`
            );
            if (isAlert) {
                alerts.push(result);
            }
        } catch (error) {
            failures++;
            console.error(error.message);
        }
    }

    const messages = buildSlackMessages(alerts, args.thresholdPercent);
    for (const [index, message] of messages.entries()) {
        if (args.dryRun) {
            console.log(JSON.stringify(message, null, 2));
        } else {
            if (index &gt; 0) {
                // Incoming webhooks allow about one message per second.
                await sleep(1100);
            }
            await postToSlack(webhookUrl, message);
        }
    }

    const posted = args.dryRun ? 0 : messages.length;
    console.log(`${alerts.length} of ${config.length} resource group(s) at or over ${args.thresholdPercent}%. Posted ${posted} Slack message(s).`);
    if (failures &gt; 0) {
        process.exitCode = 1;
    }
}

main().catch((error) =&gt; {
    console.error(error);
    process.exitCode = 1;
});
</code></pre>
<h2>Notes</h2>
<ul><li><strong>The projection is deliberately crude.</strong> Month-to-date spend divided by completed days, times days in the month. It warns early about a resource group trending over budget, but it overshoots after a one-off purchase early in the month and undershoots for workloads that ramp at month end. Azure budgets have a proper forecast-based alert (a threshold on forecasted cost) if you want Microsoft&apos;s model instead.</li>
<li>Cost data is not real time. For EA and MCA subscriptions it typically arrives within 8 to 24 hours (up to 72 hours for pay-as-you-go), and figures are estimates until the invoice is generated. Treat this as a daily trend alert, not a meter that catches a runaway resource in the hour it happens.</li>
<li><code>MonthToDate</code> follows the calendar month, and <code>monthProgress</code> counts days in UTC. Pay-as-you-go, MSDN and Visual Studio subscriptions can have invoice periods that don&apos;t align with calendar months; the Query API also accepts <code>BillingMonthToDate</code> for those, and <code>monthProgress</code> would need the same change.</li>
<li>Resource groups are queried one at a time because the Query API limits are per tenant (12 query processing units per 10 seconds, 60 per minute, 600 per hour at the time of writing, one unit per month of data). A 429 response carries the back-off in <code>x-ms-ratelimit-microsoft.costmanagement-qpu-retry-after</code>, which the script waits out.</li>
<li>Slack allows roughly one incoming-webhook message per second, with short bursts, and answers a flood with HTTP 429 and a <code>Retry-After</code> header. Batching every alert into one message (split at 20 resource groups) keeps a bad day from turning into a message storm. A section block&apos;s text is capped at 3,000 characters and its fields render as two columns.</li>
<li>The webhook URL is a credential. Slack actively looks for leaked webhook URLs and revokes them. Keep it in Key Vault or your scheduler&apos;s secret store, not in the config file or the repo.</li>
<li>A resource group that is renamed or deleted makes its query fail. The script logs it, carries on with the rest, and exits non-zero so the scheduler flags the run.</li>
</ul>
<h3>Native budgets and action groups</h3>
<p>If you would rather let Azure do the threshold math, create a budget on each resource group and attach an action group: budgets can call action groups at subscription and resource group scope, and they are evaluated against costs every 24 hours. The catch for Slack is the payload. The action group webhook sends Azure&apos;s budget notification JSON, not the <code>text</code>/<code>blocks</code> body a Slack webhook expects (Slack rejects a body without <code>text</code> as <code>no_text</code>), and the action group can&apos;t add custom headers. So you still need a small Logic App or Function in between to reshape it. The payload Microsoft documents looks like this:</p>
<pre><code class="language-json">{
  &quot;schemaId&quot;: &quot;AIP Budget Notification&quot;,
  &quot;data&quot;: {
    &quot;SubscriptionName&quot;: &quot;&lt;subscription-name&gt;&quot;,
    &quot;SubscriptionId&quot;: &quot;&lt;subscription-id&gt;&quot;,
    &quot;SpendingAmount&quot;: &quot;100&quot;,
    &quot;BudgetStartDate&quot;: &quot;6/1/2018&quot;,
    &quot;Budget&quot;: &quot;50&quot;,
    &quot;Unit&quot;: &quot;USD&quot;,
    &quot;BudgetCreator&quot;: &quot;user@example.com&quot;,
    &quot;BudgetName&quot;: &quot;BudgetName&quot;,
    &quot;BudgetType&quot;: &quot;Cost&quot;,
    &quot;ResourceGroup&quot;: &quot;&quot;,
    &quot;NotificationThresholdAmount&quot;: &quot;0.8&quot;
  }
}
</code></pre>
<p>Every value arrives as a string, so parse <code>SpendingAmount</code>, <code>Budget</code> and <code>NotificationThresholdAmount</code> before doing math on them. Budgets work with action groups whether or not the common alert schema is enabled on the group. I still prefer the script for the channel-per-team case, because one config file is easier to review than forty budgets, but the native route has no server to run.</p>
<h2>References</h2>
<ul><li><a href="https://learn.microsoft.com/en-us/rest/api/cost-management/query/usage">Query - Usage (Cost Management REST API)</a></li>
<li><a href="https://learn.microsoft.com/en-us/azure/cost-management-billing/costs/manage-automation">Manage Azure costs with automation (data latency, QPU rate limits, Budgets API)</a></li>
<li><a href="https://learn.microsoft.com/en-us/azure/cost-management-billing/costs/tutorial-acm-create-budgets">Tutorial: Create and manage budgets (action groups, evaluation frequency)</a></li>
<li><a href="https://learn.microsoft.com/en-us/azure/cost-management-billing/manage/cost-management-budget-scenario">Manage costs with budgets (budget alert payload for action groups)</a></li>
<li><a href="https://learn.microsoft.com/en-us/azure/cost-management-billing/costs/assign-access-acm-data">Assign access to Cost Management data</a></li>
<li><a href="https://learn.microsoft.com/en-us/javascript/api/overview/azure/identity-readme">Azure Identity client library for JavaScript</a></li>
<li><a href="https://docs.slack.dev/messaging/sending-messages-using-incoming-webhooks/">Slack: Sending messages using incoming webhooks</a></li>
<li><a href="https://docs.slack.dev/apis/web-api/rate-limits/">Slack: Rate limits</a> and <a href="https://docs.slack.dev/reference/block-kit/blocks/section-block/">Section block reference</a></li>
</ul>
]]></content:encoded>
      <category>Scripts</category>
      <category>Engineering</category>
    </item>
    <item>
      <title>Node.js: Discovery – Scanning a Subnet for Open RDP and SSH</title>
      <link>https://www.techcolumnist.com/2026/02/11/node-js-discovery-scanning-a-subnet-for-open-rdp-and-ssh/</link>
      <guid isPermaLink="true">https://www.techcolumnist.com/2026/02/11/node-js-discovery-scanning-a-subnet-for-open-rdp-and-ssh/</guid>
      <pubDate>Wed, 11 Feb 2026 14:00:00 GMT</pubDate>
      <dc:creator>Tom Lasswell</dc:creator>
      <description>A dependency-free Node.js TCP connect scanner that sweeps a subnet for RDP and SSH, separates closed from filtered ports, grabs SSH banners and writes CSV.</description>
      <content:encoded><![CDATA[<p>Before I trust a network diagram, I like to check it against reality, and the fastest reality check I know is &quot;what&apos;s actually listening.&quot; Nmap is the right tool for a serious scan, but when I just want a quick answer to &quot;which hosts on this /24 have RDP or SSH open&quot; from inside a script or a CI job without pulling in a system dependency, a plain Node.js TCP connect scan does the job with nothing beyond the standard library.</p>
<p>It&apos;s the routed-subnet counterpart to the <a href="https://www.techcolumnist.com/2026/01/07/python-discovery-fingerprint-every-device-on-a-subnet/">Python ARP fingerprinting script</a> (ARP only sees your own VLAN; a TCP connect works across routers) and one of the collectors in the <a href="https://www.techcolumnist.com/2026/07/15/infrastructure-a-discovery-first-approach-to-documenting-an-undocumented-network/">discovery-first approach to documenting an undocumented network</a>.</p>
<h2>Requirements</h2>
<ul><li>A supported Node.js LTS release (22 or later). Only the built-in <code>net</code> and <code>fs</code> modules are used; no <code>npm install</code>.</li>
<li>Network reachability from wherever the script runs to the target subnet. No root needed: a TCP connect scan uses the operating system&apos;s normal <code>connect()</code> call, the same thing nmap falls back to (<code>-sT</code>) when it lacks raw-packet privileges.</li>
<li>Written authorization to scan the target range. It&apos;s a plain connect scan, not a stealth technique, but scanning a network you don&apos;t own or manage without permission is not okay regardless of how the scan is implemented.</li>
</ul>
<h2>Usage</h2>
<p>Scan a /24 for the default ports (22 and 3389):</p>
<pre><code class="language-bash">node scan-subnet.js 10.0.10.0/24
</code></pre>
<p>Scan a smaller range for a custom port list (adding WinRM on 5985) with a longer per-connection timeout for a slow WAN link, and write every result, not just open ones, to CSV:</p>
<pre><code class="language-bash">node scan-subnet.js 10.0.10.0/28 --ports 22,3389,5985 --timeout 1500 --concurrency 50 --all --csv results.csv
</code></pre>
<p>Sample output from the default run:</p>
<pre><code class="language-text">Scanning 10.0.10.0/24 (254 host(s)) for ports [22, 3389]
Concurrency: 100, timeout: 500ms per attempt

10.0.10.12     22/tcp open     (ssh)  SSH-2.0-OpenSSH_9.6
10.0.10.45     3389/tcp open     (rdp)
10.0.10.201    22/tcp open     (ssh)  SSH-2.0-OpenSSH_8.7
10.0.10.201    3389/tcp open     (rdp)

Scan complete in 4.8s. 3 host(s) with at least one open port out of 254 scanned.
States: open 4, closed 61, filtered 443
</code></pre>
<p>The last line is the useful part for an exposure check. <strong>Closed</strong> means the host answered with a TCP reset (it&apos;s alive, nothing listening). <strong>Filtered</strong> means no answer before the timeout (no host there, or a firewall silently dropping the connection) or any other connection error, such as host or network unreachable.</p>
<h2>Script</h2>
<pre><code class="language-javascript">/**
 * scan-subnet.js
 *
 * Dependency-free TCP connect scanner for a small set of ports (SSH/RDP by default)
 * across every usable host in an IPv4 CIDR range. Classifies each attempt as open,
 * closed (ECONNREFUSED) or filtered (timeout / unreachable), and records the SSH
 * identification string where the server sends one.
 *
 * Reads: command-line arguments only.
 * Writes: stdout, and a CSV file when --csv is given.
 *
 * Usage:
 *   node scan-subnet.js &lt;cidr&gt; [--ports 22,3389] [--timeout 500] [--concurrency 100] [--all] [--csv out.csv]
 *
 * Only run this against networks you are authorized to scan.
 */

&apos;use strict&apos;;

const fs = require(&apos;fs&apos;);
const net = require(&apos;net&apos;);

const SERVICE_NAMES = { 22: &apos;ssh&apos;, 3389: &apos;rdp&apos;, 5985: &apos;winrm-http&apos;, 5986: &apos;winrm-https&apos; };
const BANNER_PORTS = new Set([22]);

function parseArgs(argv) {
    const args = { cidr: null, ports: [22, 3389], timeout: 500, concurrency: 100, all: false, csv: null };

    for (let i = 0; i &lt; argv.length; i++) {
        const arg = argv[i];
        if (arg === &apos;--ports&apos;) {
            args.ports = argv[++i].split(&apos;,&apos;).map((p) =&gt; parseInt(p.trim(), 10));
        } else if (arg === &apos;--timeout&apos;) {
            args.timeout = parseInt(argv[++i], 10);
        } else if (arg === &apos;--concurrency&apos;) {
            args.concurrency = parseInt(argv[++i], 10);
        } else if (arg === &apos;--csv&apos;) {
            args.csv = argv[++i];
        } else if (arg === &apos;--all&apos;) {
            args.all = true;
        } else if (!args.cidr) {
            args.cidr = arg;
        }
    }

    if (!args.cidr) {
        throw new Error(&apos;Usage: node scan-subnet.js &lt;cidr&gt; [--ports 22,3389] [--timeout 500] [--concurrency 100] [--all] [--csv out.csv]&apos;);
    }
    if (args.ports.some((p) =&gt; !Number.isInteger(p) || p &lt; 1 || p &gt; 65535)) {
        throw new Error(&apos;Ports must be integers between 1 and 65535.&apos;);
    }
    if (!Number.isInteger(args.timeout) || args.timeout &lt; 1 || !Number.isInteger(args.concurrency) || args.concurrency &lt; 1) {
        throw new Error(&apos;--timeout and --concurrency must be positive integers.&apos;);
    }
    return args;
}

function ipToInt(ip) {
    return ip.split(&apos;.&apos;).reduce((acc, octet) =&gt; ((acc &lt;&lt; 8) + parseInt(octet, 10)) &gt;&gt;&gt; 0, 0);
}

function intToIp(int) {
    return [24, 16, 8, 0].map((shift) =&gt; (int &gt;&gt;&gt; shift) &amp; 255).join(&apos;.&apos;);
}

function expandCidr(cidr) {
    const [base, prefixStr] = cidr.split(&apos;/&apos;);
    const prefix = parseInt(prefixStr ?? &apos;32&apos;, 10);

    if (!net.isIPv4(base)) {
        throw new Error(`Not an IPv4 address: ${base}`);
    }
    if (!Number.isInteger(prefix) || prefix &lt; 16 || prefix &gt; 32) {
        throw new Error(`Prefix /${prefixStr} out of range: use /16 to /32.`);
    }

    const size = 2 ** (32 - prefix);
    const network = (ipToInt(base) &amp; ((0xffffffff &lt;&lt; (32 - prefix)) &gt;&gt;&gt; 0)) &gt;&gt;&gt; 0;

    // /31 and /32 have no network/broadcast addresses to skip (RFC 3021 for /31).
    const first = prefix &gt;= 31 ? 0 : 1;
    const last = prefix &gt;= 31 ? size - 1 : size - 2;

    const ips = [];
    for (let i = first; i &lt;= last; i++) {
        ips.push(intToIp((network + i) &gt;&gt;&gt; 0));
    }
    return ips;
}

function checkPort(host, port, timeoutMs) {
    return new Promise((resolve) =&gt; {
        const socket = new net.Socket();
        let state = null;
        let banner = &apos;&apos;;

        const finish = (result) =&gt; {
            if (state) {
                return;
            }
            state = result;
            // A &apos;timeout&apos; event does not close the socket by itself; destroy() does.
            socket.destroy();
            resolve({ host, port, state, banner });
        };

        socket.setTimeout(timeoutMs);
        socket.once(&apos;connect&apos;, () =&gt; {
            if (!BANNER_PORTS.has(port)) {
                finish(&apos;open&apos;);
                return;
            }
            // Both sides send an identification string (RFC 4253 section 4.2); servers
            // normally send theirs without waiting. Buffer until the SSH- line is complete,
            // since it can be split across chunks or follow other lines.
            let received = &apos;&apos;;
            socket.on(&apos;data&apos;, (chunk) =&gt; {
                received += chunk.toString(&apos;utf8&apos;);
                const lines = received.split(&apos;\n&apos;);
                const line = lines.slice(0, -1).find((l) =&gt; l.startsWith(&apos;SSH-&apos;));
                if (line || received.length &gt; 8192) {
                    banner = line ? line.trim() : &apos;&apos;;
                    finish(&apos;open&apos;);
                }
            });
            // The server may accept and then hang up without sending anything.
            socket.once(&apos;close&apos;, () =&gt; finish(&apos;open&apos;));
        });
        socket.once(&apos;timeout&apos;, () =&gt; finish(socket.connecting ? &apos;filtered&apos; : &apos;open&apos;));
        socket.once(&apos;error&apos;, (error) =&gt; finish(error.code === &apos;ECONNREFUSED&apos; ? &apos;closed&apos; : &apos;filtered&apos;));

        socket.connect(port, host);
    });
}

async function asyncPool(limit, items, iteratorFn) {
    const results = [];
    const executing = new Set();

    for (const item of items) {
        const promise = Promise.resolve().then(() =&gt; iteratorFn(item));
        results.push(promise);
        executing.add(promise);
        const cleanup = () =&gt; executing.delete(promise);
        promise.then(cleanup, cleanup);
        if (executing.size &gt;= limit) {
            await Promise.race(executing);
        }
    }
    return Promise.all(results);
}

function csvEscape(value) {
    const text = String(value ?? &apos;&apos;);
    return /[&quot;,\n]/.test(text) ? `&quot;${text.replace(/&quot;/g, &apos;&quot;&quot;&apos;)}&quot;` : text;
}

async function main() {
    const args = parseArgs(process.argv.slice(2));
    const hosts = expandCidr(args.cidr);

    console.log(`Scanning ${args.cidr} (${hosts.length} host(s)) for ports [${args.ports.join(&apos;, &apos;)}]`);
    console.log(`Concurrency: ${args.concurrency}, timeout: ${args.timeout}ms per attempt`);
    console.log(&apos;&apos;);

    const startTime = Date.now();
    const targets = hosts.flatMap((host) =&gt; args.ports.map((port) =&gt; ({ host, port })));

    const results = await asyncPool(args.concurrency, targets, async ({ host, port }) =&gt; {
        const result = await checkPort(host, port, args.timeout);
        if (result.state === &apos;open&apos; || args.all) {
            const service = SERVICE_NAMES[port] ? `(${SERVICE_NAMES[port]})` : &apos;&apos;;
            console.log(`${host.padEnd(15)}${`${port}/tcp`} ${result.state.padEnd(8)} ${service}  ${result.banner}`.trimEnd());
        }
        return result;
    });

    const counts = { open: 0, closed: 0, filtered: 0 };
    const openHosts = new Set();
    for (const result of results) {
        counts[result.state]++;
        if (result.state === &apos;open&apos;) {
            openHosts.add(result.host);
        }
    }

    if (args.csv) {
        const rows = (args.all ? results : results.filter((r) =&gt; r.state === &apos;open&apos;))
            .map((r) =&gt; [r.host, r.port, SERVICE_NAMES[r.port] ?? &apos;&apos;, r.state, r.banner].map(csvEscape).join(&apos;,&apos;));
        fs.writeFileSync(args.csv, [&apos;ip_address,port,service,state,banner&apos;, ...rows].join(&apos;\n&apos;) + &apos;\n&apos;, &apos;utf8&apos;);
    }

    const elapsedSeconds = ((Date.now() - startTime) / 1000).toFixed(1);
    console.log(&apos;&apos;);
    console.log(`Scan complete in ${elapsedSeconds}s. ${openHosts.size} host(s) with at least one open port out of ${hosts.length} scanned.`);
    console.log(`States: open ${counts.open}, closed ${counts.closed}, filtered ${counts.filtered}`);
}

main().catch((error) =&gt; {
    console.error(error.message);
    process.exitCode = 1;
});
</code></pre>
<h2>Notes</h2>
<ul><li><strong>What changed from the first version.</strong> The earlier draft&apos;s sample output listed <code>closed</code> lines the script never printed, it scanned the network and broadcast addresses, it accepted any prefix down to <code>/0</code> (four billion targets), and it lumped refused and timed-out connections together. It now skips network/broadcast on /30 and larger, refuses anything bigger than a /16, and reports closed and filtered separately.</li>
<li><strong>Timeouts need an explicit destroy.</strong> Node&apos;s <code>socket.setTimeout()</code> only emits a <code>&apos;timeout&apos;</code> event when the socket goes idle; it does not sever the connection. The <code>finish()</code> helper calls <code>socket.destroy()</code> on every path so pending sockets don&apos;t pile up at high concurrency.</li>
<li><strong>Filtered is ambiguous by design.</strong> A timeout could be an empty address, a host firewall, or a network ACL. If you need to tell those apart, compare against an ARP-based sweep of the same VLAN or DHCP leases.</li>
<li><strong>SSH banners</strong> come for free because servers normally send their identification string without waiting for the client (RFC 4253 has both sides send one), so the script collects it passively, best effort; they identify the implementation and version (<code>SSH-2.0-OpenSSH_9.6</code>), which is enough to spot an appliance running an old build. The spec allows a server to send other lines before the <code>SSH-</code> line, so the script buffers input until a complete line starting with <code>SSH-</code> arrives rather than taking the first line. RDP doesn&apos;t volunteer anything without a protocol handshake; use <code>nmap -sV -p 3389</code> when you need the service confirmed.</li>
<li><strong>Tune for the path.</strong> Concurrency of 100 against a local /24 finishes in a few seconds. Across a WAN link or a firewall that rate-limits new connections, raise <code>--timeout</code> and lower <code>--concurrency</code>, or you&apos;ll get false &quot;filtered&quot; results from connections still pending when the timer fired.</li>
<li><strong>Detectable on purpose.</strong> This completes the TCP handshake and closes it. It will show up in firewall and IDS logs, which is what you want for a sanctioned inventory sweep.</li>
<li>To track changes over time, run nmap with <code>-oX</code> on a schedule and compare runs with the <a href="https://www.techcolumnist.com/2026/03/11/node-js-discovery-diffing-two-network-scans-to-flag-new-hosts/">scan diff script</a>.</li>
</ul>
<h2>References</h2>
<ul><li><a href="https://nodejs.org/api/net.html">Node.js <code>net</code> module: <code>socket.setTimeout()</code>, <code>&apos;timeout&apos;</code> event, <code>socket.destroy()</code>, <code>net.isIPv4()</code></a></li>
<li><a href="https://www.rfc-editor.org/rfc/rfc4253.html#section-4.2">RFC 4253, section 4.2: SSH protocol version exchange</a></li>
<li><a href="https://www.rfc-editor.org/rfc/rfc3021.html">RFC 3021: using 31-bit prefixes on point-to-point links</a></li>
<li><a href="https://nmap.org/book/man-port-scanning-techniques.html">Nmap port scanning techniques (<code>-sT</code> connect scan, privileges)</a></li>
<li><a href="https://nmap.org/book/legal-issues.html">Nmap legal issues: get written authorization first</a></li>
</ul>
]]></content:encoded>
      <category>Scripts</category>
      <category>Engineering</category>
    </item>
  </channel>
</rss>
