DocumentationArchitecture Practices

AI C4 Diagrams: From Infrastructure as Code and Runtime Data

••15 min read
AI C4 Diagrams: From Infrastructure as Code and Runtime Data

Our system and deployment diagrams kept going out of date, and whenever a discussion needed them, bringing them back up to date took a lot of time. It hurt most in a meeting about the end-to-end security of our application stack. We were not sure we had modelled all the components correctly, or that they matched what was really deployed. In a security discussion, that is the whole question.

So we let Copilot, an AI assistant, draft C4 diagrams in Structurizr DSL from our infrastructure code repository. It was mostly right, and unreadable until we moved boxes by hand and used tags so each view shows only the elements and relationships that matter. Layout was the easy problem. "Mostly right" is the hard one, because you cannot tell which part is wrong without checking every arrow yourself.

This post builds the missing piece. An AI drafts the context, container and deployment diagrams from three sources. A provenance gate is a small check that fails an AI-drafted C4 diagram when any box or arrow has no traceable source, or when something that runs is not drawn.

The Airport Security Audit for AI-Drafted C4 Diagrams

An airport keeps its security plans at three scales. The airport plan shows the terminal with the passengers, the airlines and the city around it. The terminal plan shows check-in, the baggage hall and the gates. The airside plan shows which zone each of those sits in and which doors connect them. That is the C4 zoom: system context, container and deployment.

Before an audit, a drafter redraws the plans quickly from the construction file, and they look right. The auditor then applies one rule: every door and every corridor on a plan must trace to a construction drawing or a log entry, or it comes off the plan. The auditor uses three kinds of source: the construction drawings for what was built, the badge-reader logs and camera footage for which doors people really walk through, and the operations manual for what the airport intends, which may be out of date. If the logs show traffic through a staff door that no plan has, the plan is incomplete, and the door is a finding. The head of security decides which plans exist and how much each one shows.

The AI is the drafter. Infrastructure as code is the construction drawings, the running system is the badge logs, ADRs and the README are the operations manual, the provenance gate is the auditor, and the architect is the head of security.

Where it breaks: an airport is audited a few times a year, by people. An architecture model has to be checked again on every deploy, so here the auditor is code that runs on every change.

Three Sources for a C4 Diagram, Three Blind Spots

In my setup the three sources look like this, and each one is blind where another can see.

Source Tells you Cannot tell you Feeds
Kubernetes manifests What should run, with images and settings Changes applied by hand, purpose Deployment diagram
Running cluster: pods, nginx config, env vars What runs, and the real arrows between containers Intent, who uses it Container diagram
ADRs and README People, purpose, decisions Whether they still hold System context

When they disagree, runtime wins. The manifests and the documents say what we meant. Only the cluster shows what is there. We draw what runs, and we report the difference as a gap between the infrastructure as code definition and the runtime, so someone decides which of the two has to change.

Which plans exist and how much each one shows is the architect's call. A container runs code or stores data on its own. Networks, identities, load balancers, and in Kubernetes the Services, ConfigMaps and namespace, are deployment detail. Put that rule in the prompt.

The Staff Door No Plan Showed

Runtime earned its first place. Reading the nginx configuration from the running environment, we found that we had exposed an unprotected application management portal through nginx. It should at least have required authentication, or stayed internal and reachable only through the VPN.

So my bar for showing an AI-drafted diagram to a board without reading every arrow is a source for every box and every arrow. That is the provenance gate. It also runs in reverse, like the auditor reading the badge logs: whatever runs must be drawn.

Done by hand, the architect updates the diagrams before the meeting. In our new way of working, infrastructure code changes and a nightly read of the runtime environment trigger the generation.

Build the AI C4 Diagram Gate on Your Laptop

You need Docker, kind, kubectl, the .NET 10 SDK and an AI coding assistant. Everything runs on localhost, and the shop system is made up for this article.

On Windows, install the four tools with winget:

winget install --id Docker.DockerDesktop --exact
winget install --id Kubernetes.kind --exact
winget install --id Kubernetes.kubectl --exact
winget install --id Microsoft.DotNet.SDK.10 --exact

On macOS, Homebrew does the same:

brew install --cask docker-desktop
brew install kind kubectl
brew install --cask dotnet-sdk

Homebrew installs the newest .NET SDK, which is newer than the .NET 10 this walkthrough was tested on. Start Docker Desktop once before step 1, and open a new terminal so the new commands are found.

