Diagrams as Code: The Complete How-to-Use Guide

Written By

Anthony Neto

We're seeing more and more tools that enable you to create software architecture and other Diagrams as Code. The main benefit of using this concept is that majority of the Diagrams as Code tools can be scripted and integrated into a built pipeline for generating automatic documentation. The other benefit responsible for the growing use of Fiagrams as code to create software architecture is that it enables the use of text-based tooling, which most software developers already use. Furthermore, text is easily version controllable and diff’able.

Table of Contents

What is Diagrams as Code?

In early 2020, Korean developer MinJae Kwon decided to create Diagrams. Diagrams allows you to draw cloud system architecture in Python code, allowing you to track your Diagram in any SCM. It supports major providers such as AWS, Azure, GCP, Kubernetes, OpenStack, Oracle Cloud, etc. but support drawing on-premise infrastructure as well.

How to Install Diagrams

Requirement: Python 3.6 or higher

Depending on your environment, run one of those commands below:

    # using Homebrew for macOS users$
  brew install graphviz
  # using pip (pip3)
  $ pip install diagrams
  # using pipenv
  $ pipenv install diagrams
  # using poetry
  $ poetry add diagrams

How to Use Diagrams

You must import the necessary modules you want to add to your diagrams. They are called Nodes. They represent a node or system component. Nodes are composed of three parts: Provider, Resource type, Name.

You can import OnPrem, AWS, Azure, GCP, Kubernetes nodes, and more.  If you aren't able to find something, you could always use this custom module.

  from import LoadBalancing

In the above example, the LoadBalancing is a node of the Network resource type provided by the GCP provider.

Custom Graphviz dot attributes options are supported. graph_attr note_attr and edge_attr can be used.

Reference link:

  graph_attr = {
    "layout": "dot",
    "concentrate": "true",
    "compound": "true",
    "splines": "spline",

Diagram represents a global diagram context.

  with Diagram("Client to Application Flow", show=False, graph_attr=graph_attr):

show=False Will disable the automatic file opening when you generate the diagram.

Data Flow and how to connect nodes together:

>> Connect nodes in the left to the right direction.

<< Connect nodes in right to left direction.

- Connect nodes in no direction. Undirected.

You can change the data flow direction with the direction parameter. Default is LR. (Left to Right)

  from diagrams import Diagram
from import EC2
from import RDS
from import ELB
from import S3

with Diagram("Web Services", show=False):
    ELB("lb") >> EC2("web") >> RDS("userdb") >> S3("store")
    ELB("lb") >> EC2("web") >> RDS("userdb") << EC2("stat")
    (ELB("lb") >> EC2("web")) - EC2("web") >> RDS("userdb")
Diagram as Code Data Flow Main Chart
  from diagrams import Diagram
from import EC2
from import RDS
from import ELB

with Diagram("Workers", show=False, direction="TB"):
    lb = ELB("lb")
    db = RDS("events")
    lb >> EC2("worker1") >> db
    lb >> EC2("worker2") >> db
    lb >> EC2("worker3") >> db
    lb >> EC2("worker4") >> db
    lb >> EC2("worker5") >> d
Diagram as Code Data Flow Chart

Clusters allows you to group the nodes in an isolated group. You can create a cluster context with Cluster class. And you can also connect the nodes in a cluster to other nodes outside a cluster. There is no depth limit of nesting so that you can imagine the possibilities.

  from diagrams import Cluster, Diagram, Node, Edge
from diagrams.k8s.compute import Pod
from import Ing
from import LoadBalancing
from import Nginx

with Diagram("Cluster nesting", show=False):

    gcp_lb = LoadBalancing("GCP LB")

    with Cluster("Kubernetes"):

        with Cluster("Nginx"):
            nginx= Nginx("")

        with Cluster("MyApp"):
            myapp_ing = Ing("")
            with Cluster("Pods"):
                myapp_pods = Pod("myapp")

        with Cluster("MySQL"):
            myapp_db = Pod("myapp-db")

    gcp_lb >> Edge(headport="c", tailport="c", minlen="1", lhead='cluster_Kubernetes') >> nginx
    nginx >> Edge(headport="c", tailport="c", minlen="1", lhead='cluster_MyApp') >> myapp_ing >> Edge(headport="c", tailport="c", minlen="1", lhead='cluster_MyApp pods') >> myapp_pods >> myapp_db
Diagrams as Code Cluster Flow Main View

Edges represent a link between Nodes. It contains three attributes: label, color, and style.

Custom node

We usually import icons externally hosted so they can be accessed when we generate the diagrams.

  from diagrams import Cluster, Diagram, Node, Edge
from diagrams.custom import Custom
from urllib.request import urlretrieve

with Diagram("Import logo CertManager", show=False):

    with Cluster("This is a logo"):
        certmanager_url = ""
        certmanager_icon = "logo.png"
        urlretrieve(certmanager_url, certmanager_icon)
        certmanager = Custom("Cert Manager", certmanager_icon)
Icon imported from an external host to Diagram

If you want to import local icons saved in your repository, please review the example here.

Generate the diagram

Once you're happy with the code, generate the diagram by running the command bellow which will create a .png version of your diagram.



Diagrams by Mindgrammer isn't the only option out there with Cloudgram, PlantUML, or even having similar functionality of saving the XML generated in Git. We clearly do not lack options with open-source tools to create diagrams. Similarly, Python is so overly present that learning how to use Diagrams wasn't a steep learning curve.

At Bluelight, we create Diagrams for our clients during the discovery phase using Diagrams by Mindgrammer. It has been accelerating our discovery process and allows anyone in our team to jump in and quickly update the Diagram through version control.

You may also be interested in: 

Nearshore Staff Augmentation: Top 4 Benefits for Businesses

What is Kubecost: The Complete Guide

The Complete React Developer Salary Guide for 2022

A Detailed Overview of the Top 11 AWS Certification Courses

The Ultimate DevOps Hourly Rate Guide for 2022

Redux Toolkit with Typescript: How to Get Started

What is DevSecOps: Top 5 Automation Tools for CI Pipelines

DevOps on AWS: Everything you Need to Know

DevOps Engineer Salary: GCP Guide for 2021

Bluelight Consulting is a nearshore DevOps & Software Outsourcing company that helps startups, SaaS, and enterprises with cutting-edge solutions.

More cost-effective than hiring in-house, with Nearshore Boost, our nearshore software development service, you can ensure your business stays competitive with an expanded team and a bigger global presence, you can be flexible as you respond to your customers’ needs.

Learn more about our services by booking a free consultation with us today!

Let us solve your business’ biggest challenges

Book a free Consultation

Get In Touch

We’re here to help! Reach out to us today to schedule a free consultation.

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.