PowerShell + API REST per monitorare lo stato dei MS Flow

Tradotto dall'originale in spagnolo. Leggi in spagnolo

In questa guida impareremo a usare PowerShell insieme alle API REST e a un Service Principal di Azure per monitorare lo stato di diversi Flow. Può essere particolarmente utile per gestire e automatizzare gli avvisi sui flussi critici.

iStock AI Generator

Creare un Service Principal in Azure

Prima di eseguire lo script, dovrai creare un Service Principal in Azure. Funziona come un’identità applicativa che ti permette di autenticarti ed eseguire operazioni tramite le API di Azure.

Definire l’ID dell’ambiente e l’ambito

L’EnvironmentID corrisponde all’ambiente di Microsoft Automate in cui si trovano i tuoi flow.

$environmentId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"  
$scope = "https://service.flow.microsoft.com//.default"

Impostare i Flow da monitorare

Crea una hashtable con i nomi dei Flow che vuoi monitorare e i rispettivi ID.

$taskFlows = @{
    "Flow1" = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
    "Flow2" = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
    # Agrega más Flows si es necesario
}

Dettagli del Service Principal

Fornisci i dettagli del tuo Service Principal: Tenant ID, Application ID e Secret.

$tenantId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"  
$appId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"  
$appSecret = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"

Ottenere il token per il Service Principal

Invia una richiesta per ottenere un token di accesso, che useremo per autenticare le chiamate all’API.

$body = @{  
    grant_type    = "client_credentials"  
    client_id     = $appId  
    client_secret = $appSecret  
    scope         = $scope
}  
$tokenUrl = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"  
$tokenResponse = Invoke-RestMethod -Uri $tokenUrl -Method Post -Body $body  
$token = $tokenResponse.access_token

Configurare gli header per la chiamata all’API

Gli header includeranno il token di accesso e il tipo di contenuto accettato.

$headers = @{  
    Authorization = "Bearer $token"  
    'Content-Type' = 'application/json'  
}

Creare una hashtable per memorizzare lo stato di errore dei Flow

$flowFailureStatus = @{}

Iterare ed elaborare ogni Flow

Esegui un ciclo su ogni Flow, verificane lo stato e salva il risultato nella hashtable.

foreach ($key in $taskFlows.Keys) {
    Write-Output "Processing: $key"
    Write-Output "FlowName: $($taskFlows[$key])"
    Write-Output "------------------"
    $taskFlowID = $($taskFlows[$key])
    $apiUrl = "https://api.flow.microsoft.com/providers/Microsoft.ProcessSimple/environments/$environmentId/flows/$taskFlowID/runs?api-version=2016-11-01&$top=50"

    try {
        $response = Invoke-RestMethod -Uri $apiUrl -Headers $headers -Method Get

        if ($key -eq "Flow1") {
            $runningCount = ($response.value | Where-Object { $_.properties.status -eq 'Running' }).Count
            if ($runningCount -eq 5) {
                Write-Output "Flow Alert: at least 5 jobs are still running in the Flow1 flow."
            }
        }

        $failedCount = ($response.value | Where-Object { $_.properties.status -eq 'Failed' }).Count

        if ($failedCount -gt 5) {
            Write-Output "The flow has failed more than 5 times."
            $flowFailureStatus[$key] = $true
        }
    } catch {
        Write-Output "Failed to retrieve flow run history for: $key"
        Write-Output $_.Exception.Message
        $flowFailureStatus[$key] = $null
    }
    Write-Output "------------------"
}

Codice completo

Ecco lo script completo per monitorare lo stato dei tuoi Flow con PowerShell:

$environmentId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"  
$scope = "https://service.flow.microsoft.com//.default"

$taskFlows = @{
    "Flow1" = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
    "Flow2" = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
    # ... (agrega tantos Flows como necesites)
}

$tenantId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"  
$appId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"  
$appSecret = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"

# Acquire Token for Service Principal  
$body = @{  
    grant_type    = "client_credentials"  
    client_id     = $appId  
    client_secret = $appSecret  
    scope         = $scope
}  
$tokenUrl = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"  
$tokenResponse = Invoke-RestMethod -Uri $tokenUrl -Method Post -Body $body  
$token = $tokenResponse.access_token  

$headers = @{  
    Authorization = "Bearer $token"  
    'Content-Type' = 'application/json'  
}  

$flowFailureStatus = @{}

foreach ($key in $taskFlows.Keys) {
    Write-Output "Processing: $key"
    Write-Output "FlowName: $($taskFlows[$key])"
    Write-Output "------------------"
    $taskFlowID = $($taskFlows[$key])
    $apiUrl = "https://api.flow.microsoft.com/providers/Microsoft.ProcessSimple/environments/$environmentId/flows/$taskFlowID/runs?api-version=2016-11-01&$top=50"

    try {
        $response = Invoke-RestMethod -Uri $apiUrl -Headers $headers -Method Get

        if ($key -eq "Flow1") {
            $runningCount = ($response.value | Where-Object { $_.properties.status -eq 'Running' }).Count

            if ($runningCount -eq 5) {
                Write-Output "Flow Alert: at least 5 jobs are still running in the Flow1 flow."
            }
        }

        $failedCount = ($response.value | Where-Object { $_.properties.status -eq 'Failed' }).Count

        if ($failedCount -gt 5) {
            Write-Output "The flow has failed more than 5 times."
            $flowFailureStatus[$key] = $true
        }
    } catch {
        Write-Output "Failed to retrieve flow run history for: $key"
        Write-Output $_.Exception.Message
        $flowFailureStatus[$key] = $null
    }
    Write-Output "------------------"
}

if ($flowFailureStatus.Count -gt 0) {
    Write-Host "Flows that have failed the last 5 times:"
    foreach ($flow in $flowFailureStatus.GetEnumerator()) {
        if ($flow.Value -eq $true) {
            Write-Host "Flow: $($flow.Key) - Failed 5 times consecutively"
        }
    }
} else {
    Write-Host "No flows have failed the last 5 times."
}

Maximiliano Díaz Doglia

AI Platform Engineer & Full-Stack Developer
Building Enterprise Integrations & Automations