Search code examples
c#azureazure-virtual-networkazure-sdk-.netazure-devtest-labs

Configure a Virtual Network in Azure DevTest Labs - programmatically (c#)


I'm trying to create a brand new network with two address spaces (10.0.0.0/20 and 10.0.16.0/20) and, most importantly, set useInVmCreationPermission and usePublicIpAddressPermission to Allow.

I have the lab already created and I'm able to create a network but I'm unable to relate them with each other. I'm not sure if it's possible through the REST API but if the portal does it, I'm pretty sure it can be achieved (even if I had to use HttpClient). The way it's done in the Azure Portal, is described here: https://learn.microsoft.com/en-us/azure/devtest-labs/devtest-lab-configure-vnet .

This is my code:

private async Task Create(IAzure azureClient, DbLab dbLab)
{
    var virtualNetworkId = Guid.NewGuid().ToString();
    var virtualNetwork = await azureClient
        .Networks
        .Define(virtualNetworkId)
        .WithRegion(dbLab.Region.Value)
        .WithExistingResourceGroup(dbLab.ResourceGroupName)
        .WithAddressSpace(Consts.IPv4DynamicAddressSpace)
        .WithAddressSpace(Consts.IPv4StaticAddressSpace)
        .WithSubnet($"{virtualNetworkId}_dynamic", Consts.IPv4DynamicAddressSpace)
        .WithSubnet($"{virtualNetworkId}_static", Consts.IPv4StaticAddressSpace)
        .CreateAsync();

    var fragment = new VirtualNetworkFragment(
        subnetOverrides: virtualNetwork.Subnets.Select(s =>
            new SubnetOverrideFragment(
                resourceId: s.Value.Name,
                useInVmCreationPermission: "Allow",
                usePublicIpAddressPermission: "Allow")).ToList());

    // fails because vnet is not related to that lab
    var vnet = await BaseClientFactory.CreateDevTestLabClient(azureClient)
        .VirtualNetworks
        .UpdateAsync(dbLab.ResourceGroupName, dbLab.LabId.ToString(), virtualNetworkId, fragment);
}

How do I attach a lab to the vnet programmatically in c#?


Solution

  • Yes, you can configure your existing virtual network to a lab's Virtual Network settings via both the REST API and the SDK as well.

    REST API: Virtual Networks - Create Or Update

    PUT https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualnetworks/{name}?api-version=2018-09-15
    

    Note that resourceGroupName is the name of the resource group where the DevTest Lab exists, and not that of the VNet.

    Here is the equivalent method in the .Net SDK: CreateOrUpdateWithHttpMessagesAsync