Eliminación de blobs de almacenamiento de registros de flujo de grupo de seguridad de red en Network WatcherDelete network security group flow log storage blobs in Network Watcher

Actualmente existe un problema por el que los registros de flujo del grupo de seguridad de red (NSG) en Network Watcher no se eliminan automáticamente del almacenamiento de blobs en función de la configuración de la directiva de retención.Currently, there’s an issue where network security group (NSG) flow logs for Network Watcher are not automatically deleted from Blob storage based on retention policy settings. Ahora, hay que ejecutar un script de PowerShell para eliminar manualmente los registros de flujo de la cuenta de almacenamiento, tal y como se describe en este artículo.You must now run a PowerShell script to manually delete the flow logs from your storage account as described in this article.

Ejecución de un script de PowerShell para eliminar registros de flujo de NSGRun PowerShell script to delete NSG flow logs

Copie y guarde el siguiente script en una ubicación, como el directorio donde esté trabajando actualmente.Copy and save the following script to a location such as your current working directory.

# This powershell script deletes all NSG flow log blobs that should not be retained anymore as per configured retention policy.
# While configuring NSG flow logs on Azure portal, the user configures the retention period of NSG flow log blobs in
# their storage account (in days).
# This script reads all blobs and deletes blobs that are not to be retained (outside retention window)
# if the retention days are zero; all blobs are retained forever and hence no blobs are deleted.
#
#

param (
        [string] [Parameter(Mandatory=$true)]  $SubscriptionId,
        [string] [Parameter(Mandatory=$true)]  $Location,
        [switch] [Parameter(Mandatory=$false)] $Confirm
    )

Login-AzAccount

$SubId = Get-AzSubscription| Where-Object {$_.Id.contains($SubscriptionId.ToLower())}

if ($SubId.Count -eq 0)
{
    Write-Error 'The SubscriptionId does not exist' -ErrorAction Stop
}

Set-AzContext -SubscriptionId $SubscriptionId

$NsgList = Get-AzNetworkSecurityGroup | Where-Object {$_.Location -eq $Location}
$NW = Get-AzNetworkWatcher | Where-Object {$_.Location -eq $Location}

$FlowLogsList = @()
foreach ($Nsg in $NsgList)
{
    # Query Flow Log Status which are enabled
    $NsgFlowLog = Get-AzNetworkWatcherFlowLogStatus -NetworkWatcher $NW -TargetResourceId $Nsg.Id | Where-Object {$_.Enabled -eq "True"}
    if ($NsgFlowLog.Count -gt 0)
    {
        $FlowLogsList +=  $NsgFlowLog
        Write-Output ('Enabled NSG found: ' +  $NsgFlowLog.TargetResourceId)
    }
}

foreach ($Psflowlog in $FlowLogsList)
{
    $RetentionDays = $Psflowlog.RetentionPolicy.Days
    if ($RetentionDays -le 0)
    {
        continue
    }

    $Strings = $Psflowlog.StorageId -split '/'
    $RGName = $Strings[4]
    $StorageAccountName = $Strings[-1]

    $Key = (Get-AzStorageAccountKey -ResourceGroupName $RGName -Name $StorageAccountName).Value[1]
    $StorageAccount = New-AzStorageContext -StorageAccountName $StorageAccountName -StorageAccountKey $Key

    $ContainerName = 'insights-logs-networksecuritygroupflowevent'  
    $BLobsList = Get-AzStorageBlob -Container $ContainerName -Context $StorageAccount.Context

    $TargetBLobsList = $BLobsList | Where-Object {$_.Name.contains($Psflowlog.TargetResourceId.ToUpper())}

    $RetentionDate = Get-Date
    $RetentionDate = $RetentionDate.AddDays(-1*$RetentionDays)
    $RetentionDateInUTC = $RetentionDate.ToUniversalTime()

    foreach ($Blob in $TargetBLobsList)
    {
        $BlobLastModifietedDTinUTC = [datetime]$Blob.LastModified.UtcDateTime

        if ($BlobLastModifietedDTinUTC -ge  $RetentionDateInUTC)
        {
            Write-Output ($Blob.Name + '===>' + $BlobLastModifietedDTinUTC  + ' ===> RETAINED')
            continue
        }

        if ($Confirm)
        {
            Write-Output (Blob to be deleted: $Blob.Name)
            $Confirmation = Read-Host "Are you sure you want to remove this blob (Y/N)?"
        }

        if ((-not $Confirm) -or ($Confirmation -eq 'Y'))
        {
            Write-Output ($Blob.Name + '===>' + $BlobLastModifietedDTinUTC  + ' ===> DELETED')
            Remove-AzStorageBlob -Container $ContainerName -Context $StorageAccount.Context -Blob $Blob.Name
        }
        else
        {
            Write-Output ($Blob.Name + '===>' + $BlobLastModifietedDTinUTC  + ' ===> RETAINED')
        }
    }
}

Write-Output ('Retention policy for all NSGs evaluated and completed successfully')
  1. Escriba los siguientes parámetros en el script según sea necesario:Enter the following parameters in the script as needed:

    • SubscriptionId (obligatorio): identificador de la suscripción desde la que quiere eliminar los blobs de registro de flujo de NSG.SubscriptionId [Mandatory]: The subscription ID from where you would like to delete NSG Flow Log blobs.
    • Location (obligatorio): cadena de ubicación de la región de los registros NSG donde quiere eliminar los blobs de registro de flujo de NSG.Location [Mandatory]: The location string of the region of the NSGs for which you would like to delete NSG Flow Log blobs. Esta información se puede encontrar en Azure Portal o en GitHub.You can view this information on the Azure portal or on GitHub.
    • Confirm (opcional): pase la marca de confirmación en caso de que quiera confirmar manualmente la eliminación de cada blob de almacenamiento.Confirm [Optional]: Pass the confirm flag if you want to manually confirm the deletion of each storage blob.
  2. Ejecute el script guardado como se muestra en el siguiente ejemplo, donde el archivo de script se guardó como Delete-NsgFlowLogsBlobs.ps1:Run the saved script as shown in the following example, where the script file was saved as Delete-NsgFlowLogsBlobs.ps1:

    .\Delete-NsgFlowLogsBlobs.ps1 -SubscriptionId <subscriptionId> -Location  <location> -Confirm
    

Pasos siguientesNext steps