PowerShell + API REST pour surveiller l'état des MS Flows

Traduit de l'original en espagnol. Lire en espagnol

Dans ce guide, nous allons voir comment utiliser PowerShell avec des API REST et un Service Principal Azure pour surveiller l’état de plusieurs Flows. Cela peut être particulièrement utile pour gérer et automatiser les alertes sur des flux critiques.

iStock AI Generator

Créer un Service Principal dans Azure

Avant d’exécuter le script, vous devrez créer un Service Principal dans Azure. Il agit comme une identité d’application qui vous permet de vous authentifier et d’effectuer des opérations via les API Azure.

Définir l’ID d’environnement et la portée

L’EnvironmentID correspond à l’environnement Microsoft Automate où se trouvent vos flows.

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

Définir les Flows à surveiller

Créez une hashtable avec les noms des Flows que vous souhaitez surveiller et leurs ID respectifs.

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

Détails du Service Principal

Indiquez les détails de votre Service Principal : Tenant ID, Application ID et Secret.

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

Obtention du token pour le Service Principal

Envoyez une requête pour obtenir un token d’accès, que nous utiliserons pour authentifier nos appels 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

Configuration des headers pour l’appel à l’API

Les headers contiendront le token d’accès et le type de contenu accepté.

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

Création d’une hashtable pour stocker l’état d’échec des Flows

$flowFailureStatus = @{}

Parcourir et traiter chaque Flow

Parcourez chaque Flow dans une boucle, vérifiez son état et enregistrez le résultat dans la 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 "------------------"
}

Code complet

Voici le script complet pour surveiller l’état de vos Flows avec 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