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
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.