Drawing infrastructure from Terraform state with F#

Every infrastructure diagram I have ever maintained was wrong within a fortnight of drawing it. Subnets get renumbered, instances get replaced, and the picture pinned to the wiki quietly stops describing what is actually running. Terraform state is the artefact that already knows the truth, so using F# to generate infrastructure diagrams from Terraform state removes the hand-drawn step entirely: you point a program at a tfstate file and get a picture you can regenerate whenever the estate changes. Learn more about Msi Afterburnerでフレームレートキャップを設定して消費電力を抑える方法と遅延への影響.

The approach I use is straightforward — deserialise the state into F# types, turn resources and their dependencies into a graph, render that graph as SVG for a wiki page or a pull request, and wire the whole thing into a pipeline so the diagram ages alongside the code. I have written comparable tooling in Python and PowerShell before, but F# suits the job because pattern matching over a resource union keeps the awkward parts readable without a stack of dictionary lookups.

Why the state file beats a hand-drawn picture

A Terraform state file lists every managed resource with a stable address, a type, a provider and its attributes, plus the dependency metadata recorded when the resource was created. That is more detail than a plan gives you, and it reflects reality rather than intention, which makes it a far better source for a diagram than anything a human sketches in a vector editor.

The payoff shows up when the estate drifts. Orphaned resources, resources that survived a module rename and resources whose tags changed all appear in the state, and each of them shifts a node or an edge in the generated picture. A diagram regenerated from state makes that churn visible in a code review, instead of leaving it to be discovered during an incident at three in the morning.

One caution belongs here: state files contain sensitive values. Database passwords, private key material and API tokens can sit inside resource attributes, so the generator should filter attributes before rendering and never commit raw state. In an ACSC Essential Eight-aligned environment, treat the state file with the same care as the credentials it holds.

Reading Terraform state in F#

Modern state is JSON, version 4 by default, with a top-level resources array where each entry carries mode, type, name, provider and usually instances, alongside an outputs block. Resources living inside a module appear with a prefixed address such as module.network.aws_subnet.private, which is enough to group nodes without parsing the configuration at all.

F# gives you two useful tools here: records for the fields you care about, and a discriminated union for the resource categories you want to distinguish. Newtonsoft.Json handles F# records and unions with far less ceremony than the alternative, while System.Text.Json works well if you would rather write your own converters.

type Resource =
    | Compute of Details
    | Network of Details
    | Data of Details
    | Unknown of Details

and Details =
    { Address: string
      Type: string
      Region: string option
      DependsOn: string list }

Run it as a dotnet fsi script while prototyping, then promote it to a console application or a dotnet tool once it settles. Keep the raw JsonDocument around as well: the strongly typed model captures what you render, and the raw document answers the occasional question about an attribute you never thought to model.

Turning resources into a dependency graph

Explicit dependencies are recorded in the state's dependency metadata, and implicit ones are implied by attribute references, so a graph built purely from depends_on misses plenty of ordering. I build the adjacency map from the typed resources, key nodes by address, and add edges for both explicit and inferred relationships so the picture shows how traffic and lifecycle actually flow.

Ordering matters more than it looks. A topological sort gives a stable ranking for the renderer, and cycles occasionally appear when provider requirements feed back into a resource, so a depth-first traversal with a visited set is safer than assuming the graph is a clean tree. Grouping by module, VPC and availability zone turns a wall of boxes into something a person can read in a minute.

Immutable maps make this code pleasant to write. A Map<string, Resource> for the nodes and a Map<string, string list> for the edges keep the transformation pure, which means you can test the graph against a fixture state file and get the same answer every time the pipeline runs.

Rendering something people will actually read

Graphviz is the obvious target: emit DOT, run dot -Tsvg, and you have a crisp diagram that scales and diffs well in a repository. Mermaid is the better fit when the output has to live inside a wiki page, and PlantUML works when your audience already reads UML. I usually generate DOT and keep a Mermaid variant for the wiki, skipping low-signal resources such as individual IAM policies and route tables unless someone asks for them.

Layout is a design decision, not a default. Direction, cluster boundaries and colour coding all change who can use the result, and a picture listing forty near-identical boxes teaches nobody anything. The useful version shows the tiers, the network boundaries and the region each resource actually lives in.

Determinism pays for itself later. Sort nodes by address before emitting them and the generated SVG changes only when the estate changes, so a diff in a pull request tells you what moved rather than showing that the tool reordered everything.

Wiring the generator into a pipeline

The generator works best as a scheduled job that runs after an apply and again on a nightly refresh. Pull a refreshed state, run the tool, commit the SVG, and publish a short summary of what appeared or disappeared. Remote state backends such as S3 with a DynamoDB lock, or Terraform Cloud, make this straightforward because the pipeline can fetch state without a human touching the workstation.

A nightly run also catches drift that no pull request would reveal. When the estate changes without a commit — a console fix, a manual import, a module upgrade applied by hand — the regenerated diagram differs, and that difference deserves a notification rather than a surprise later.

Observability and diagrams answer different questions. A dashboard tells you whether a service is healthy right now, while the diagram tells you what exists and how it is wired together; I wrote about building a monitoring dashboard with Flask previously, and the two sit comfortably side by side on an operations wiki page.

