PowerShell + REST APIs para monitorear el estado de MS Flows

En esta guía, aprenderemos cómo utilizar PowerShell junto con REST APIs y un Service Principal de Azure para monitorear el estado de varios Flows. Esto puede ser especialmente útil para administrar y automatizar alertas en flujos críticos.

iStock AI Generator

Crear un Service Principal en Azure

Antes de ejecutar el script, necesitarás crear un Service Principal en Azure. Este actuará como una identidad de aplicaciones que te permitirá autenticarte y realizar operaciones a través de las APIs de Azure.

Definir el ID de entorno y el alcance

El EnvironmentID corresponde al entorno de Microsoft Automate donde se encuentran tus flows.

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

Establecer los Flows a monitorear

Crea un hashtable con los nombres de los Flows que deseas monitorear y sus respectivos IDs.

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

Detalles del Service Principal

Proporciona los detalles de tu Service Principal: Tenant ID, Application ID y Secret.

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

Obtención del Token para el Service Principal

Realiza una solicitud para obtener un token de acceso que usaremos para autenticar nuestras llamadas 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

Configuración de headers para llamada a la API

Los headers incluirán el token de acceso y el tipo de contenido aceptado.

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

Creación de un Hashtable para almacenar el estado de fallo de los Flows

$flowFailureStatus = @{}

Iterar y procesar cada Flow

Realiza un bucle a través de cada Flow, verifica su estado y almacena el resultado en el 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 "------------------"
}

Código completo

Aquí tienes el script completo para monitorear el estado de tus Flows en 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