Diagrams — Architecture as Code
Generate cloud architecture diagrams programmatically using Python. Supports 15+ providers including AWS, Azure, GCP, Kubernetes, and on-premises infrastructure.
Repository: github.com/mingrammer/diagrams
Prerequisites
# Check installation
python3 -c "import diagrams; print(f'diagrams {diagrams.__version__}')" 2>/dev/null || echo "NOT INSTALLED"
dot -V 2>/dev/null || echo "Graphviz NOT INSTALLED"
# Install if needed
pip install diagrams
# macOS: brew install graphviz
# Ubuntu: apt-get install graphviz
Decision Matrix
| Need |
Approach |
Example |
| Simple 3-tier architecture |
Single Diagram context |
with Diagram("Web App"): |
| Grouped components |
Cluster context |
with Cluster("VPC"): |
| Multiple environments |
Nested Clusters |
with Cluster("Prod"): with Cluster("AZ-1"): |
| Data flow direction |
Edge operators |
web >> cache >> db |
| Bidirectional flow |
Double edge |
web >> Edge(label="gRPC") << api |
| Multiple outputs |
Edge from list |
[svc1, svc2] >> lb |
| Custom styling |
Edge attributes |
Edge(color="red", style="dashed") |
Phase 1 — Discovery
Identify what architecture to diagram:
#!/usr/bin/env python3
"""List all available node providers and categories."""
import diagrams
from diagrams import aws, azure, gcp, k8s, onprem, saas, generic, programming, c4
# List available providers
providers = {
"aws": dir(aws),
"azure": dir(azure),
"gcp": dir(gcp),
"k8s": dir(k8s),
"onprem": dir(onprem),
"saas": dir(saas),
"generic": dir(generic),
"programming": dir(programming),
"c4": dir(c4),
}
for provider, modules in providers.items():
categories = [m for m in modules if not m.startswith("_")]
print(f"{provider}: {', '.join(categories[:10])}...")
Phase 2 — Generate Diagram
AWS Architecture Example
#!/usr/bin/env python3
from diagrams import Diagram, Cluster, Edge
from diagrams.aws.compute import ECS, Lambda
from diagrams.aws.database import RDS, ElastiCache
from diagrams.aws.network import ELB, CloudFront, Route53
from diagrams.aws.storage import S3
from diagrams.aws.integration import SQS, SNS
from diagrams.aws.security import WAF
with Diagram("Production Architecture", show=False, direction="LR"):
dns = Route53("DNS")
cdn = CloudFront("CDN")
waf = WAF("WAF")
with Cluster("VPC"):
lb = ELB("ALB")
with Cluster("Application Tier"):
svc = [ECS("service-1"), ECS("service-2"), ECS("service-3")]
with Cluster("Data Tier"):
db = RDS("PostgreSQL")
cache = ElastiCache("Redis")
with Cluster("Async Processing"):
queue = SQS("task-queue")
worker = Lambda("processor")
events = SNS("notifications")
storage = S3("assets")
dns >> cdn >> waf >> lb >> svc
svc >> cache >> db
svc >> queue >> worker >> events
cdn >> storage
Kubernetes Architecture Example
#!/usr/bin/env python3
from diagrams import Diagram, Cluster
from diagrams.k8s.compute import Pod, Deploy, RS
from diagrams.k8s.network import Ingress, Service
from diagrams.k8s.storage import PV, PVC
from diagrams.k8s.podconfig import ConfigMap, Secret
with Diagram("K8s Deployment", show=False):
ingress = Ingress("ingress")
with Cluster("Namespace: production"):
svc = Service("api-svc")
with Cluster("Deployment"):
pods = [Pod("pod-1"), Pod("pod-2"), Pod("pod-3")]
config = ConfigMap("config")
secret = Secret("credentials")
pvc = PVC("data-vol")
pv = PV("persistent-volume")
ingress >> svc >> pods
[config, secret] >> pods
pvc >> pv
Multi-Cloud / Hybrid Example
#!/usr/bin/env python3
from diagrams import Diagram, Cluster, Edge
from diagrams.aws.compute import ECS
from diagrams.gcp.compute import GKE
from diagrams.azure.compute import AKS
from diagrams.onprem.network import Nginx
from diagrams.onprem.monitoring import Prometheus, Grafana
from diagrams.generic.network import Firewall
with Diagram("Multi-Cloud Architecture", show=False, direction="TB"):
with Cluster("On-Premises"):
lb = Nginx("Load Balancer")
fw = Firewall("Firewall")
monitoring = [Prometheus("metrics"), Grafana("dashboards")]
with Cluster("AWS"):
aws_app = ECS("api-service")
with Cluster("GCP"):
gcp_app = GKE("ml-pipeline")
with Cluster("Azure"):
az_app = AKS("data-service")
fw >> lb >> [aws_app, gcp_app, az_app]
[aws_app, gcp_app, az_app] >> Edge(style="dashed") >> monitoring[0]
Available Providers
| Provider |
Import |
Key Categories |
| AWS |
diagrams.aws |
compute, database, network, storage, security, integration, analytics, ml |
| Azure |
diagrams.azure |
compute, database, network, storage, security, integration, analytics, ml |
| GCP |
diagrams.gcp |
compute, database, network, storage, security, analytics, ml |
| Kubernetes |
diagrams.k8s |
compute, network, storage, podconfig, rbac, ecosystem |
| On-Premises |
diagrams.onprem |
compute, database, network, monitoring, queue, ci, container |
| SaaS |
diagrams.saas |
alerting, analytics, chat, identity, logging, media, social |
| Generic |
diagrams.generic |
compute, database, network, os, storage, place |
| Programming |
diagrams.programming |
framework, language, runtime |
| C4 |
diagrams.c4 |
SystemBoundary, Container, Database, Person, Relationship |
Diagram Parameters
| Parameter |
Default |
Description |
name |
required |
Diagram title (also used as filename) |
show |
True |
Auto-open after generation. Set False for scripts |
direction |
"LR" |
Layout: LR, RL, TB, BT |
filename |
from name |
Override output filename |
outformat |
"png" |
png, jpg, svg, pdf, dot |
graph_attr |
{} |
Graphviz graph attributes |
node_attr |
{} |
Graphviz node attributes |
edge_attr |
{} |
Graphviz edge attributes |
Anti-Hallucination Rules
- NEVER import a node class without verifying it exists — use
dir(diagrams.aws.compute) to check
- NEVER assume provider category names — they differ across providers (e.g.,
aws.integration vs gcp.api)
- ALWAYS set
show=False in scripts/automation to prevent auto-opening
- ALWAYS verify Graphviz is installed before generating — diagrams silently fails without it
Output Format
Diagrams Report
═══════════════
Generated: [filename].png
Provider: [aws/gcp/azure/k8s/multi-cloud]
Components: [count] nodes, [count] clusters
Layout: [direction]
File: [absolute path to generated image]
Common Pitfalls
- Missing Graphviz:
pip install diagrams does NOT install Graphviz — install separately
- show=True in CI: Will fail in headless environments — always use
show=False
- Large diagrams: Use
direction="LR" and clusters to keep readable
- Node naming: Node labels appear in diagram — keep short and descriptive
- Edge direction:
>> means left-to-right flow; << means reverse; order matters
1---2name: managing-diagrams3description: |4 Use when generating cloud architecture diagrams as code — creating, modifying,5 or reviewing infrastructure diagrams using the Python Diagrams library.6 Covers AWS, Azure, GCP, Kubernetes, on-premises, and SaaS provider nodes.7 Generates PNG/SVG architecture diagrams from Python code with Graphviz rendering.8connection_type: diagrams9preload: false10metadata:11 source: https://skillmd.com/skills/cloudthinker-ai/managing-diagrams12---1314# Diagrams — Architecture as Code1516Generate cloud architecture diagrams programmatically using Python. Supports 15+ providers including AWS, Azure, GCP, Kubernetes, and on-premises infrastructure.1718**Repository**: [github.com/mingrammer/diagrams](https://github.com/mingrammer/diagrams)1920## Prerequisites2122```bash23# Check installation24python3 -c "import diagrams; print(f'diagrams {diagrams.__version__}')" 2>/dev/null || echo "NOT INSTALLED"25dot -V 2>/dev/null || echo "Graphviz NOT INSTALLED"2627# Install if needed28pip install diagrams29# macOS: brew install graphviz30# Ubuntu: apt-get install graphviz31```3233## Decision Matrix3435| Need | Approach | Example |36|------|----------|---------|37| Simple 3-tier architecture | Single Diagram context | `with Diagram("Web App"):` |38| Grouped components | Cluster context | `with Cluster("VPC"):` |39| Multiple environments | Nested Clusters | `with Cluster("Prod"): with Cluster("AZ-1"):` |40| Data flow direction | Edge operators | `web >> cache >> db` |41| Bidirectional flow | Double edge | `web >> Edge(label="gRPC") << api` |42| Multiple outputs | Edge from list | `[svc1, svc2] >> lb` |43| Custom styling | Edge attributes | `Edge(color="red", style="dashed")` |4445## Phase 1 — Discovery4647Identify what architecture to diagram:4849```python50#!/usr/bin/env python351"""List all available node providers and categories."""52import diagrams53from diagrams import aws, azure, gcp, k8s, onprem, saas, generic, programming, c45455# List available providers56providers = {57 "aws": dir(aws),58 "azure": dir(azure),59 "gcp": dir(gcp),60 "k8s": dir(k8s),61 "onprem": dir(onprem),62 "saas": dir(saas),63 "generic": dir(generic),64 "programming": dir(programming),65 "c4": dir(c4),66}6768for provider, modules in providers.items():69 categories = [m for m in modules if not m.startswith("_")]70 print(f"{provider}: {', '.join(categories[:10])}...")71```7273## Phase 2 — Generate Diagram7475### AWS Architecture Example7677```python78#!/usr/bin/env python379from diagrams import Diagram, Cluster, Edge80from diagrams.aws.compute import ECS, Lambda81from diagrams.aws.database import RDS, ElastiCache82from diagrams.aws.network import ELB, CloudFront, Route5383from diagrams.aws.storage import S384from diagrams.aws.integration import SQS, SNS85from diagrams.aws.security import WAF8687with Diagram("Production Architecture", show=False, direction="LR"):88 dns = Route53("DNS")89 cdn = CloudFront("CDN")90 waf = WAF("WAF")9192 with Cluster("VPC"):93 lb = ELB("ALB")9495 with Cluster("Application Tier"):96 svc = [ECS("service-1"), ECS("service-2"), ECS("service-3")]9798 with Cluster("Data Tier"):99 db = RDS("PostgreSQL")100 cache = ElastiCache("Redis")101102 with Cluster("Async Processing"):103 queue = SQS("task-queue")104 worker = Lambda("processor")105 events = SNS("notifications")106107 storage = S3("assets")108109 dns >> cdn >> waf >> lb >> svc110 svc >> cache >> db111 svc >> queue >> worker >> events112 cdn >> storage113```114115### Kubernetes Architecture Example116117```python118#!/usr/bin/env python3119from diagrams import Diagram, Cluster120from diagrams.k8s.compute import Pod, Deploy, RS121from diagrams.k8s.network import Ingress, Service122from diagrams.k8s.storage import PV, PVC123from diagrams.k8s.podconfig import ConfigMap, Secret124125with Diagram("K8s Deployment", show=False):126 ingress = Ingress("ingress")127128 with Cluster("Namespace: production"):129 svc = Service("api-svc")130131 with Cluster("Deployment"):132 pods = [Pod("pod-1"), Pod("pod-2"), Pod("pod-3")]133134 config = ConfigMap("config")135 secret = Secret("credentials")136 pvc = PVC("data-vol")137138 pv = PV("persistent-volume")139140 ingress >> svc >> pods141 [config, secret] >> pods142 pvc >> pv143```144145### Multi-Cloud / Hybrid Example146147```python148#!/usr/bin/env python3149from diagrams import Diagram, Cluster, Edge150from diagrams.aws.compute import ECS151from diagrams.gcp.compute import GKE152from diagrams.azure.compute import AKS153from diagrams.onprem.network import Nginx154from diagrams.onprem.monitoring import Prometheus, Grafana155from diagrams.generic.network import Firewall156157with Diagram("Multi-Cloud Architecture", show=False, direction="TB"):158 with Cluster("On-Premises"):159 lb = Nginx("Load Balancer")160 fw = Firewall("Firewall")161 monitoring = [Prometheus("metrics"), Grafana("dashboards")]162163 with Cluster("AWS"):164 aws_app = ECS("api-service")165166 with Cluster("GCP"):167 gcp_app = GKE("ml-pipeline")168169 with Cluster("Azure"):170 az_app = AKS("data-service")171172 fw >> lb >> [aws_app, gcp_app, az_app]173 [aws_app, gcp_app, az_app] >> Edge(style="dashed") >> monitoring[0]174```175176## Available Providers177178| Provider | Import | Key Categories |179|----------|--------|----------------|180| AWS | `diagrams.aws` | compute, database, network, storage, security, integration, analytics, ml |181| Azure | `diagrams.azure` | compute, database, network, storage, security, integration, analytics, ml |182| GCP | `diagrams.gcp` | compute, database, network, storage, security, analytics, ml |183| Kubernetes | `diagrams.k8s` | compute, network, storage, podconfig, rbac, ecosystem |184| On-Premises | `diagrams.onprem` | compute, database, network, monitoring, queue, ci, container |185| SaaS | `diagrams.saas` | alerting, analytics, chat, identity, logging, media, social |186| Generic | `diagrams.generic` | compute, database, network, os, storage, place |187| Programming | `diagrams.programming` | framework, language, runtime |188| C4 | `diagrams.c4` | SystemBoundary, Container, Database, Person, Relationship |189190## Diagram Parameters191192| Parameter | Default | Description |193|-----------|---------|-------------|194| `name` | required | Diagram title (also used as filename) |195| `show` | `True` | Auto-open after generation. Set `False` for scripts |196| `direction` | `"LR"` | Layout: `LR`, `RL`, `TB`, `BT` |197| `filename` | from name | Override output filename |198| `outformat` | `"png"` | `png`, `jpg`, `svg`, `pdf`, `dot` |199| `graph_attr` | `{}` | Graphviz graph attributes |200| `node_attr` | `{}` | Graphviz node attributes |201| `edge_attr` | `{}` | Graphviz edge attributes |202203## Anti-Hallucination Rules204205- **NEVER** import a node class without verifying it exists — use `dir(diagrams.aws.compute)` to check206- **NEVER** assume provider category names — they differ across providers (e.g., `aws.integration` vs `gcp.api`)207- **ALWAYS** set `show=False` in scripts/automation to prevent auto-opening208- **ALWAYS** verify Graphviz is installed before generating — diagrams silently fails without it209210## Output Format211212```213Diagrams Report214═══════════════215Generated: [filename].png216Provider: [aws/gcp/azure/k8s/multi-cloud]217Components: [count] nodes, [count] clusters218Layout: [direction]219220File: [absolute path to generated image]221```222223## Common Pitfalls224225- **Missing Graphviz**: `pip install diagrams` does NOT install Graphviz — install separately226- **show=True in CI**: Will fail in headless environments — always use `show=False`227- **Large diagrams**: Use `direction="LR"` and clusters to keep readable228- **Node naming**: Node labels appear in diagram — keep short and descriptive229- **Edge direction**: `>>` means left-to-right flow; `<<` means reverse; order matters