Step 1: Start the cluster and the sample system

Create a folder c4-demo with k8s and docs inside, and work from c4-demo. Save the construction drawings as k8s/shop.yaml: four workloads in a shop namespace.

apiVersion: v1
kind: Namespace
metadata:
  name: shop
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: web-config
  namespace: shop
data:
  default.conf: |
    server {
      listen 80;
      location / {
        proxy_pass http://orders-api:5678;
      }
    }
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
  namespace: shop
spec:
  selector: { matchLabels: { app: web } }
  template:
    metadata: { labels: { app: web } }
    spec:
      containers:
        - name: nginx
          image: nginx:1.29-alpine
          volumeMounts:
            - { name: config, mountPath: /etc/nginx/conf.d }
      volumes:
        - name: config
          configMap: { name: web-config }
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: orders-api
  namespace: shop
spec:
  selector: { matchLabels: { app: orders-api } }
  template:
    metadata: { labels: { app: orders-api } }
    spec:
      containers:
        - name: api
          image: hashicorp/http-echo:1.0
          args: ["-text=orders-api"]
          env:
            - { name: ORDERS_DB_HOST, value: orders-db }
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: orders-db
  namespace: shop
spec:
  selector: { matchLabels: { app: orders-db } }
  template:
    metadata: { labels: { app: orders-db } }
    spec:
      containers:
        - name: postgres
          image: postgres:17-alpine
          env:
            - { name: POSTGRES_PASSWORD, value: local-demo-only }
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: admin
  namespace: shop
spec:
  selector: { matchLabels: { app: admin } }
  template:
    metadata: { labels: { app: admin } }
    spec:
      containers:
        - name: adminer
          image: adminer:5
          env:
            - { name: ADMINER_DEFAULT_SERVER, value: orders-db }
---
apiVersion: v1
kind: Service
metadata: { name: web, namespace: shop }
spec: { selector: { app: web }, ports: [{ port: 80 }] }
---
apiVersion: v1
kind: Service
metadata: { name: orders-api, namespace: shop }
spec: { selector: { app: orders-api }, ports: [{ port: 5678 }] }
---
apiVersion: v1
kind: Service
metadata: { name: orders-db, namespace: shop }
spec: { selector: { app: orders-db }, ports: [{ port: 5432 }] }
---
apiVersion: v1
kind: Service
metadata: { name: admin, namespace: shop }
spec: { selector: { app: admin }, ports: [{ port: 8080 }] }

Create the cluster, deploy, and wait. The first run pulls four images, so give it time.

kind create cluster --name c4-demo
kubectl --context kind-c4-demo apply -f k8s/shop.yaml
kubectl --context kind-c4-demo wait --for=condition=Available deployment --all -n shop --timeout=240s

The wait prints deployment.apps/admin condition met, then the same line for orders-api, orders-db and web.

Step 2: Apply the change nobody recorded

Somebody adds an /admin/ route to the public nginx by hand and never commits it. Save this as hotfix.yaml one level up, next to the c4-demo folder and outside it. The file stands for a change that never reached the repository, so the AI must not find it: an assistant working in c4-demo could read it and cite it as a source.

apiVersion: v1
kind: ConfigMap
metadata:
  name: web-config
  namespace: shop
data:
  default.conf: |
    server {
      listen 80;
      location / {
        proxy_pass http://orders-api:5678;
      }
      location /admin/ {
        proxy_pass http://admin:8080/;
      }
    }
kubectl --context kind-c4-demo apply -f ../hotfix.yaml
kubectl --context kind-c4-demo rollout restart deployment/web -n shop
kubectl --context kind-c4-demo rollout status deployment/web -n shop

The last line is deployment "web" successfully rolled out. Forward the public entry in one terminal and call it from a second.

kubectl --context kind-c4-demo port-forward -n shop svc/web 8081:80
# in a second terminal
curl http://localhost:8081/
curl -s http://localhost:8081/admin/ | grep -o "<title>.*</title>"

In Windows PowerShell, curl is a different command that asks for a Uri instead of calling the address. Type curl.exe, and use Select-String in place of grep:

curl.exe http://localhost:8081/
curl.exe -s http://localhost:8081/admin/ | Select-String "<title>"

