DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Document Your AWS Cloud Infrastructure Using Multicloud-Diagrams Framework
  • Data Flow Diagrams for Software Engineering
  • Requirements, Code, and Tests: How Venn Diagrams Can Explain It All
  • AI Is Transforming How We Use Software Diagrams

Trending

  • Mastering Advanced Traffic Management in Multi-Cloud Kubernetes: Scaling With Multiple Istio Ingress Gateways
  • AI Meets Vector Databases: Redefining Data Retrieval in the Age of Intelligence
  • The Human Side of Logs: What Unstructured Data Is Trying to Tell You
  • Apache Doris vs Elasticsearch: An In-Depth Comparative Analysis
  1. DZone
  2. Data Engineering
  3. Data
  4. Diagrams as Code: The Complete How-to-Use Guide

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

Diagrams as code is one of the latest ways to diagram software architecture, particularly for long-lived high-level documentation.

By 
Anthony Neto user avatar
Anthony Neto
·
Apr. 23, 22 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
14.3K Views

Join the DZone community and get the full member experience.

Join For Free

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 Diagrams 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 Diagram as Code?
  • How to install Diagrams
  • How to use Diagrams
  • Conclusion

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 supports 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:

Shell
 
# 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.

Python
 
  from diagrams.gcp.network 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: https://www.graphviz.org/doc/info/attrs.html

JSON
 
  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)

Python
 
from diagrams import Diagram
from diagrams.aws.compute import EC2
from diagrams.aws.database import RDS
from diagrams.aws.network import ELB
from diagrams.aws.storage 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")


Python
 
from diagrams import Diagram
from diagrams.aws.compute import EC2
from diagrams.aws.database import RDS
from diagrams.aws.network 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


Clusters allow you to group the nodes in an isolated group. You can create a cluster context with the 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.

Python
 
from diagrams import Cluster, Diagram, Node, Edge
from diagrams.k8s.compute import Pod
from diagrams.k8s.network import Ing
from diagrams.gcp.network import LoadBalancing
from diagrams.onprem.network 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


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

https://diagrams.mingrammer.com/docs/guides/edge

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 = "https://github.com/jetstack/cert-manager/raw/master/logo/logo.png"      
        certmanager_icon = "logo.png"       
        urlretrieve(certmanager_url, certmanager_icon)       
        certmanager = Custom("Cert Manager", certmanager_icon)

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 below, which will create a .png version of your diagram.

Shell
 
  python my_diagram.py


Conclusion

Diagrams by Mindgrammer isn't the only option out there with Cloudgram, PlantUML, or even Draw.io 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.

Diagram

Published at DZone with permission of Anthony Neto. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How to Document Your AWS Cloud Infrastructure Using Multicloud-Diagrams Framework
  • Data Flow Diagrams for Software Engineering
  • Requirements, Code, and Tests: How Venn Diagrams Can Explain It All
  • AI Is Transforming How We Use Software Diagrams

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!