Category: Azure

A guide to getting started with C4 diagrams and Structurizr

Discover the benefits of using Structurizr and Domain Specific Language (DSL) to create interactive and versioned C4 diagrams as code, enabling precise CA modelling and visualization for your software architecture.

Table of Contents

What are C4 diagrams?

The C4 model diagram strategy was created to establish a standard set of simple notation principals for visually documenting software architectures.

It consist of a standard set of hierarchical abstractions (software systems, containers, components, and code) that are used to create a set of hierarchical diagrams (system context, containers, components, and code). Although the code diagram is almost never created, other than from the code itself.

Each level of diagram digs deeper into the details of the systems you are trying to communicate and can be thought of as different scales on a map.

The C4 model for visualising software architecture from c4modeI.com

For detailed explanations see The C4 model for visualising software architecture

Structurizr is a toolset that helps code, manage and display C4 diagrams. This guide will help you get setup and started quickly.

You can use a variety of tools to create and conform to this diagramming standard. The key ones I have used are:

For a full list of tools see C4 model tools

Using Structurizr and Domain Specific Language (DSL)

Getting started with Visio is straight forward, just using the stencil. However, what we are after is diagrams as code, that we can version along with our design and code changes. To do this we can either use Mermaid or Domain Specific Language (DSL). DSL allows for more precise C4 modelling and Structurizr allows for creating interactive visualizations.

This is a quick getting started guide to get going locally rendering views of your models on Windows. You can read all the details and options of Structurizr and the DSL syntax at Structurizr.

Prerequisites

Setup Steps and getting started

1. Working Folder

You will need to have a folder that’s dedicated for the Structurizr C4 diagrams code and configuration files. Ideally this will be for a single domain and in your local git folders. That way you can branch, versions and commit your diagrams as versioned code.

For example: c:\gitrepos\myprojectrepo\docs\architecture\diagrams\my-domain\structurizr-data\

Note: Currently you can only have one workspace per folder, so you may need several workspaces, such as one per domain.

2. Docker setup

After you have installed Docker Desktop then the next step is to ‘pull’ (or download) the Structurizr docker image from a Docker registry, typically Docker Hub. By pulling this image, you鈥檙e downloading the necessary files to run Structurizr Lite in a Docker container on your local machine. To do this run the following command

# Pull the Structurizr docker image
docker pull structurizr/lite

The easiest way to execute these commands is from the Docker Desktop built-in Terminal. Click on the ‘>_ Terminal’ button at the bottom.

3. Create and run a container

Once the image is downloaded and ready in Docker, then from the Docker terminal run the following command in this format

docker run -it --rm -p <local port>:8080 -v "<host machine Structurizr folder>:/usr/local/structurizr" structurizr/lite

The -it option supports both:
-i (interactive) keeps the STDIN open even if not attached.
-t (tty) allocates a pseudo-TTY, which allows you to interact with the container.

The -rm option automatically removes the container when it exits, ensuring no leftover containers. You may not want to do this if you are going to run this container repeatedly and have the necessary disk space.

In this case it would be something like…

docker run -it --rm -p 8080:8080 -v "c:\gitrepos\myprojectrepo\docs\architecture\diagrams\my-domain\structurizr-data\:/usr/local/structurizr" structurizr/lite

Once you have your command line tested, it’s a good idea to put this into a readme.md file in the structurizr-data folder, so that others can easily create a server pointing to the correct folders (unless everyone uses the same root paths, they will need to adjust it for themselves, but it’s a good starter).

If you have all the paths correct then you should see a successful start and something like this in the terminal.

4. Access Structurizr Web Dashboard

Once the container is running you can now simply open a browser and navigate to http://localhost:<local port> or in our example http://localhost:8080

A default Structurizr workspace will be automatically created for you. It will look like this…

and a corresponding set of file and folders will be added to your folder.

It’s the workspace.dsl that you will be editing to define your architectural model and how it should be visualized.

Quick-start on modelling using DSL

workspace.dsl

The workspace.dsl file is a text-based domain-specific language (DSL) file used to define a software architecture model based on the C4 model. This file allows you to describe the elements of your software system, their relationships, and how they should be visualized. Here are some key components:

  • Model Definition: Defines the people, software systems, containers, components, and their relationships.
{
    "model": {
        "people": [
            {
                "id": "1",
                "name": "User",
                "description": "A user of my software system."
            }
        ],
        "softwareSystems": [
            {
                "id": "2",
                "name": "Software System",
                "description": "My software system."
            }
        ],
        "relationships": [
            {
                "sourceId": "1",
                "destinationId": "2",
                "description": "Uses"
            }
        ]
    }
}
  • Views: Specifies how the elements should be visualized in different diagrams (e.g., system context, container, component diagrams).
{
    "views": {
        "systemContextViews": [
            {
                "softwareSystemId": "2",
                "description": "System Context diagram for Software System",
                "elements": [
                    { "id": "1" },
                    { "id": "2" }
                ],
                "automaticLayout": true
            }
        ],
        "styles": {
            "elements": [
                {
                    "tag": "Software System",
                    "background": "#1168bd",
                    "color": "#ffffff"
                },
                {
                    "tag": "Person",
                    "shape": "person",
                    "background": "#08427b",
                    "color": "#ffffff"
                }
            ]
        }
    }
}

