Search code examples
azureazure-storagefirewallrest

How to programatically update Azure Storage firewall settings


I am using Azure Storage, and it allows to control access by managing "Firewall and Virtual Network" settings from the Azure portal.
Is there a way to do the same via API? I did some documentation search but could not find APIs which can do this.
Any pointer around this will be helpful.


Solution

  • If you want to update Azure Storage Firewall via API, you want to use the following Rest API to implement it. For more details, please refer to here

    PATCH https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}?api-version=2019-06-01
    
    Authorization: Bearer <access token>
    
    {
      "properties": {
        "networkAcls": {
          "bypass": "string",
          "virtualNetworkRules": [
            {
              "id": "string",
              "action": "Allow",
              "state": "string"
            }
          ],
          "ipRules": [
            {
              "value": "string",
              "action": "Allow"
            }
          ],
          "defaultAction": "string"
         }
      }
    }
    
    

    For example

    1. Create a service principal and assign Contributor role to the sp
    az login
    # create sp and assign Contributor to the sp at the subscription level
    az ad sp create-for-rbac -n "your service principal name"
    
    1. Get Token
    POST https://login.microsoftonline.com/<tenant id>/oauth2/v2.0/token
    Content-Type: application/x-www-form-urlencoded
    
    grant_type=client_credentials
    &scope=https://management.azure.com/.default
    &client_id=<sp appId>
    &client_secret=<sp password>
    
    1. Test (I update the account's firewall to allow some IP and AzureServices to access storage).
    PATCH https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}?api-version=2019-06-01
    
    Authorization: Bearer <access token>
    
    {
      "properties": {
            "networkAcls": {
                "bypass": "AzureServices",
                "virtualNetworkRules": [],
                "ipRules": [
                    {
                        "value": "167.220.255.0/24",
                        "action": "Allow"
                    }
                ],
                "defaultAction": "Deny"
            }
       }
    }
    

    result