Architecture, Azure Pipelines, Diagrams

Azure Pipelines – Diagrams as Code

Following on from my previous post on Architecture Diagrams I thought I would share my experiences with another tool, Diagrams.

Diagrams uses the Python language to describe diagrams, Python is not a language I use generally but it was simple enough to learn building diagrams.

The documentation describes how to get started and setup. I am a big fan of containers and so I created a container for using Diagrams.

The following dockerfile will create an environment:

FROM python:alpine3.13
ENV APK_ADD "bash py3-pip graphviz ttf-freefont"

RUN apk upgrade --update && \
    apk add --no-cache --virtual .pipeline-deps readline linux-pam && \
    apk add --no-cache ${APK_ADD} && \
    # Install Diagrams
    pip --no-cache-dir install --upgrade pip && \
    pip --no-cache-dir install diagrams && \
    # Tidy up
    apk del .pipeline-deps

RUN echo "PS1='\n\[\033[01;35m\][\[\033[0m\]Diagrams\[\033[01;35m\]]\[\033[0m\]\n\[\033[01;35m\][\[\033[0m\]\[\033[01;32m\]\w\[\033[0m\]\[\033[01;35m\]]\[\033[0m\]\n \[\033[01;33m\]->\[\033[0m\] '" >> ~/.bashrc

CMD tail -f /dev/null

To build and run: (I used a windows 10 machine)

docker build -f diagrams.dockerfile -t my-diagrams
docker run -it --entrypoint=/bin/bash --volume $env:USERPROFILE\source\repos:/mycode my-diagrams

Diagram

With my new environment I can use an editor of my choice to create the diagrams, my current go to is Visual Studio Code and there is a extension for Python.

The purpose of using this tool was to draw a diagram of an Azure Tenant and Subscription setup, I needed something that would allow the diagram to be changed quickly as the multiple people were collaborating.

The code below shows a simple example of the diagram being created:

from diagrams import Cluster, Diagram
from diagrams.azure.general import Managementgroups
from diagrams.azure.general import Subscriptions
from diagrams.azure.identity import ActiveDirectory

with Diagram("Azure Tenant Design", show=False, direction="TB"):
    tenant = ActiveDirectory("Tenant AD")  
    topGroup = Managementgroups("Main\r\nManagement Group")
    sandbox = Subscriptions("Sandbox\r\nSubscription")

    with Cluster("Business Units"):
        with Cluster("Unit1"):
          mainGroup = Managementgroups("Unit1\r\nManagement Group")
          topGroup >> mainGroup
          with Cluster("Project1"):
            group = Managementgroups("Project1\r\nManagement Group")
            sub = [Subscriptions("Project1\r\nDev/Test\r\nSubscription"), Subscriptions("Project1\r\nProduction\r\nSubscription")]
            group - sub
            mainGroup >> group

          with Cluster("Project2"):
            group = Managementgroups("Project2\r\nManagement Group")
            sub = [Subscriptions("Project2\r\nDev/Test\r\nSubscription"), Subscriptions("Project2\r\nProduction\r\nSubscription")]
            group - sub
            mainGroup >> group

        with Cluster("Infrastructure"):
          group = Managementgroups("Infrastructure\r\nManagement Group")
          sub = [Subscriptions("Test\r\nSubscription"), Subscriptions("Infrastructure\r\nProduction\r\nSubscription")]
          group - sub
          topGroup >> group

    tenant >> topGroup >> sandbox

The diagram can be created by simply calling python and the name of the file (this code was executed from the container).

The code produces the following diagram:

Azure Pipelines

Now the diagram code is created, it would be good to be able to have a pipeline building the diagram and providing the image. Building the diagrams in an Azure Pipeline would be easier if I could use the container created earlier.

Fortunately I can, Azure Pipelines allows container jobs, but that means the dockerfile needs a few modifications to use it in Azure Pipelines. The Microsoft Docs explain in more detail but for this I need node installed, a special label and some additional packages.

The new dockerfile looks like this:

FROM node:lts-alpine3.13 AS node_base

RUN echo "NODE Version:" && node --version
RUN echo "NPM Version:" && npm --version

FROM python:alpine3.13

ENV NODE_HOME /usr/local/bin/node
COPY --from=node_base ["${NODE_HOME}", "${NODE_HOME}"] 

LABEL maintainer="Tazmainiandevil"
LABEL "com.azure.dev.pipelines.agent.handler.node.path"="${NODE_HOME}" 

ENV APK_ADD "bash sudo shadow py3-pip graphviz ttf-freefont"

RUN apk upgrade --update && \
    apk add --no-cache --virtual .pipeline-deps readline linux-pam && \
    apk add --no-cache ${APK_ADD} && \
    # Install Diagrams
    pip --no-cache-dir install --upgrade pip && \
    pip --no-cache-dir install diagrams && \
    # Tidy up
    apk del .pipeline-deps

