Manage Azure Virtual Machines with JavaScript

The Azure SDK for JavaScript provides a comprehensive set of tools and libraries to programmatically manage Azure Virtual Machines (VMs). This documentation guides you through creating, configuring, and managing your VMs using JavaScript, empowering you to automate infrastructure tasks and build scalable cloud solutions.

Leverage the power of Azure compute services to deploy and manage virtual machines tailored to your application's needs. Whether you're setting up web servers, development environments, or complex application backends, the JavaScript SDK offers a streamlined and efficient way to interact with Azure VM resources.

Note: This SDK primarily focuses on the Azure Compute resource provider, enabling deep integration with VM operations.

Installation

To get started, install the necessary Azure SDK packages for JavaScript:


npm install @azure/arm-compute @azure/identity
                

Authentication

Securely authenticate your application with Azure using the @azure/identity package. This package provides various credential types, such as environment credentials or managed identity credentials, suitable for different deployment scenarios.

A common approach is to use DefaultAzureCredential, which attempts authentication in a sensible order:


import { DefaultAzureCredential } from "@azure/identity";
import { ComputeManagementClient } from "@azure/arm-compute";

const credential = new DefaultAzureCredential();
const subscriptionId = process.env["AZURE_SUBSCRIPTION_ID"]; // Or get from configuration

const computeClient = new ComputeManagementClient(credential, subscriptionId);
                

Core Concepts

Creating a Virtual Machine

Creating a VM involves defining its properties, including size, image, network configuration, and disk settings. Here's a simplified example of creating a basic Linux VM:


async function createVm(computeClient, resourceGroupName, vmName) {
    const vmParameters = {
        location: "eastus",
        hardwareProfile: { vmSize: "Standard_B1s" },
        storageProfile: {
            imageReference: {
                publisher: "Canonical",
                offer: "UbuntuServer",
                sku: "18.04-LTS",
                version: "latest"
            },
            osDisk: {
                createOption: "FromImage",
                managedDisk: { storageAccountType: "Standard_LRS" }
            }
        },
        osProfile: {
            computerName: vmName,
            adminUsername: "azureuser",
            adminPassword: "yourSecurePassword!" // Consider using SSH keys for production
        },
        networkProfile: {
            networkInterfaces: [
                {
                    id: "/subscriptions/YOUR_SUB_ID/resourceGroups/RESOURCE_GROUP_NAME/providers/Microsoft.Network/networkInterfaces/YOUR_NIC_NAME",
                    primary: true
                }
            ]
        }
    };

    const poller = await computeClient.virtualMachines.beginCreateOrUpdate(
        resourceGroupName,
        vmName,
        vmParameters
    );
    const vm = await poller.pollUntilDone();
    console.log(`VM ${vmName} created successfully.`);
    return vm;
}
                
Tip: For production environments, always use SSH key pairs for authentication instead of passwords.

Managing Virtual Machines

You can perform various management operations on existing VMs:

  • Starting a VM: computeClient.virtualMachines.beginStart(resourceGroupName, vmName)
  • Stopping a VM: computeClient.virtualMachines.beginPowerOff(resourceGroupName, vmName)
  • Deallocating a VM: computeClient.virtualMachines.beginDeallocate(resourceGroupName, vmName)
  • Restarting a VM: computeClient.virtualMachines.beginRestart(resourceGroupName, vmName)
  • Deleting a VM: computeClient.virtualMachines.beginDelete(resourceGroupName, vmName)

VM Sizing

Choosing the right VM size is crucial for performance and cost-effectiveness. You can list available VM sizes for a location:


async function listVmSizes(computeClient, location) {
    const vmSizes = await computeClient.virtualMachines.listSizes(location);
    console.log(`Available VM sizes in ${location}:`);
    vmSizes.forEach(size => console.log(`- ${size.name} (${size.numberOfCores} vCPUs, ${size.memoryInMB} MB RAM)`));
}
                

VM Disks

Virtual Machines rely on managed disks for operating system and data storage. You can manage disk types (Standard HDD, Standard SSD, Premium SSD, Ultra Disk) and sizes when creating or updating VMs.

Code Examples

Explore the following comprehensive code examples to see the SDK in action:

API Reference

For detailed information on all available methods and their parameters, refer to the official Azure Compute Management SDK API Reference.

Tutorials

Dive deeper with our step-by-step tutorials:

Code Samples

Find ready-to-use code snippets and samples in our GitHub repository.

Important: Always handle sensitive information like passwords and keys securely. Utilize Azure Key Vault or managed identities for production workloads.