Network Interface Error and NicInUse error on Azure when creating VM from image using typescript & react

128 views Asked by At

I have an Azure subscription and an image I created.

Now, using my typescript / react code, I'd like to spawn more instances of the image I have.

Here's the code I have:

// pages/api/azure-create-instances.ts

import { ComputeManagementClient, VirtualMachine } from '@azure/arm-compute';
import { DefaultAzureCredential } from '@azure/identity';
import { NextApiRequest, NextApiResponse } from 'next';

const subscriptionId = process.env.AZURE_SUBSCRIPTION_ID!;
const resourceGroupName = 'Azure-test_group'; // Replace with your resource group name
const vmName = 'myVM'; // Replace with your desired VM name
const location = 'westeurope'; // Replace with your desired location
const vmSize = 'Standard_DS1_v2'; // Replace with your desired VM size
const imageId = `/subscriptions/${subscriptionId}/resourceGroups/Azure-test_group/providers/Microsoft.Compute/galleries/imgs_gallery1/images/test_img/versions/0.0.1`;
const networkId = `/subscriptions/${subscriptionId}/resourceGroups/Azure-test_group/providers/Microsoft.Network/networkInterfaces/azure-test666_z3`;

const createVM = async () => {
    try {
        // Authenticate using DefaultAzureCredential
        const creds = new DefaultAzureCredential();
        const computeClient = new ComputeManagementClient(creds, subscriptionId);

        // Define VM parameters
        const vmParams: VirtualMachine = {
            location,
            hardwareProfile: {
                vmSize,
            },
            networkProfile: {
                networkInterfaces: [
                    {
                        id: networkId,
                    },
                ],
            },
            storageProfile: {
                imageReference: {
                    id: imageId,
                },
            },
            osProfile: {
                computerName: vmName,
                adminUsername: 'myAdmin', // Replace with your desired admin username
                adminPassword: 'myPassword123!', // Replace with your desired admin password
            },
            // Other VM configurations
        };

        // Create VM
        const result = await computeClient.virtualMachines.beginCreateOrUpdate(resourceGroupName, vmName, vmParams);
        console.log('VM created:', result);
    } catch (err) {
        console.error('Error creating VM:', err);
    }
};

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
    return createVM().then(() => {
        res.send('success');
    });
}

now the problem is that I get the error NicInUse :

Error creating VM: RestError: Network Interface azure-test666_z3 is used by existing resource /subscriptions/<subscriptionId>/resourceGroups/Azure-test_group/providers/Microsoft.Compute/virtualMachines/Azure-test. In order to delete the network interface, it must be dissociated from the resource. To learn more, see aka.ms/deletenic.

and if I do not specify the networkInterfaces, I get the following error with code VirtualMachineMustHaveAtLeastOneNetworkInterface:

Error creating VM: RestError: Virtual machine /subscriptions/<subscriptionID>/resourceGroups/Azure-test_group/providers/Microsoft.Compute/virtualMachines/myVM must have at least one network interface. 

If I understand it correctly, the issue is that I do not have a specific network interface for the new instance, because I still have not created it, and it is important for me to be able to do it via the API (without logging directly to the Azure Portal). So I am looking for a solution that will allow me to create as many instances as I want from this image --> without the need to create a new network interface manually.

Do I understand the issue correctly?

Any suggestions on how to resolve it?

0

There are 0 answers