workspace.json

Both files serve the same purpose but cater to different use cases. The DSL file is more human-readable and easier to write manually, while the JSON file is better suited for automated processing and integration with other tools.

The web app, Structurizr Lite generates and maintains this file and you should very rarely need to view or update this file manually.

.structurizr folder

The .structurizr folder is a directory used by Structurizr to store various configuration and data files related to your workspace such as images, other assets, logs and temporary files used during operations. This is managed by the app should not be interferred with 馃槈

Tips for building you model

Add a title and description to your workspace

workspace "Model Title Here" "Add a description of the model here" {

    model {
    ...
    }
    views {
    ...
    }
    configuration {
    ...
    }

Set Identifiers as hierarchical

By default, all identifiers are treated as being globally scoped, however by using the !identifiers keyword you can specify that element identifiers should be treated as hierarchical (relationship identifiers are unaffected by this setting).

workspace {

    !identifiers hierarchical

    model {
        softwareSystem1 = softwareSystem "Software System 1" {
            api = container "API"
        }

        softwareSystem2 = softwareSystem "Software System 2" {
            api = container "API"
        }
    }
}

So now each api can have the same local name, but be referenced softwareSystem1.api and softwareSystem2.api respectively.

see Identifiers | Structurizr

Add your users/personas at the top

Syntax

person <name> [description] [tags] {
    // Define properties and relationships here
}

Example

model {
        customer = person "Online Shopping Customer" "A customer"
        picker = person "Picker" "A warehouse picker" "Warehouse"
        whmanager= person "Warehouse Manager" "A warehouse manager" "Warehouse"
        despatcher = person "Despatch Operator" "A warehouse despatcher" "Warehouse"
        ...

Then your high level systems

In Structurizr DSL, the softwareSystem element is used to define a software system within your architecture model. A software system represents a major part of your overall system, typically encompassing multiple containers and components.

Syntax

softwareSystem <name> [description] [tags] {
    // Define properties and relationships here
}

Example

webapp= softwaresystem "Store Web App" "The main web store" "Existing System"
email = softwaresystem "E-mail System" "The internal Microsoft Exchange e-mail system." "Existing System"
atm = softwaresystem "ATM" "Allows customers to withdraw cash." "Existing System"

Use Groups

The group element is used to define a named grouping of elements, which will be rendered as a boundary around those elements. This is useful for organizing and visually separating different parts of your architecture model.

Example

workspace {
    model {
        group "Company 1" {
            a = softwareSystem "System A" "Description of System A."
        }
        group "Company 2" {
            b = softwareSystem "System B" "Description of System B."
        }
        a -> b "Uses"
    }
    views {
        systemLandscape {
            include *
            autoLayout lr
        }
        styles {
            element "Group" {
                color #ff0000
            }
        }
    }
}

Use the Azure or other custom themes

The theme element is used to apply a set of predefined styles to your diagrams and is used in the views section. Themes help you maintain a consistent look and feel across your diagrams, especially when using common visual styles for elements and relationships.

Syntax

theme <url>

Example of the Azure theme

Here I have also added some shapes that get overridden by the Azure theme.

views {
        // theme default
        themes https://static.structurizr.com/themes/microsoft-azure-2021.01.26/theme.json
        // https://structurizr.com/help/theme?url=https://static.structurizr.com/themes/microsoft-azure-2021.01.26/theme.json
        styles {
            element "Database" {
                shape "cylinder"
            }
            element "Person" {
                shape "Person"
                background "#08427b"
                color "#ffffff"
            }
            element "Software System" {
                background "#1168bd"
                color "#ffffff"
            }
        }
        ...

For more themes see Themes | Structurizr

Allow manual layout in Structurizr Lite

The autolayout element is used to automatically arrange the elements in a view, making it easier to create well-organized and visually appealing diagrams without manually positioning each element.

Syntax

autolayout [direction] [rankSeparation] [nodeSeparation]
  • Direction: Specifies the direction of the layout. Possible values are:
    • lr (left to right)
    • rl (right to left)
    • tb (top to bottom)
    • bt (bottom to top)
  • Rank Separation: (Optional) Specifies the separation between ranks (levels) in the layout. Default is 300.
  • Node Separation: (Optional) Specifies the separation between nodes (elements) in the layout. Default is 300

When you add this to a view definition, you will not be able to manually reposition the shapes in the GUI. Just remove or remark the line to allow it.

views {        
       systemLandscape "SystemLandscape" {
            include *
            // autolayout lr
        }

        systemContext eCommerceSystem "SystemContext" {
            include *
            autolayout lr
        }
        ...

Here the SystemLandscape is manually arranged and the eCommerceSystem is arrange left-to-right.

Notes, Examples and References

Structuring YAML Pipelines and nested variables in Azure DevOps

When managing pipelines for large and complex repositories with multiple ‘Platforms’, each containing multiple apps and services, then the folder structure and variable strategy can be complicated. However, if this is done right, then the payoff for template reuse is dramatic.

Here, I outline my approach on the pipeline folder and YAML structure only. The variable structure allows for a full set of naming conventions to easily default across all your projects apps and delegate standards to organisation and platform levels. This, ideally, leaves only app specific configurations for your dev teams to manage and worry about.

This strategy rests on top of my general approach to structuring a mono-repository. For more details on that see Mono-repository folder structures.

Continue reading “Structuring YAML Pipelines and nested variables in Azure DevOps”

Mono-repository folder structures

Every developer has their own way of structuring their code base. There is no right or wrong way, but some strategies have at least had some logical thought 馃槈

This is a sample of how I generally structure my mono-repos when they need to scale to many organisational platforms, apps, and projects.

Continue reading “Mono-repository folder structures”

How to publish a multi-page Azure DevOps Wiki to PDF (and pipeline it)

Although you can print a single page of your wiki to a PDF using the browser, it’s problematic when you have a more complex structured multi-page wiki and you need to distribute or archive it as a single file.

Fortunately thanks to the great initiative by Max Melcher and his AzureDevOps.WikiPDFExport tool, combined with Richard Fennell’s WIKI PDF Export Tasks, we can not only produce pretty good multi-page PDF’s of our Wiki’s, but to also create a Pipeline to automate their production.

The documentation for both these tools is good, but I have included here some additional tips and more complete steps to quickly get your pipelines setup.

Pre-requirements

To follow the steps outlined below you will need to:

  1. Download the latest azuredevops-export-wiki.exe from GitHub (or the source code and build it yourself)
    • I create a local folder like C:\MyApps\AzureDevOps-Export-Wiki\ and drop the EXE there. Then I can execute all my command lines and see the outputs there too.
  2. Add the WIKI PDF Export Tasks extension in the Visual Studio Marketplace to your Azure DevOps Organisation. Click here WIKI PDF Export Tasks – Visual Studio Marketplace

The Setup

Assume we have an Azure DevOps (Azdo) project called ‘MyAzdoProject‘. This has a default code repository with the same name and once created, a wiki repository called ‘MyAzdoProject.wiki‘.

You can clone this Wiki repo by selecting the ‘Clone wiki’ from the Wiki menu.

In the code repository, I have created a folder called /resources/wiki-pdf-styles/ to hold the

  • Header HTML template file
  • Footer HTML template file
  • CSS Style Sheet

In the Wiki, we may have documentation for several Apps and each may have several sections such as Architecture, UX design, Requirements notes etc..

For this illustration I am only wanting to output the Architecture pages and subpages for App1. So everything below /App1/Architecture/** in the wiki.

The Resource Files

My resource files are as follows (name of the files include the apps ‘Short Code’ ‘app1’ so each app can have independent files):

header-app1.html

<div style='padding-left: 10px; margin: 0; -webkit-print-color-adjust: exact; border-bottom:1px solid grey; color: grey; width: 100%; text-align: left; font-size: 6px;'>
Nicholas Rogoff - My Cool App 1 - Architecture
</div>

footer-app1.html

<div style='padding-right: 10px; padding-top:2px; margin: 0; -webkit-print-color-adjust: exact; border-top:1px solid grey; color: grey; width: 100%; text-align: right; font-size: 6px;'>Copyright Nicholas Rogoff 2023 |
 Printed: <span class='date'></span> | Page: </span><span class='pageNumber'></span> of <span class='totalPages'></span>
</div>

styles.css

body {
  font-family: "Segoe UI Emoji", Tahoma, Geneva, Verdana, sans-serif;
  font-size: 10pt;
}

h1 {
  font-size: 25pt;
  color: #521e59;
}

h2 {
  font-size: 20pt;
  color: #3b868d;
}

h3 {
  font-size: 15pt;
  color: #f39000;
}

h4 {
  font-size: 12pt;
  color: #ec644a;
}

img {
  max-width: 100%;
  max-height: 800px;
}

/* Workaround to add a cover page */
.toc {
  page-break-after: always;
}

/* target a span with class title inside an h1 */
h1 span.title {
  page-break-before: avoid !important;
  page-break-after: always;
  padding-top: 25%;
  text-align: center;
  font-size: 48px;
}

/* make tables have a grey border */
table {
  border-collapse: collapse;
  border: 1px solid #ccc;
}

/* make table cells have a grey border */
td,
th {
  border: 1px solid #ccc;
  padding: 5px;
}

The Command Line

You can manually run the azure-export-wiki.exe (download the latest from here Releases 路 MaxMelcher/AzureDevOps.WikiPDFExport (github.com)) locally on a clone of your wiki repository. This is useful not just to output the PDF, but also to quickly refine your customizations, such as, parameters, templates and CSS.

I have used the following parameters:

  • -p / –path
    • Path to the wiki folder. If not provided, the current folder of the executable is used.
  • -o / –output
    • The path to the export file including the filename, e.g. c:\output.pdf
  • –footer-template-path, –header-template-path
    • local path to the header and footer html files
  • –css
    • local path to the CSS file
  • –breakPage
    • Adds a page break for each wiki page/file
  • –pathToHeading
    • Adds a path to the heading of each page. This can be formatted in the CSS
  • –highight-code
    • Highlight code blocks using highligh.js
  • –globaltoc
    • This sets the title for a global Table of Contents. As you will see, I have used this, in combination with the CSS to add in a main header Title.

…so my final command line looks like this:

.\azuredevops-export-wiki.exe 
  -p "C:\GitRepos\MyAzdoProject.wiki\MyAzdoProject\App1\Architecture" 
  -o "output.pdf"  
  --footer-template-path "C:\GitRepos\MyAzdoProject\MyAzdoProject\resources\wiki-pdf-styles\footer-cdhui.html"  
  --header-template-path "C:\GitRepos\MyAzdoProject\MyAzdoProject\resources\wiki-pdf-styles\header-cdhui.html" 
  --css "C:\GitRepos\MyAzdoProject\MyAzdoProject\resources\wiki-pdf-styles\styles.css" 
  --breakPage 
  --pathToHeading 
  --highlight-code 
  --globaltoc "<span class='title'>Nicholas Rogoff Cool App 1 Architecture Wiki</span>" -v

You can run and refine this command line locally and generate the output.

You can also do a lot more styling with the CSS than I have done and refine it to your requirements. Just use the –debug flag in the command line above and the intermediate HTML file is produced. You can then see all the classes that you can play with.

The Pipeline

I decided to create a YAML Pipeline Template, as I often have many apps and extensive wiki documentation. Printing the whole Wiki to a PDF is not feasible, and hits limitations, so I have a several pipelines to output distinct parts of the wiki structure.

The YAML Task Template (publish-wiki-to-pdf-cd-task-template.yml)

Everything in this template is parameterized to allow flexible usage. You can also set the defaults and simplify the consuming pipelines.

# Task template for generating the PDF from the Wiki

parameters:
  - name: LocalWikiCloneFolder
    displayName: The local path to clone the wiki repo to
    type: string
    default: '$(System.DefaultWorkingDirectory)\wikirepo'
  - name: WikiRootExportPath
    displayName: The path in the Wiki to export to PDF
    type: string
  - name: ProjectShortCode
    displayName: The short code for the project. Used to pick up the custom headers and footers files
    type: string
  - name: CustomFilesPath
    displayName: The local path to the custom files on the build agent in the main repo
    type: string
    default: '\resources\wiki-pdf-styles\**'
  - name: PdfOutputFileName
    displayName: The filename for the output pdf. Do not include the extension
    type: string
    default: '$(ProjectShortCode)-Wiki.pdf'
  - name: WikiRepoUrl
    displayName: The URL of the Wiki repo
    type: string
    default: 'https://myorg@dev.azure.com/myorg/MyAzdoProject/_git/MyAzdoProject.wiki'
  - name: PdfTitleHeading
    displayName: The title heading for the PDF
    type: string
    default: 'Nicholas Rogoff - $(ProjectShortCode) - Wiki'
    
steps:
- task: CopyFiles@2
  displayName: Copy-Headers-Footers-Styles
  inputs:
    Contents: '$(CustomFilesPath)'
    TargetFolder: '$(System.DefaultWorkingDirectory)\styles\'
    OverWrite: true
  enabled: false
- task: WikiPdfExportTask@3
  displayName: Create-PDF
  inputs:
    cloneRepo: true
    repo: '$(WikiRepoUrl)'
    useAgentToken: true
    localpath: '$(LocalWikiCloneFolder)'
    rootExportPath: '$(WikiRootExportPath)'
    outputFile: '$(System.DefaultWorkingDirectory)\$(PdfOutputFileName).pdf'
    ExtraParameters: '--footer-template-path "$(System.DefaultWorkingDirectory)\resources\wiki-pdf-styles\footer-$(ProjectShortCode).html" --header-template-path "$(System.DefaultWorkingDirectory)\resources\wiki-pdf-styles\header-$(ProjectShortCode).html" --css "$(System.DefaultWorkingDirectory)\resources\wiki-pdf-styles\styles.css" --breakPage --pathToHeading --highlight-code --globaltoc "<span class=''title''>$(PdfTitleHeading)</span>" -v'
- task: PublishBuildArtifacts@1
  displayName: Publish-Artifact
  inputs:
    PathtoPublish: '$(System.DefaultWorkingDirectory)\$(PdfOutputFileName).pdf'
    ArtifactName: 'drop'
    publishLocation: 'Container'

The main pipeline

# Publishes the wiki to PDFs

trigger:
- none
pr: none

# schedules:
# - cron: "0 0 * * *"
#   displayName: Daily midnight wiki publish
#   branches:
#     include:
#     - main

#   always: true

pool:
  vmImage: windows-latest

# Setting the build number to the date as work-around to include in the Title as $(Build.BuildNumber)
name: $(Date:yyyy-MM-dd)

variables:
- name: projectShortCode
  value: 'app1'
- name: localWikiCloneFolder
  value: '$(System.DefaultWorkingDirectory)\wikirepo'
- name: wikiRootExportPath
  value: '$(localWikiCloneFolder)\MyAzdoProject\Projects\CDH-UI\Architecture'
- name: customFilesPath
  value: '\resources\wiki-pdf-styles\**'
- name: wikiRepoUrl
  value: 'https://myorg@dev.azure.com/m/MyorgyAzdoProject/_git/MyAzdoProject.wiki'
- name: pdfOutputFilename
  value: '$(ProjectShortCode)-Architecture-Wiki.pdf'
- name: pdfTitleHeading
  value: 'Nicholas Rogoff - $(ProjectShortCode) - Architecture Wiki $(Build.BuildNumber)'

steps:
- template: './templates/publish-wiki-to-pdf-cd-task-template.yml'
  parameters:
    LocalWikiCloneFolder: $(localWikiCloneFolder)
    WikiRootExportPath: '$(wikiRootExportPath)'
    ProjectShortCode: '$(projectShortCode)'
    CustomFilesPath: '$(customFilesPath)'
    PdfOutputFileName: '$(pdfOutputFilename)'
    WikiRepoUrl: '$(wikiRepoUrl)'
    PdfTitleHeading: '$(pdfTitleHeading)'

I have left in some running options here. The default is completely manual, but I have added for reference, commented out, the format for a scheduled operation, as well as on every change (not recommended).

I have also used the ‘name:’ (which is referenced as $(Build.BuildNumber)), to create a date in a format I wanted for the Header page.

When this pipeline runs the PDF artifact can be downloaded. You can obviously add a new step to copy the file to any destination that suits your requirements.

Enabling Diagnostics on everything* in Azure

Sometimes you just want to enable diagnostics on everything* (* = eligiable resource types) in a Resource Group and to point to the same Log Analytics workspace.

Here is a PowerShell script that allows you to do this. See the Examples for details on what you can do.

The Log Analytics and Storage accounts do need to be in the same subscription.

<#PSScriptInfo
.VERSION 1.0
.GUID 4859bbd0-103e-4089-a6a1-35af0f9c5e63
.AUTHOR Nicholas Rogoff

.RELEASENOTES
Initial version. Could do with more error handling
#>
<#
.SYNOPSIS
  Script to enable diagnostics on all* resources (* = eligible resource types)
.DESCRIPTION
  Iterates through all eligible resources and enables diagnostics on all them. 
  Diagnostic data is sent to Log analytics workspace and storage account if  set.

.NOTES
  Version:        1.0
  Author:         Nicholas Rogoff
  Creation Date:  2020-10-28
  Purpose/Change: Initial script development

.PARAMETER ResourceGroupName
  The resource group to scan for resources that can have diagnostics enabled

.PARAMETER LogAnalyticsWS
    The Log Analytics workspace to forward logs too

.PARAMETER StorageAccName
    [Optional] If this is given then diagnostics will be set to ship the logs for longer term archiving to the chosen storage account. 
    The storage account MUST be in the same region as the resource.

.PARAMETER ResourceTypes
    [Optional] An array of resource types 
    (see https://docs.microsoft.com/en-us/azure/azure-resource-manager/management/azure-services-resource-providers)
    to enable diagnostcs on. If not passed a default set is used as follows: 
    "Microsoft.Automation/automationAccounts", "Microsoft.Logic/workflows", "Microsoft.Storage/storageAccounts", 
    "Microsoft.DesktopVirtualization/workspaces", "Microsoft.DesktopVirtualization/applicationgroups", 
    "Microsoft.DesktopVirtualization/hostpools", "Microsoft.Compute/virtualMachines","Microsoft.Network/virtualNetworks","Microsoft.Web/serverFarms"

.EXAMPLE
  .\EnableDiagnostics.ps1 -ResourceGroupName $ResourceGroupName  -LogAnalyticsWS $LogAnalyticsWS -StorageAccName $StorageAccName 
  Enables Diagnostics on eveything in a resource group it can and includes shipping logs to storage account

.EXAMPLE
.\EnableDiagnostics.ps1 -ResourceGroupName $ResourceGroupName  -LogAnalyticsWS $LogAnalyticsWS
  Enables Diagnostics on eveything in a resource group it can to the chosen LogAnalytics Workspace Only

.EXAMPLE
$ResourceTypes = @('Microsoft.Compute/virtualMachines','Microsoft.Network/virtualNetworks')
.\EnableDiagnostics.ps1 -ResourceGroupName $ResourceGroupName  -LogAnalyticsWS $LogAnalyticsWS -ResourceTypes $ResourceTypes
  Enables Diagnostics on eveything in a resource group it can to the chosen LogAnalytics Workspace and for Resource Type of VMs 
  and Virtual Networks only
#>
#---------------------------------------------------------[Script Parameters]------------------------------------------------------
[CmdletBinding()]
Param (
    #Script parameters go here
    [Parameter(mandatory = $true)]
    [string] $ResourceGroupName,
	
    [Parameter(mandatory = $true)]
    [string] $LogAnalyticsWS,
    
    [Parameter(mandatory = $false)]
    [string] $StorageAccName,
    
    [Parameter(mandatory = $false)]
    [string[]] $ResourceTypes = @("Microsoft.Automation/automationAccounts", "Microsoft.Logic/workflows", "Microsoft.Storage/storageAccounts", "Microsoft.DesktopVirtualization/workspaces", "Microsoft.DesktopVirtualization/applicationgroups", "Microsoft.DesktopVirtualization/hostpools","Microsoft.Compute/virtualMachines","Microsoft.Network/virtualNetworks","Microsoft.Web/sites","Microsoft.Web/serverFarms")

)

#---------------------------------------------------------[Initialisations]--------------------------------------------------------

#Set Error Action to Silently Continue
$ErrorActionPreference = 'Continue'

#Variable to hold Passed and failed resources
$Passed = "Successfully Enabled On  : "
$Failed = "Failed On    : "

#----------------------------------------------------------[Declarations]----------------------------------------------------------

#Any Global Declarations go here

#-----------------------------------------------------------[Functions]------------------------------------------------------------

# Function to check if the module is imported
function EnableDiagnostics {
    [CmdletBinding()]
    param(
        [Parameter(mandatory = $true)]
        [string]$ResourceGroupName,
        [Parameter(mandatory = $true)]
        [string]$LogAnalyticsWS,
        [Parameter(mandatory = $false)]
        [string]$StorageAccName
    )

    Write-Debug ("Script EnableDiagnostics function execution started...")
			
    #Variables to hold log analytics resource id's
    $LogAnlyResId = Get-AzResource -Name $LogAnalyticsWS | Select-Object ResourceId

    #Iterate over all configured resource types
    foreach ($resType in $ResourceTypes) {
						
        #Variable to hold Resource list for each resource type
        $resources = Get-AzResource -ResourceGroupName $ResourceGroupName -ResourceType $resType | Select-Object Name, ResourceId, Location
						
        #Enable Diagnostics for each resource in resource list
        foreach ($resource in $resources) {
            $Error.clear()
													 
            #Command to enable diagnostics	
            $DiagName = $resource.Name + "-Diagnostics"
            $resName = $resource.Name
            Write-Output "=== Setting diagnostics on $resName"
			if($StorageAccName)
			{
				$StrAccResId = Get-AzResource -Name $StorageAccName | Select-Object ResourceId

				Set-AzDiagnosticSetting -Name $DiagName `
					-ResourceId $resource.ResourceId `
					-Enabled $True `
					-StorageAccountId $StrAccResId.ResourceId `
					-WorkspaceId $LogAnlyResId.ResourceId
			} else {
				Set-AzDiagnosticSetting -Name $DiagName `
					-ResourceId $resource.ResourceId `
					-Enabled $True `
					-WorkspaceId $LogAnlyResId.ResourceId
			}
							   
            #Log Error and success
            if (!$Error[0]) {
                Write-Output ("--- Diagnostics Successfully enabled on :" + $resource.Name)
                $Passed = $Passed + $resource.Name + " , " 
            }
            else {
                Write-Error ("!!! Error Occurred on :" + $resource.Name + "Error Message :" + $Error[0])
                $Failed = $Failed + $resource.Name + " , " 
            }
        }	
	}
	Write-Output ("Finished for Resource Group :" + $ResourceGroupName)
                
    If ($?) {
        Write-Output "Script executed successfully."
        Write-Output("Diagnostics Script Run Results ")
        Write-Output("======================================== ")
        Write-Output("======================================== ")
        $Passed
        $Failed
    }
}

#-----------------------------------------------------------[Execution]------------------------------------------------------------

# Script Execution goes here

# Execute Function
if($StorageAccName)
{
	EnableDiagnostics  $ResourceGroupName $LogAnalyticsWS $StorageAccName
} else {
	EnableDiagnostics  $ResourceGroupName $LogAnalyticsWS
}

Azure Key Vault – List Secrets that have not been set

When working across multiple environments, with restricted access, it can by difficult tracking which Key Vault secrets have been configured and which still need values set.

On my projects I like to give the dev teams autonomy on the dev environments setting their own Key Vault Keys and Secrets (following an agreed convention).

Periodically we then copy these keys to the other environment Key Vaults (see my other post on https://home-5012866824.webspace-host.com/wordpress/2021/08/09/azure-key-vault-script-for-copying-secrets-from-one-to-another/ )

The following script can be run to output all the Key Vault secrets, or only show the ones that need configuration. It can also be set to output pure markdown like…

# hms-sapp-kv-qa-ne (2021-07-03 14:31:04.590)

| Secret Name                                           | Needs Configuration                    |
|-------------------------------------------------------|----------------------------------------|
| apim-api-subscription-primary-key                     | ******                                 |
| apim-tests-subscription-primary-key                   | ******                                 |
| b2c-client-id-extensions-app                          | ******                                 |
| b2c-client-id-postman                                 | ******                                 |
| saleforce-client-id                                   | Needs Configuration                    |
| salesforce-client-secret                              | Needs Configuration                    |
| sql-database-ro-password                              | ******                                 |
| sql-database-rw-password                              | ******                                 |

that can be copy and pasted into the Azure or Github Wiki too and displays like the table below when rendered.

hms-sapp-kv-qa-ne (2021-07-03 14:31:04.590)

Secret Name Needs Configuration
apim-api-subscription-primary-key ******
apim-tests-subscription-primary-key ******
b2c-client-id-extensions-app ******
b2c-client-id-postman ******
saleforce-client-id Needs Configuration
salesforce-client-secret Needs Configuration
sql-database-ro-password ******
sql-database-rw-password ******

The script will output ‘Needs Configuration’ for any Secret values that are either blank, contain ‘Needs Configuration’ or ‘TBC’.

Script below, aslo contains examples:

<#PSScriptInfo
.VERSION 1.1
.GUName 48b4b27a-b77e-41e6-8a37-b3767da5caee
.AUTHOR Nicholas Rogoff

.RELEASENOTES
Initial version.
#>
<# 
.SYNOPSIS 
Copy Key Vault Secrets from one Vault to another. If the secret name exists it will NOT overwrite the value. 
 
.DESCRIPTION 
Loops through all secrets and copies them or fills them with a 'Needs Configuration'.
Will not copy secrets of ContentType application/x-pkcs12

PRE-REQUIREMENT
---------------
Run 'Import-Module Az.Accounts'
Run 'Import-Module Az.KeyVault'
You need to be logged into Azure and have the access necessary rights to both Key Vaults.

.INPUTS
None. You cannot pipe objects to this!

.OUTPUTS
None.

.PARAMETER SrcSubscriptionName
This is the Source Subscription Name

.PARAMETER SrcKvName
The name of the Source Key Vault

.PARAMETER MarkdownOnly
Output Markdown Only

.PARAMETER NameOnly
Set to only copy across the secret name and NOT the actual secret. The secret will be populated with 'Needs Configuration'

.NOTES
  Version:        1.1
  Author:         Nicholas Rogoff
  Creation Date:  2021-08-09
  Purpose/Change: Refined for publication
   
.EXAMPLE 
PS> .\List-UnSet-KeyVault-Secrets.ps1 -SrcSubscriptionName $srcSubscriptionName -SrcKvName $srcKvName 
This will list the secrets keys in the specified key vault and diplay 'Needs Configuration' for those that are blank, contain 'Needs Configuration' or 'TBC'

.EXAMPLE 
PS> .\List-UnSet-KeyVault-Secrets.ps1 -SrcSubscriptionName $srcSubscriptionName -SrcKvName $srcKvName -MarkdownOnly
Use for updating the Wiki. This will list the secrets keys, as MarkDown ONLY, in the specified key vault and diplay 'Needs Configuration' for those that are blank, contain 'Needs Configuration' or 'TBC'


.EXAMPLE 
PS> .\List-UnSet-KeyVault-Secrets.ps1 -SrcSubscriptionName $srcSubscriptionName -SrcKvName $srcKvName -ShowSecrets
This will list the secrets keys in the specified key vault and show the secrets


#>
#---------------------------------------------------------[Script Parameters]------------------------------------------------------
[CmdletBinding()]
Param(
  [Parameter(Mandatory = $true, HelpMessage = "This is the Source Subscription Name")]
  [string] $SrcSubscriptionName,
  [Parameter(Mandatory = $true, HelpMessage = "The name of the Source Key Vault")]
  [string] $SrcKvName,
  [Parameter(Mandatory = $false, HelpMessage = "Output Markdown Only")]
  [switch] $MarkdownOnly,
  [Parameter(Mandatory = $false, HelpMessage = "Output the secrets set")]
  [switch] $ShowSecrets
)

#---------------------------------------------------------[Initialisations]--------------------------------------------------------

# Set Error Action to Silently Continue
$ErrorActionPreference = 'Continue'

# Set Warnings Action to Silently Continue
$WarningPreference = "SilentlyContinue"

#----------------------------------------------------------[Declarations]----------------------------------------------------------
# Any Global Declarations go here

$SecretsFound = @()

#----------------------------------------------------------[Functions]----------------------------------------------------------

# Inline If Function
Function IIf($If, $Right, $Wrong) { If ($If) { $Right } Else { $Wrong } }

#-----------------------------------------------------------[Execution]------------------------------------------------------------

$checked = 0
$failed = 0

if (!$MarkdownOnly) {
  Write-Host "======================================================"
  Write-Host ($(Get-Date -Format 'yyyy-MM-dd HH:mm:ss.fff') + " Starting to check secrets in " + $SrcKvName + "... ") -ForegroundColor Blue
  Write-Host "======================================================"
}
else {
  Write-Host ("# " + $SrcKvName + " (" + $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss.fff') + ")") -ForegroundColor Blue
}
Write-Host ""



$sourceSecrets = Get-AzKeyVaultSecret -VaultName $SrcKvName | Where-Object { $_.ContentType -notmatch "application/x-pkcs12" }

if (!$MarkdownOnly) {
  # Headers
  Write-Host -NoNewline "|".PadRight(60, "-")
  Write-Host -NoNewline "|".PadRight(60, "-")
  Write-Host "|"
}

Write-Host -NoNewline "| Secret Name".PadRight(60)
if (!$ShowSecrets) {
  Write-Host -NoNewline "| Needs Configuration".PadRight(60)  
}
else {
  Write-Host -NoNewline "| Secret Value".PadRight(60)      
}
Write-Host "|"

Write-Host -NoNewline "|".PadRight(60, "-")
Write-Host -NoNewline "|".PadRight(60, "-")
Write-Host "|"

ForEach ($sourceSecret in $sourceSecrets) {
  $Error.clear()

  $name = $sourceSecret.Name
  $plainTxtSecret = Get-AzKeyVaultSecret -VaultName $srckvName -Name $name -AsPlainText

  if ($plainTxtSecret -eq "Needs Configuration" -or $plainTxtSecret -eq "TBC" -or !$plainTxtSecret) {
    $secretToShow = $plainTxtSecret
  }
  elseif ($ShowSecrets) {
    $secretToShow = $plainTxtSecret
  }
  else {
    $secretToShow = "******"
  }

  Write-Host -NoNewline "| $name".PadRight(60)
  if ($secretToShow -eq "Needs Configuration" -or $plainTxtSecret -eq "TBC" -or !$plainTxtSecret) {
    Write-Host -NoNewline "| $secretToShow".PadRight(60) -ForegroundColor Magenta  
  }
  else {
    Write-Host -NoNewline "| $secretToShow".PadRight(60) -ForegroundColor DarkGray      
  }
  Write-Host "|"

  if (!$Error[0]) {
    $checked += 1
  }
  else {
    $failed += 1
    Write-Error "!! Failed to get secret $name"
  }
}

if (!$MarkdownOnly) {
  Write-Host -NoNewline "|".PadRight(60, "-")
  Write-Host -NoNewline "|".PadRight(60, "-")    
  Write-Host "|"

  Write-Host ""
  Write-Host ""
  Write-Host "================================="
  Write-Host "Completed Key Vault Secrets Copy"
  Write-Host "Checked: $checked"
  Write-Host "Failed: $failed"
  Write-Host "================================="
}
else {
  Write-Host ""
  Write-Host ("**Total Secrets Listed: " + $checked + "**")
  if ($failed -gt 0) {
    Write-Host "Failed: $failed" -ForegroundColor Red
  } 
  Write-Host ""
}