How to dis associate subnet from NATGateway using Azure SDK.

Shijun Lv 106 Reputation points Microsoft Employee
2024-04-17T07:00:51.18+00:00

0

I am using this method to associate NATGateway to a subnet.


            ArmClient azure = this.azureProvider.GetAzureClient(resourceTenantId, subscriptionId);

            var subnetId = SubnetResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, vNetName, subnetName);

            SubnetResource subnetResource = await azure.GetSubnetResource(subnetId).GetAsync();

            subnetResource.Data.NatGatewayId = ResourceIdentifier.Parse(natGatewayId);

            await subnetResource.UpdateAsync(waitUntil: WaitUntil.Completed, data: subnetResource.Data);

But I do not know how to disassociate it.

To disassociate it, if I use

            SubnetResource subnetResource = await azure.GetSubnetResource(subnetId).GetAsync();

            subnetResource.Data.NatGatewayId = null;

            await subnetResource.UpdateAsync(waitUntil: WaitUntil.Completed, data: subnetResource.Data);

Azure will throw exception "error":{"code":"InvalidRequestFormat","message":"Cannot parse the request.","details":[{"code":"MissingJsonReferenceId","message":"Value for reference id is missing. Path properties.natGateway."}] since the resourceId cannot be null.

Azure NAT Gateway
Azure NAT Gateway
NAT Gateway is a fully managed service that securely routes internet traffic from a private virtual network with enterprise-grade performance and low latency.
37 questions
0 comments No comments
{count} votes

Accepted answer
  1. ChaitanyaNaykodi-MSFT 26,216 Reputation points Microsoft Employee
    2024-04-19T00:20:47.92+00:00

    @Shijun Lv

    Thank you for reaching out.

    I understand you are trying to diss-associate the NAT Gateway from the subnet using Azure dotnet SDK.

    As you have correctly understood that this is currently not supported via dotnet SDK.

    If it helps, I was able to find work around in this case. The workaround is to invoke Management REST API Subnets - Create Or Update via code.

    I was successful in diss-associating the NAT Gateway using the REST API above and below is the code I implemented (the code is in crude state and can be enhanced).

    Code:

    using System.Net.Http.Headers;
    using System.Text;
    using Microsoft.Identity.Client;
    using Newtonsoft.Json.Linq;
    
    namespace AzureRestApiListSub
    {
    
        class Program
        {
            private static readonly HttpClient client = new HttpClient();
    
            static async Task Main(string[] args)
            {
                // Azure AD application details
                string clientId = "xxxxxxxxxxxxx";
                string clientSecret = "xxxxxxxxxxxxx";
                string tenantId = "xxxxxxxxxxxxx";
    
                // Azure REST API endpoint
                string apiVersion = "2023-09-01";
                string endpoint = $"https://management.azure.com/subscriptions?api-version={apiVersion}";
    
                {
                    // Set up the authentication context
                    var confidentialClientApplication = ConfidentialClientApplicationBuilder
                        .Create(clientId)
                        .WithClientSecret(clientSecret)
                        .WithAuthority(new Uri($"https://login.microsoftonline.com/{tenantId}"))
                        .Build();
    
                    string[] scopes = new string[] { "https://management.azure.com/.default" };
    
                    // Authenticate and acquire an access token
                    var authResult = await confidentialClientApplication
                        .AcquireTokenForClient(scopes)
                        .ExecuteAsync();
    
                    string accessToken = authResult.AccessToken;
    
                    var url = "https://management.azure.com/subscriptions/xxxxxxxxxxxxx/resourceGroups/xxxxxxxxxxxxx/providers/Microsoft.Network/virtualNetworks/xxxxxxxxxxxxx/subnets/xxxxxxxxxxxxx?api-version=2023-09-01";
    
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
    
    		//Invoke GET request first
    
                    HttpResponseMessage response = await client.GetAsync(url);
                    string json = await response.Content.ReadAsStringAsync();
    
    		//Parse JSON and remove the natGateway property
                    JObject jo = JObject.Parse(json);
                    JObject header = (JObject)jo.SelectToken("properties");
                    header.Property("natGateway").Remove();
                    string jsonpost = jo.ToString();
                    var content = new StringContent(jsonpost, Encoding.UTF8, "application/json");
                    Console.Write(jsonpost);
                    Console.WriteLine();
                    using HttpResponseMessage update = await client.PutAsync(url, content);
                    Console.WriteLine("Request with status code: " + update.StatusCode);
                }
            }
        }
    }
    
    
    

    I was able to implement it on my end

    User's image

    With associated NAT Gateway:

    User's image

    After the code is executed, the association is removed

    User's image

    I understand this not exactly a perfect workaround and I will report the limitation to the NAT Gateway Team.

    Hope this helps! Please let me know if you have any questions. Thank you!


    Please "Accept the answer" if the information helped you. This will help us and others in the community as well.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Anand Prakash Yadav 7,795 Reputation points Microsoft Vendor
    2024-04-18T10:49:06.7966667+00:00

    Hello Shijun Lv,

    Thank you for posting your query here!

    According to this MS-Document, disassociating the subnet from the NAT Gateway can be done by either through Azure portal or using Azure CLI commands.

    Command:

    az network vnet subnet update --resource-group <resource-group-name> --name <subnet-name> --vnet-name <vnet-name> --nat-gateway null
    
    

    Output:

    az network vnet subnet update --resource-group vxxx --name xx --vnet-name vxxx --nat-gateway null
    {
      "addressPrefix": "10.xxx/24",
      "delegations": [],
      "etag": "W/\"1059xxx4092f\"",
      "id": "/subscriptions/xxxx/resourceGroups/xxxx/providers/Microsoft.Network/virtualNetworks/vnet678/subnets/default",
      "name": "default",
      "networkSecurityGroup": {
        "id": "/subscriptions/xxxx/resourceGroups/xxxx/providers/Microsoft.Network/networkSecurityGroups/sampnat",
        "resourceGroup": "v-vsettu-mindtree"
      },
      "privateEndpointNetworkPolicies": "NetworkSecurityGroupEnabled",
      "privateLinkServiceNetworkPolicies": "Enabled",
      "provisioningState": "Succeeded",
      "resourceGroup": "vxe",
      "serviceEndpoints": [
        {
          "locations": [
            "eastus",
            "westus",
            "westus3"
          ],
          "provisioningState": "Succeeded",
          "service": "Microsoft.Storage"
        }
      ],
      "type": "Microsoft.Network/virtualNetworks/subnets"
    }
    

    User's image

    For further details: https://learn.microsoft.com/en-us/cli/azure/network/vnet/subnet?view=azure-cli-latest#az-network-vnet-subnet-update

    Reference: https://stackoverflow.com/questions/78338945/how-to-dis-associate-subnet-from-natgateway-using-azure-sdk

    I hope this helps! Please let me know if the issue persists or if you have any other questions.

    Please do not forget to "Accept the answer” and “up-vote” wherever the information provided helps you, this can be beneficial to other community members.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.