The first call prints orders-api. The second prints <title>Login - Adminer</title>: the admin portal's login page, reachable through the public entry. Keep the slash at the end of /admin/, because without it nginx answers with a redirect page. Stop the port-forward with Ctrl+C.

Step 3: Collect the three sources

Save the operations manual as docs/README.md and docs/adr-004.md:

# Shop

Customers place orders through the web entry. Operators manage the orders
database through the admin portal.
# ADR 004: The admin portal stays internal

## Status
Accepted

## Decision
The admin portal is reached through the VPN only. The public web entry
routes customers to the orders API and nothing else.

Then read the badge logs. nginx -T prints the full running configuration from inside the web pod:

mkdir facts
kubectl --context kind-c4-demo get deploy,svc,pods -n shop -o json > facts/runtime.json
kubectl --context kind-c4-demo exec -n shop deploy/web -- nginx -T > facts/nginx.conf

The route the repository does not have is in facts/nginx.conf:

  location / {
    proxy_pass http://orders-api:5678;
  location /admin/ {
    proxy_pass http://admin:8080/;

Step 4: Let the AI write the first draft

Give your assistant this prompt from the c4-demo folder. The first draft reads only the manifests and the documents.

Read the files in k8s/ and docs/. Write workspace.dsl in Structurizr DSL for the Shop
system, with a system context view, a container view and a deployment view.

A container is something that runs code or stores data on its own. Kubernetes
Services, ConfigMaps and the namespace are deployment detail: use them for the
deployment view and never draw them as containers.

Give every person, software system, container and relationship a property named
"source" in the form "<file>: <text copied exactly from that file>". If you cannot
quote a source for an element or a relationship, leave it out.

A container and two arrows from the result:

            web = container "Web entry" "Routes public requests." "nginx" {
                properties {
                    "source" "k8s/shop.yaml: image: nginx:1.29-alpine"
                }
            }

        web -> api "Forwards requests" {
            properties {
                "source" "k8s/shop.yaml: proxy_pass http://orders-api:5678"
            }
        }
        api -> db "Reads and writes orders" {
            properties {
                "source" "k8s/shop.yaml: name: ORDERS_DB_HOST, value: orders-db"
            }
        }

Validate, export and view it. In PowerShell, $(pwd) becomes ${PWD}.

docker run --rm -v "$(pwd):/usr/local/structurizr" structurizr/structurizr:2026.10.26 validate -workspace workspace.dsl
docker run --rm -v "$(pwd):/usr/local/structurizr" structurizr/structurizr:2026.10.26 export -workspace workspace.dsl -format json
docker run -it --rm -p 8080:8080 -v "$(pwd):/usr/local/structurizr" structurizr/structurizr:2026.10.26 local

validate prints nothing and exits with code 0. export writes workspace.json, and its last log line ends with Finished. The third command serves the local viewer at http://localhost:8080 until you press Ctrl+C. Expect what we saw with Copilot: mostly right, with layout and tags still yours to fix.

Step 5: Run the provenance gate

The gate checks that every element in workspace.json cites a file that contains its quote, then checks in reverse that every running nginx route and every Deployment is cited, by its name or by its image. Save it as gate.cs:

using System.Text.Json;
using System.Text.RegularExpressions;

var model = JsonDocument.Parse(File.ReadAllText("workspace.json")).RootElement.GetProperty("model");
var failures = new List<string>();
var evidence = new List<string>();

// Layout and quoting differ between YAML, JSON and nginx, so compare without them.
static string Flat(string text) => Regex.Replace(text, @"[\s""'{}]", "");

void Check(string what, JsonElement item)
{
    var source = item.TryGetProperty("properties", out var p) && p.TryGetProperty("source", out var s)
        ? s.GetString()! : "";
    var parts = source.Split(": ", 2);
    if (parts.Length < 2 || !File.Exists(parts[0]))
        failures.Add($"NO SOURCE   {what}");
    else if (!Flat(File.ReadAllText(parts[0])).Contains(Flat(parts[1])))
        failures.Add($"NOT FOUND   {what}: \"{parts[1]}\" is not in {parts[0]}");
    else
        evidence.Add(source);
}

void Walk(JsonElement element)
{
    var name = element.GetProperty("name").GetString()!;
    Check(name, element);
    if (element.TryGetProperty("relationships", out var relationships))
        foreach (var r in relationships.EnumerateArray())
            if (!r.TryGetProperty("linkedRelationshipId", out _))
                Check($"{name} -> {r.GetProperty("description").GetString()}", r);
    if (element.TryGetProperty("containers", out var containers))
        foreach (var container in containers.EnumerateArray())
            Walk(container);
}

foreach (var person in model.GetProperty("people").EnumerateArray()) Walk(person);
foreach (var system in model.GetProperty("softwareSystems").EnumerateArray()) Walk(system);

// The reverse check: what runs must be drawn.
foreach (Match route in Regex.Matches(File.ReadAllText("facts/nginx.conf"), @"proxy_pass\s+(\S+?)/?;"))
    if (!evidence.Any(e => e.Contains(route.Groups[1].Value)))
        failures.Add($"NOT DRAWN   the running nginx routes to {route.Groups[1].Value}");

var runtime = JsonDocument.Parse(File.ReadAllText("facts/runtime.json")).RootElement;
foreach (var item in runtime.GetProperty("items").EnumerateArray())
{
    if (item.GetProperty("kind").GetString() != "Deployment") continue;
    // A diagram may cite a Deployment by its name or by the image it runs.
    var workload = item.GetProperty("metadata").GetProperty("name").GetString()!;
    var names = item.GetProperty("spec").GetProperty("template").GetProperty("spec")
        .GetProperty("containers").EnumerateArray()
        .Select(c => c.GetProperty("image").GetString()!).Append(workload);
    if (!evidence.Any(e => names.Any(e.Contains)))
        failures.Add($"NOT DRAWN   deployment {workload} runs in the cluster");
}

failures.ForEach(Console.WriteLine);
Console.WriteLine(failures.Count == 0 ? $"PASS  {evidence.Count} sources checked" : $"FAIL  {failures.Count} problem(s)");
return failures.Count == 0 ? 0 : 1;

Run it with dotnet run gate.cs, which needs no project on .NET 10. For the first draft:

NOT DRAWN   the running nginx routes to http://admin:8080
FAIL  1 problem(s)

The draft is accurate and incomplete. A test draft with one made-up quote and one unsourced arrow adds a NOT FOUND and a NO SOURCE line and reports 3 problems. Exit code 1 on failure lets the gate stop a pipeline. Your assistant words things differently, so your output may vary, but expect the missing admin route.

Step 6: Add the runtime facts and run it again

Change the first line of the prompt and add one rule:

Read the files in k8s/, docs/ and facts/.
When the files disagree, the running system in facts/ wins: draw what runs and cite the facts file.

Regenerate, repeat the validate and export from step 4, and run the gate again. It prints PASS and the number of sources it checked: 13 in our run, more if your assistant cites more.

Look at what passed. The diagram now shows the web entry forwarding /admin/ requests to the admin portal, cited from facts/nginx.conf, while ADR 004 keeps that portal behind the VPN. The diagram is right and the system is wrong, so fix the cluster. Then tear it all down:

kind delete cluster --name c4-demo

Reading the Provenance Gate Verdict

Result Means Do this
NO SOURCE The AI drew something and cited nothing Cut it, or find a real source and regenerate
NOT FOUND The quote is not in the file it names Treat it as invented and cut it
NOT DRAWN Something runs that the diagram leaves out Draw it from facts/. If it breaks a decision, like the admin route, fix the cluster

Know the limits. The gate proves each quote exists in the named file. It cannot prove the quote means what the arrow claims, so a person still reads the sources, which are far fewer lines than the systems behind them.

Every Door on the Plan Needs a Source

  • Runtime wins. When manifests, documents and cluster disagree, draw what runs, cite where you saw it, and report the gap.
  • A source for every box and arrow. If the AI cannot quote it, it stays off the diagram.
  • Check in reverse. A diagram where every line checks out can still miss the route that matters.
  • The architect decides what each plan shows. Level, scope, layout and tags are human decisions.
  • Run it on every change. Infrastructure code changes and a nightly runtime read, so the diagram stops waiting for the next meeting.

That security meeting needed one answer: does the picture match what is deployed? A draft that cites a source for every line, and fails when something running is missing, gives you that answer before the meeting starts.

Which arrows in your current diagrams could you source today? And most importantly, if you read the running configuration of your public entry point tonight, would every route on it be in the picture?

Share this article

Enjoyed this article?

Subscribe to get more insights delivered to your inbox monthly

No spam, unsubscribe anytime.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.