azurepowershellazure-cliazure-policy

Running Azure policy evaluation on demand getting the error Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred


I am trying to run Azure policy evaluation on demand. According to the documentation, there is an API that can be used to trigger this, and a Ps script. I have opted for the API since I have got 8 subscriptions and much easier to invoke the API at the subscription level.

$subscriptions = Get-AzSubscription | Where-Object Name -eq 'xxx'

foreach($subscription in $subscriptions){
    Set-AzContext -Subscription $subscription

    $SubscriptionId = $subscription.Id

    $azContext = Get-AzContext
    $azProfile = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile
    $profileClient = New-Object -TypeName Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient -ArgumentList ($azProfile)
    $token = $profileClient.AcquireAccessToken($azContext.Subscription.TenantId)

    $authHeader = @{
        'Content-Type'='application/json'
        'Authorization'='Bearer ' + $token.AccessToken
    }

    $restUri = "https://management.azure.com/subscriptions/$SubscriptionId/providers/Microsoft.PolicyInsights/policyStates/latest/triggerEvaluation?api-version=2018-07-01-preview"
       
    Invoke-RestMethod -Uri $restUrl -Method POST -Headers $authHeader

}

I then get the error below.

Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a receive.At line:1 char:1+ Invoke-RestMethod -Uri $restUrl -Method POST -Headers $authHeader + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

Having done some research, I have ran the following.

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 to no avail.


Solution

  • Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a receive.

    The above error is encountered because of passing the wrong Uri. The parameter mentioned in the code is $restUri, but in the Invoke-RestMethod command, you are passing $restUrl. If you still encounter the same issue, kindly update the PowerShell module to the latest version.

    Here is the updated PowerShell script to trigger evaluations.

        $subscriptions = Get-AzSubscription | Where-Object Name -eq 'xxxxxxxx'
        
        foreach ($subscription in $subscriptions) {
            Set-AzContext -Subscription $subscription
        
            $SubscriptionId = $subscription.Id
        
            $newtoken = Get-AzAccessToken -ResourceUrl "https://management.azure.com"
            $authHeader = @{
                'Content-Type'='application/json'
                'Authorization'='Bearer ' + $newtoken.Token
            }
        
            $restUri = "https://management.azure.com/subscriptions/$SubscriptionId/providers/Microsoft.PolicyInsights/policyStates/latest/triggerEvaluation?api-version=2018-07-01-preview"
        
            try {
                # Try to invoke the REST method
                Invoke-RestMethod -Uri $restUri -Method POST -Headers $authHeader
        
                # If successful, print a success message
                Write-Host "Policy evaluation triggered successfully for subscription: $SubscriptionId"
            } catch {
                # If an error occurs, print the error message and status code
                Write-Host "Failed to trigger policy evaluation for subscription: $SubscriptionId. $_"
                if ($_.Exception.Response -ne $null) {
                    $statusCode = $_.Exception.Response.StatusCode.value__
                    Write-Host "Response code: $statusCode"
                }
            }
        }
    

    Response:

    enter image description here

    Reference: Trigger evaluations for all resources in a subscription