Skip to main content

How to Setup Diagrams As Code in 5 Minutes

·2 mins

In the same vein as xaaS , we’re now seeing anything and everything As Code(TM).

Thankfully, this is one of the best examples I’ve seen since you can work in a much more declarative manner compared to having to drag around icons here and there.

Firstly, here’s the dependencies:

  • GraphViz
  • Python3
  • Pip3

Here’s a quick script for it if you’re on Ubuntu:

sudo apt-get install graphviz python3 python3-pip -y
pip3 install diagrams

When they’re installed, you then can get started on writing the code. If you’ve not written any code outside of IaC before, don’t fret. There’s not really any huge concepts to learn. Here’s a (likely now outdated) example for how this site has been setup on the backend:


#diagram.py
from diagrams import Cluster, Diagram
from diagrams.aws.compute import EC2, EC2SpotInstance
from diagrams.aws.network import ELB, CF, VPC, Route53
from diagrams.aws.storage import EFS, S3
from diagrams.aws.devtools import Codecommit
from diagrams.aws.management import Cloudwatch

with Diagram("liamhardman.cloud", show=True):
    DNS = Route53("DNS")
    CF = CF("CloudFront Distribution")
    ELB = ELB("Web LB")
    EFS = EFS("Shared Storage")
    CC = Codecommit("Code Repo")
    S3 = S3("Code Backup & Deployment")
    CW = Cloudwatch("CloudWatch Monitoring & Alerting")

    with Cluster("Web Cluster"):
        Web = [EC2("eu-west-2a"),
        EC2SpotInstance("eu-west-2b"),
        EC2SpotInstance("eu-west-2c")]

    DNS >> CF >> ELB >> Web
    Web >> EFS
    CW >> ELB
    CC >> S3 >> Web

Then, just run python3 diagram.py and voila!

The end result isn’t too shabby considering this took about 20 mins from no install at all.

The great part about this project is it’s fully open source with some great documentation as well.

What do you all think then? Are we reaching the age where documentation can be automated too? Well, keep your eyes peeled because that’s the next thing I’m looking at too.