Skip to content

Send an email when policy-based VPN connection is down (Powershell)

I was trying to implement a solution for one of my customers using Azure Automation, the customer simply requested that he needs a notifying solution to alert the Azure admin by email when a VPN connection (between Azure and his on-premises) is down.

First I used this script in the below article:

# Set these variables to the proper values for your environment
$o365AutomationCredential = "<Office 365 account>"
$fromEmail = "<from email address>"
$toEmail = "<to email address>"
$smtpServer = "<smtp.office365.com>"
$smtpPort = 587
$runAsConnectionName = "<AzureRunAsConnection>"
$subscriptionId = "<subscription id>"
$region = "<Azure region>"
$vpnConnectionName = "<vpn connection name>"
$vpnConnectionResourceGroup = "<resource group name>"
$storageAccountName = "<storage account name>"
$storageAccountResourceGroup = "<resource group name>"
$storageAccountContainer = "<container name>"

# Get credentials for Office 365 account
$cred = Get-AutomationPSCredential -Name $o365AutomationCredential

# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection=Get-AutomationConnection -Name $runAsConnectionName

"Logging in to Azure..."
Connect-AzureRmAccount `
    -ServicePrincipal `
    -TenantId $servicePrincipalConnection.TenantId `
    -ApplicationId $servicePrincipalConnection.ApplicationId `
    -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
"Setting context to a specific subscription"
Set-AzureRmContext -SubscriptionId $subscriptionId

$nw = Get-AzurermResource | Where {$_.ResourceType -eq "Microsoft.Network/networkWatchers" -and $_.Location -eq $region }
$networkWatcher = Get-AzureRmNetworkWatcher -Name $nw.Name -ResourceGroupName $nw.ResourceGroupName
$connection = Get-AzureRmVirtualNetworkGatewayConnection -Name $vpnConnectionName -ResourceGroupName $vpnConnectionResourceGroup
$sa = Get-AzureRmStorageAccount -Name $storageAccountName -ResourceGroupName $storageAccountResourceGroup 
$storagePath = "$($sa.PrimaryEndpoints.Blob)$($storageAccountContainer)"
$result = Start-AzureRmNetworkWatcherResourceTroubleshooting -NetworkWatcher $networkWatcher -TargetResourceId $connection.Id -StorageId $sa.Id -StoragePath $storagePath

if($result.code -ne "Healthy")
    {
        $body = "Connection for $($connection.name) is: $($result.code) `n$($result.results[0].summary) `nView the logs at $($storagePath) to learn more."
        Write-Output $body$subject = "$($connection.name) Status"
        Send-MailMessage `
        -To $toEmail `
        -Subject $subject `
        -Body $body `
        -UseSsl `
        -Port $smtpPort `
        -SmtpServer $smtpServer `
        -From $fromEmail `
        -BodyAsHtml `
        -Credential $cred
    }
else
    {
    Write-Output ("Connection Status is: $($result.code)")
    }

https://docs.microsoft.com/en-us/azure/network-watcher/network-watcher-monitor-with-azure-automation

But after implementing the suggested solution it turns out that Start-AzureRmNetworkWatcherResourceTroubleshooting cmdlet used in the script doesn’t support PolicyBased VPN connection

https://docs.microsoft.com/en-us/azure/network-watcher/network-watcher-troubleshoot-overview

So I had to think of a workaround and I could find a simpler yet very helpful one using Azure Automation too.

The script is:

# Set these variables to the proper values for your environment
$o365AutomationCredential = "<Office 365 account>"
$fromEmail = "<from email address>"
$toEmail = "<to email address>"
$smtpServer = "smtp.office365.com"
$smtpPort = 587
$runAsConnectionName = "<AzureRunAsConnection>" 
$subscriptionId = "<subscription id>"
$region = "<Azure region>"
$vpnConnectionName = "<vpn connection name>"
$vpnConnectionResourceGroup = "<resource group name>"


# Get credentials for Office 365 account
$cred = Get-AutomationPSCredential -Name $o365AutomationCredential



"Logging in to Azure..."
Add-AzureRmAccount -TenantId "<TenantId>" -SubscriptionId "<SubscriptionId>" -Credential $Cred


"Setting context to a specific subscription"
Set-AzureRmContext -SubscriptionId $subscriptionId




$connection = Get-AzureRmVirtualNetworkGatewayConnection -Name $vpnConnectionName -ResourceGroupName $vpnConnectionResourceGroup

$status = Get-AzureRmVirtualNetworkGatewayConnection -Name Azure-to-A2A -ResourceGroupName TESTVM | Format-Table  connectionstatus | Out-String -Stream 




if(($status[3]) -match "Connected")

    {
      Write-Output ("Connection Status is: $($status[3])")  

    }
else
    {
    
    
    $body = "Connection for $($connection.name) is: $($status[3]) *NOT CONNECTED* "
        Write-Output $body$subject = "$($connection.name) Status"
        Send-MailMessage `
        -To $toEmail `
        -Subject $subject `
        -Body $body `
        -UseSsl `
        -Port $smtpPort `
        -SmtpServer $smtpServer `
        -From $fromEmail `
        -BodyAsHtml `
        -Credential $cred
    }

As you can see we didn’t use any of Azure Network Watcher functions therefore we have lost the privileges to save any logs that are related to the connection status and there’s no need to use a storage account anymore.

The core of the script is this cmdlet

$status = Get-AzureRmVirtualNetworkGatewayConnection -Name Azure-to-A2A -ResourceGroupName TESTVM | Format-Table  connectionstatus | Out-String -Stream

it will store the result of Get-AzureRmVirtualNetworkGatewayConnection (only the connection status) into an array of strings $status.

Please note that if you used Get-AzureRmVirtualNetworkGatewayConnection with only the Resource Group Name as a parameter it will return any result for the connection status

to get the correct result you have to specify the connection name as a parameter

then what are we doing is simply to format it and convert it to an array of string using | Out-String -Stream

The rest is a basic if statement

if($status -match "Connected")

it checks if the array we made contains the string “connected” if not then we have a problem and the connection might be down so it will send an email to the admin.

This script is also available on TechNet

https://gallery.technet.microsoft.com/Send-an-email-when-policy-67546fdc

Please let me know if you’re aware of any other solutions or workarounds, or if you have any comments or suggestions on the solution provided.

Spread the love
Published inAzure Networking

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *