PowerShell + REST APIs para monitorar o status de MS Flows

Traduzido do original em espanhol. Ler em espanhol

Neste guia, vamos aprender a usar PowerShell junto com REST APIs e um Service Principal do Azure para monitorar o status de vários Flows. Isso pode ser especialmente útil para gerenciar e automatizar alertas em fluxos críticos.

iStock AI Generator

Criar um Service Principal no Azure

Antes de executar o script, você precisará criar um Service Principal no Azure. Ele funciona como uma identidade de aplicativo que permite se autenticar e realizar operações por meio das APIs do Azure.

Definir o ID do ambiente e o escopo

O EnvironmentID corresponde ao ambiente do Microsoft Automate onde estão seus flows.

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

Definir os Flows a monitorar

Crie um hashtable com os nomes dos Flows que você quer monitorar e seus respectivos IDs.

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

Detalhes do Service Principal

Informe os detalhes do seu 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"

Obtenção do token para o Service Principal

Faça uma requisição para obter um token de acesso, que usaremos para autenticar nossas chamadas à 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

Configuração dos headers da chamada à API

Os headers incluirão o token de acesso e o tipo de conteúdo aceito.

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

Criação de um hashtable para armazenar o status de falha dos Flows

$flowFailureStatus = @{}

Iterar e processar cada Flow

Percorra cada Flow em um loop, verifique seu status e armazene o resultado no 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

Aqui está o script completo para monitorar o status dos seus Flows em 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