Wednesday, February 19, 2020

Resolving Queue Creation Script Failures Due to Delay in Applying Default Action of a Azure Storage Account in IaC

This post discusses an issue faced, while trying to allow in the default action of a storage account,  running PowerShell based Azure CLI, Infrastructure as code.

Issue : Requirement is to create a new azure storage queue using the PowerShell script in an existing storage account which is attached to a vnet and have access restrictions applied. Hence, the script needs to remove the restrictions to storage by setting Defualt Action to allow and then  create new storage queue. Once the new queue added to the storage, restrict the storage account access again. However, the time delay to apply the removal of restriction sometimes create an a hoc issue as the next step to create the queue fails with, network access error.

Queue named stq-sample-queue not found in Storage Account testsstorage . Creating it...
ERROR: 
The request may be blocked by network rules of storage account. Please check network rule set using 'az storage account show -n account name --query networkRuleSet'.
If you want to change the default action to apply when no rule matches, please use 'az storage account update'

This failure occurs due to azure storage doesn't updated soon after the script executed. Once we enable the storage account default action to allow, through script it takes some time to apply the change in azure side. So, when we try to create the storage queue storage is still under vnet restriction, which causes a failure. As a solution we can add a do while loop to the script to check whether  storage account default action is set to allow or not. It will exit from the loop when default action to allow outside vnet to storage account. It fix the issue and allow to add new queue to the storage account.

Following is the script used to fix the issue.


function Allow-StorageAccountOutsideVNetAccess
{
    Param(
    [Parameter(Mandatory=$true)]
    [string] $name
    )

    # Set unique name for storage
    $storageAccountName = (Generate-StorageAccountName -name $name);
    

    Write-Host ("Applying storage account " + $storageAccountName + " access rule as  Allow...")
    az storage account update -n $storageAccountName -g $storageAccountResourceGroupName `
        --bypass $storageAccountByPass --default-action 'Allow' 

    if ($LastExitCode -ne 0) {
            throw $Error[1]
    }
    Write-Host ("Done.")
    $storageNetworkAccess="Deny";
   Do {
        
        Start-Sleep -Milliseconds 300
        $stagAcc=az storage account show -g $storageAccountResourceGroupName -n $storageAccountName | ConvertFrom-Json
        $storageNetworkAccess= $stagAcc.networkRuleSet.defaultAction
      
      } Until ($storageNetworkAccess -eq "Allow")
}

No comments:

Post a Comment