Fitting this into an Australian infrastructure reality

Australian estates spread across Sydney (ap-southeast-2), Melbourne (ap-southeast-4), Brisbane (ap-southeast-3) and Perth (ap-southeast-5), and the availability zone suffixes matter when you are describing redundancy. A diagram naming the region and zone for each subnet tells an on-call engineer far more than a generic cloud box, particularly for teams supporting a footprint with a genuine interstate latency budget.

Home offices add their own constraints. A fixed-line NBN connection and Australian electricity prices make an always-on workstation a real cost, so if you host dashboards on a gaming box, notes on Afterburner frame caps are worth reading before you chase millisecond gains the network will eat anyway.

Scheduling deserves one more local detail: daylight saving moves clocks in most states between October and April, so a job pinned to a UTC hour drifts against local working hours twice a year unless that is deliberate. Keeping a dated diagram in the same repository as the Terraform code also leaves an audit trail that is easier to defend than a picture on a whiteboard in a Sydney office.

A pragmatic build order for your own state file

Starting small keeps the first version honest. Read one non-production state file, print what you find, and only then decide what the picture should emphasise — the order below has kept the work predictable for me.

  • Begin with a read-only pass that prints resource counts by type before any rendering happens.
  • Model a small union of categories and route unknown resource types to a fallback node instead of failing the run.
  • Filter sensitive attributes early and keep secrets out of the rendered output entirely.
  • Emit DOT first, then move to SVG once the layout is stable, with deterministic ordering so diffs stay readable.
  • Run the generator on a schedule as well as on pull requests, and treat a changed diagram as a review signal in its own right.

Once the generator is stable, the diagram becomes the artefact that starts conversations. Teams notice a missing route or an unexpected cross-region link far earlier when the picture updates with the code, and the arguments shift from whether something is true to what should change next.

The quickest way to see the value is to point the generator at a single workspace, let it render, and compare the result against the last picture someone drew by hand. If you would rather not build the generator yourself, I take on independent infrastructure consulting engagements covering infrastructure planning, cloud migration and systems architecture, and a small pilot on one workspace is a sensible first scope. Send over the state file you want diagrammed and we can settle the shape of the first version together.

Experience

Information Technology Consulting

Independent Practice

Provides IT consulting services focused on infrastructure planning, cloud migration strategy, and systems architecture. Engagements draw on years of hands-on sysadmin and development experience across Linux, Windows, and hybrid environments.

K9 Search & Rescue Volunteer

Ongoing

Active participant in K9 Search & Rescue operations, combining technical logistics skills with field support for canine search teams.

Karl Katzke's Blog

October 2006 – May 2014

Published a long-running personal technology blog covering cloud vs. in-house infrastructure, F# and Mono on OSX, hardware vendor critiques, RAID card performance analysis, and sysadmin storytelling. Notable posts include "When Sysadmins Ruled the Earth" (May 15, 2014) and "Getting Started with F# and Mono on OSX" (December 22, 2012).

Credentials

A small badge icon with a shield shape in muted blue tones on a light background

Systems Administration

Deep experience with Linux (RHEL, SLES, CentOS), high-availability clusters, and STONITH configurations.

A small badge icon with a gear shape in muted blue tones on a light background

Cloud Infrastructure

Practical knowledge of AWS EC2, reserved instances, and cost analysis for cloud vs. on-premises deployments.

A small badge icon with a code symbol in muted blue tones on a light background

Development

Proficient in F#, PHP (Symfony), and cross-platform tooling including Mono and MonoDevelop on OSX.

Studies

F# & Functional Programming

Self-directed, 2012

Explored strongly typed functional programming with F# on OSX using the Mono runtime. Published a detailed getting-started guide covering toolchain setup and cross-platform game development research.

High-Availability & Cluster Management

Professional Development, 2009

Configured and documented crm_mon email alerting for STONITH events on SLES11-HAE clusters, integrating with Nagios monitoring for production environments.

Hardware & Storage Performance

Ongoing

Conducted hands-on benchmarking of SATA/SAS RAID controllers including HighPoint RocketRaid 2740 and LSI/SuperMicro AOC-USASLP2-H8iR, comparing against software RAID configurations.

Skills

A small icon representing a server with clean geometric lines in slate blue

Linux Administration

RHEL, SLES, CentOS — package management, kernel tuning, HA clustering, and monitoring integration.

A small icon representing a cloud shape with clean geometric lines in slate blue

Cloud Architecture

AWS EC2, reserved-instance planning, cost modeling, and hybrid infrastructure strategy.

A small icon representing code brackets with clean geometric lines in slate blue

F# & .NET/Mono

Functional programming on OSX, MonoDevelop toolchain, and cross-platform game-dev exploration.

A small icon representing a database cylinder with clean geometric lines in slate blue

PHP & Symfony

Web application development with the Symfony framework and the broader PHP ecosystem.

A small icon representing a storage drive with clean geometric lines in slate blue

Storage & RAID

SATA/SAS controller evaluation, md RAID configuration, and performance benchmarking.

A small icon representing a shield with clean geometric lines in slate blue

High Availability

Pacemaker, STONITH, crm_mon alerting, and Nagios integration for production cluster monitoring.