RUN echo "PS1='\n\[\033[01;35m\][\[\033[0m\]Diagrams\[\033[01;35m\]]\[\033[0m\]\n\[\033[01;35m\][\[\033[0m\]\[\033[01;32m\]\w\[\033[0m\]\[\033[01;35m\]]\[\033[0m\]\n \[\033[01;33m\]->\[\033[0m\] '" >> ~/.bashrc

CMD tail -f /dev/null

Container Build

Using Azure Pipelines I can build the container and added it to an Azure Container Registry (if you need to know how to setup ACR see my previous post on Configuring ACR)

trigger: 
 branches:
    include:
    - main
 paths:
    include: 
     - diagrams.dockerfile

pr: none

variables:
- group: Azure Connections
- name: dockerFilePath
  value: diagrams.dockerfile
- name: imageRepository
  value: dac/diagrams

pool:
  vmImage: "ubuntu-latest"

steps:
  - task: Docker@2
    displayName: "Build Diagram Image"
    inputs:
      containerRegistry: "$(myContainerRegistry)"
      repository: '$(imageRepository)'
      command: 'buildAndPush'
      Dockerfile: '$(dockerfilePath)'
      tags: |
        $(Build.BuildNumber)
        latest

With the container added to my registry I can use it in a pipeline to create my diagrams.

Image Build

The pipeline needs to create an image as an artifact and only when on the main branch to make sure only the final diagrams are published and not ones in progress.

The YAML below defines the pipeline:

trigger: 
   - main

pr: none

variables:
  isMain: $[eq(variables['Build.SourceBranch'], 'refs/heads/main')]

jobs:
- job: creatediagram
  displayName: Create Diagram  
  pool:
    vmImage: ubuntu-latest
  container:
    image: $(myContainerRegistry)/dac/diagrams:latest
    endpoint: 'My Registry Service Connection'
  variables:
    workspaceFolder: 'TenantDesign'
  steps:
  - script: | 
      python tenant.py
      cp *.png $(Build.ArtifactStagingDirectory)
    displayName: Run Python
  - publish: '$(Build.ArtifactStagingDirectory)'
    displayName: Publish Diagrams
    artifact: $(workspaceFolder)
    condition: eq(variables.isMain, true)

Conclusion

I found using Diagrams simple and the documentation was good to allow picking up what was needed quickly. I will certainly be looking at using it for other diagrams in the future. I like the fact that it is easy to use, open source and supports custom images so you are not limited to the provided icons (Custom Docs).

Diagrams GitHub

Diagrams Docs

I hope that others find this useful and use Diagrams as Code for their projects.

Architecture, Azure Pipelines, Diagrams

Azure Pipelines – Architecture Diagrams as Code

Over the past few years I have drawn many Architecture diagrams in a variety of tools like drawio, visio, Lucid Chart, etc. and always found there were many hours spent doing rework and updates.

I generally draw diagrams using the C4 model for detailed architecture but still would have drawn them by hand and totally forgetting about the fact there is a lot of support for building diagrams as code. First time I looked at the C4 model I used code to draw diagrams, so why had I not been using it? to be honest I have no idea why, but it’s definitely time to embrace it again.

If you are not familiar with the C4 model I suggest you checkout the website and I recommend Simon Brown’s books on Software Architecture for Developers, which is available on Leanpub.

Getting Started

So, I recently embarked on creating diagrams as code using the C4 model and Structurizr. First thing is create a free account on Structurizr to get started.

I now needed to decide what to language to use for my diagram as code. Structurizr supports a number of languages for authoring, Java, .NET, TypeScript, PHP, Python, Go and of course its own DSL. I choose the Structurizr DSL for my diagram as it looked easy enough. For editing the code I used Visual Studio Code and an extension for code highlighting by Ciaran Treanor. The DSL demo page and language reference were really helpful to get started as well as the examples.

Building architecture diagrams using the C4 model is great and using the DSL made it easy to build my diagram quite quickly and using the demo page I could see what my diagram was going to look like.

Publish

Having created my diagram as code and added it to source control, I now needed to push my diagram to my Structurizr workspace. Structurizr has a CLI that you can use to do this.

structurizr-cli push -id <my workspace> -key <workspace key> -secret <workspaceSecret> -workspace mydiagram.dsl

The details for the workspace can be found on your Structurizr page by selecting ‘Show more’.

The CLI has other features including exporting to different formats e.g. Mermaid (for more details on the supported outputs see the website)

structurizr export -workspace mydiagram.dsl -format mermaid

Having published my diagram to my workspace, it would be really good to automate this process so any changes to the diagram get pushed.

