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: Use when generating cloud architecture diagrams as code — creating, modifying, or reviewing infrastructure diagrams using the Python Diagrams library. Covers AWS, Azure, GCP, Kubernetes, on-premises, and SaaS provider nodes. Generates PNG/SVG architecture diagrams from Python code with Graphviz rendering.4---56# Diagrams — Architecture as Code78Generate cloud architecture diagrams programmatically using Python. Supports 15+ providers including AWS, Azure, GCP, Kubernetes, and on-premises infrastructure.910**Repository**: [github.com/mingrammer/diagrams](https://github.com/mingrammer/diagrams)1112## Prerequisites1314```bash15# Check installation16python3 -c "import diagrams; print(f'diagrams {diagrams.__version__}')" 2>/dev/null || echo "NOT INSTALLED"17dot -V 2>/dev/null || echo "Graphviz NOT INSTALLED"1819# Install if needed20pip install diagrams21# macOS: brew install graphviz22# Ubuntu: apt-get install graphviz23```2425## Decision Matrix2627| Need | Approach | Example |28|------|----------|---------|29| Simple 3-tier architecture | Single Diagram context | `with Diagram("Web App"):` |30| Grouped components | Cluster context | `with Cluster("VPC"):` |31| Multiple environments | Nested Clusters | `with Cluster("Prod"): with Cluster("AZ-1"):` |32| Data flow direction | Edge operators | `web >> cache >> db` |33| Bidirectional flow | Double edge | `web >> Edge(label="gRPC") << api` |34| Multiple outputs | Edge from list | `[svc1, svc2] >> lb` |35| Custom styling | Edge attributes | `Edge(color="red", style="dashed")` |3637## Phase 1 — Discovery3839Identify what architecture to diagram:4041```python42#!/usr/bin/env python343"""List all available node providers and categories."""44import diagrams45from diagrams import aws, azure, gcp, k8s, onprem, saas, generic, programming, c44647# List available providers48providers = {49 "aws": dir(aws),50 "azure": dir(azure),51 "gcp": dir(gcp),52 "k8s": dir(k8s),53 "onprem": dir(onprem),54 "saas": dir(saas),55 "generic": dir(generic),56 "programming": dir(programming),57 "c4": dir(c4),58}5960for provider, modules in providers.items():61 categories = [m for m in modules if not m.startswith("_")]62 print(f"{provider}: {', '.join(categories[:10])}...")63```6465## Phase 2 — Generate Diagram6667### AWS Architecture Example6869```python70#!/usr/bin/env python371from diagrams import Diagram, Cluster, Edge72from diagrams.aws.compute import ECS, Lambda73from diagrams.aws.database import RDS, ElastiCache74from diagrams.aws.network import ELB, CloudFront, Route5375from diagrams.aws.storage import S376from diagrams.aws.integration import SQS, SNS77from diagrams.aws.security import WAF7879with Diagram("Production Architecture", show=False, direction="LR"):80 dns = Route53("DNS")81 cdn = CloudFront("CDN")82 waf = WAF("WAF")8384 with Cluster("VPC"):85 lb = ELB("ALB")8687 with Cluster("Application Tier"):88 svc = [ECS("service-1"), ECS("service-2"), ECS("service-3")]8990 with Cluster("Data Tier"):91 db = RDS("PostgreSQL")92 cache = ElastiCache("Redis")9394 with Cluster("Async Processing"):95 queue = SQS("task-queue")96 worker = Lambda("processor")97 events = SNS("notifications")9899 storage = S3("assets")100101 dns >> cdn >> waf >> lb >> svc102 svc >> cache >> db103 svc >> queue >> worker >> events104 cdn >> storage105```106107### Kubernetes Architecture Example108109```python110#!/usr/bin/env python3111from diagrams import Diagram, Cluster112from diagrams.k8s.compute import Pod, Deploy, RS113from diagrams.k8s.network import Ingress, Service114from diagrams.k8s.storage import PV, PVC115from diagrams.k8s.podconfig import ConfigMap, Secret116117with Diagram("K8s Deployment", show=False):118 ingress = Ingress("ingress")119120 with Cluster("Namespace: production"):121 svc = Service("api-svc")122123 with Cluster("Deployment"):124 pods = [Pod("pod-1"), Pod("pod-2"), Pod("pod-3")]125126 config = ConfigMap("config")127 secret = Secret("credentials")128 pvc = PVC("data-vol")129130 pv = PV("persistent-volume")131132 ingress >> svc >> pods133 [config, secret] >> pods134 pvc >> pv135```136137### Multi-Cloud / Hybrid Example138139```python140#!/usr/bin/env python3141from diagrams import Diagram, Cluster, Edge142from diagrams.aws.compute import ECS143from diagrams.gcp.compute import GKE144from diagrams.azure.compute import AKS145from diagrams.onprem.network import Nginx146from diagrams.onprem.monitoring import Prometheus, Grafana147from diagrams.generic.network import Firewall148149with Diagram("Multi-Cloud Architecture", show=False, direction="TB"):150 with Cluster("On-Premises"):151 lb = Nginx("Load Balancer")152 fw = Firewall("Firewall")153 monitoring = [Prometheus("metrics"), Grafana("dashboards")]154155 with Cluster("AWS"):156 aws_app = ECS("api-service")157158 with Cluster("GCP"):159 gcp_app = GKE("ml-pipeline")160161 with Cluster("Azure"):162 az_app = AKS("data-service")163164 fw >> lb >> [aws_app, gcp_app, az_app]165 [aws_app, gcp_app, az_app] >> Edge(style="dashed") >> monitoring[0]166```167168## Available Providers169170| Provider | Import | Key Categories |171|----------|--------|----------------|172| AWS | `diagrams.aws` | compute, database, network, storage, security, integration, analytics, ml |173| Azure | `diagrams.azure` | compute, database, network, storage, security, integration, analytics, ml |174| GCP | `diagrams.gcp` | compute, database, network, storage, security, analytics, ml |175| Kubernetes | `diagrams.k8s` | compute, network, storage, podconfig, rbac, ecosystem |176| On-Premises | `diagrams.onprem` | compute, database, network, monitoring, queue, ci, container |177| SaaS | `diagrams.saas` | alerting, analytics, chat, identity, logging, media, social |178| Generic | `diagrams.generic` | compute, database, network, os, storage, place |179| Programming | `diagrams.programming` | framework, language, runtime |180| C4 | `diagrams.c4` | SystemBoundary, Container, Database, Person, Relationship |181182## Diagram Parameters183184| Parameter | Default | Description |185|-----------|---------|-------------|186| `name` | required | Diagram title (also used as filename) |187| `show` | `True` | Auto-open after generation. Set `False` for scripts |188| `direction` | `"LR"` | Layout: `LR`, `RL`, `TB`, `BT` |189| `filename` | from name | Override output filename |190| `outformat` | `"png"` | `png`, `jpg`, `svg`, `pdf`, `dot` |191| `graph_attr` | `{}` | Graphviz graph attributes |192| `node_attr` | `{}` | Graphviz node attributes |193| `edge_attr` | `{}` | Graphviz edge attributes |194195## Anti-Hallucination Rules196197- **NEVER** import a node class without verifying it exists — use `dir(diagrams.aws.compute)` to check198- **NEVER** assume provider category names — they differ across providers (e.g., `aws.integration` vs `gcp.api`)199- **ALWAYS** set `show=False` in scripts/automation to prevent auto-opening200- **ALWAYS** verify Graphviz is installed before generating — diagrams silently fails without it201202## Output Format203204```205Diagrams Report206═══════════════207Generated: [filename].png208Provider: [aws/gcp/azure/k8s/multi-cloud]209Components: [count] nodes, [count] clusters210Layout: [direction]211212File: [absolute path to generated image]213```214215## Common Pitfalls216217- **Missing Graphviz**: `pip install diagrams` does NOT install Graphviz — install separately218- **show=True in CI**: Will fail in headless environments — always use `show=False`219- **Large diagrams**: Use `direction="LR"` and clusters to keep readable220- **Node naming**: Node labels appear in diagram — keep short and descriptive221- **Edge direction**: `>>` means left-to-right flow; `<<` means reverse; order matters