Search code examples
azurepowershellazure-cliazure-storage-account

How can I test for when an Azure Storage Account network rule has actually taken effect


I have a pipeline that will whitelist the agents current IP to a storage account's network rules with:

az storage account network-rule add

It then immediately moves to the next task which requires access within one of the storage account's containers. Because there is a 5-30 second period where the network rule is taking effect, the task needs retry logic because it almost always returns:

autorest/azure: Service returned an error. Status=403 Code="AuthorizationFailure" Message="This request is not authorized to perform this operation

After enough time and retries have passed, then task will then happily continue. I was wondering if there was a recommended method for writing a loop that tests access to the container and only exits the loop when the firewall rule has actually been applied.


Solution

  • I tried in my environment and got the below results:

    How can I test for when an Azure Storage Account network rule has actually taken effect

    You can use the below powershell command to tests access to the container after network rule applied.

    Command:

    $storageAccountName = ""
    $resourceGroupName = ""
    $containerName = ""
    $currentIP = ""
    $storageAccountKey=""
     # Add the current IP to the network rule
    az storage account network-rule add --resource-group $resourceGroupName --account-name $storageAccountName --ip-address $currentIP
    
    Start-Sleep -Seconds 30
    
     # Wait for the network rule to take effect
    while ($true)
    {
        # Test access to the container
        try {
            Get-AzStorageBlob -Container $containerName -Context (New-AzStorageContext -StorageAccountName $storageAccountName -StorageAccountKey $storageAccountKey)
    # If the access is successful, exit the loop
           break
        }
        catch {
            # Wait for 10 seconds before trying again
            Start-Sleep -Seconds 5
        }
    }
    

    Output:

    enter image description here

    Portal:

    enter image description here