Currently I am using Azure Pipelines a lot, so it seemed fitting to create this process using Azure Pipelines YAML.

Building the Pipeline

This should be straight forward, I just need to perform the same steps as I did locally to push my diagram to Structurizr.

The build pipeline automatically checkouts my code from my repo so that step is done for me. The Microsoft Build Agents already have HomeBrew installed so that makes installing the CLI simple.

- bash: |
    brew install structurizr-cli
  displayName: 'Install Structurizr'

Pushing to Structurizr needs a number of parameters which should be kept secret so adding them as secure variables in the Pipeline is one solution.

- bash: |
    structurizr-cli push -id $(workspaceId) -key $(workspaceKey) -secret $(workspaceSecret) -workspace $(workspaceFile)
  displayName: 'Push Diagram to Structurizr'

Enhancing the Pipeline

The diagram has been updated in Structurizr but I now usually need images to add to a presentation or documentation. I could go to Structurizr and export the images for each diagram by hand but that takes time and is not helpful is someone else needs them.

Fortunately there are some examples of how to do this using Puppeteer with Structurizr on GitHub which is great and the export of private diagrams worked out of the box with no modification.

The pipeline can be updated now to Install Puppeteer

- bash: |
   npm install puppeteer 
  displayName: 'Install Puppeteer'

And get the example from the Structurizr/Puppeteer repo

- bash: |
    git clone 'https://github.com/structurizr/puppeteer.git'
  displayName: "Get Structurizr Puppeteer"    

Using the example and providing the required details, png files can now be exported.

- bash: |    
    cd $(Build.ArtifactStagingDirectory)
    node $(System.DefaultWorkingDirectory)/puppeteer/export-private-diagrams.js $(workspaceUrl) $(workspaceUsername) $(workspacePassword) png $(workspaceId)
  displayName: 'Export Diagram from Structurizr'

Or svg files.

- bash: |    
    cd $(Build.ArtifactStagingDirectory)
    node $(System.DefaultWorkingDirectory)/puppeteer/export-private-diagrams.js $(workspaceUrl) $(workspaceUsername) $(workspacePassword) svg $(workspaceId)
  displayName: 'Export Diagram from Structurizr'

The images are outputted to the ArtifactStagingDirectory and can now be published as an artifact.

- publish: '$(Build.ArtifactStagingDirectory)'
  displayName: Publish Diagrams
  artifact: 'mydiagrams'

The artifacts will be individual files and so it might be easier to zip them for easier download from Azure Pipelines using the ArchiveFiles task.

 - task: ArchiveFiles@2
   inputs:
      rootFolderOrFile: '$(Build.ArtifactStagingDirectory)'
      archiveFile: '$(Build.ArtifactStagingDirectory)/diagrams.zip' 
 - publish: '$(Build.ArtifactStagingDirectory)/diagrams.zip'
   displayName: Publish Diagrams
   artifact: 'mydiagrams'

Final Pipeline

Putting all that together, my final pipeline looks like this:

trigger: 
- main

pr: none

variables:
  workspaceFile: 'mydiagram.dsl'
  isMain: $[eq(variables['Build.SourceBranch'], 'refs/heads/main')]

jobs:
  - job: UpdateArchitecture
    displayName: Update Architecture
    condition: and(succeeded(), eq(variables.isMain, true))
    pool:
      vmImage: ubuntu-18.04
    steps:
      - bash: |
          brew install structurizr-cli
          brew info structurizr-cli
        displayName: 'Install Structurizr'
      - bash: |
          npm install puppeteer 
        displayName: 'Install Puppeteer'
      - bash: |
          git clone 'https://github.com/structurizr/puppeteer.git'
        displayName: 'Get Structurizr Puppeteer'
      - bash: |
          structurizr-cli push -id $(workspaceId) -key $(workspaceKey) -secret $(workspaceSecret) -workspace $(workspaceFile)
        displayName: 'Push Diagram to Structurizr'
      - bash: |    
          cd $(Build.ArtifactStagingDirectory)
          node $(System.DefaultWorkingDirectory)/puppeteer/export-private-diagrams.js $(workspaceUrl) '$(workspaceUsername)' '$(workspacePassword)' png $(workspaceId)
        displayName: 'Export Diagram from Structurizr'
      - publish: '$(Build.ArtifactStagingDirectory)'
        displayName: Publish Diagrams
        artifact: 'mydiagrams'

Final Thoughts

I started on a journey to automate building architecture diagrams and export the images and this satisfies todays need but in the future I may need to enhance the pipeline to push the images to another system or export them in to another format.

I will certainly be using this article to remind me about diagrams as code, I hope you consider diagrams as code for you own needs and that this has been useful to share.

Happy diagramming.