Search code examples
azure-sdkazure-sdk-python

How to specify availability zone when creating VM through Azure SDK


I'm using the ComputeManagementClient in Azure's Python SDK to create a virtual machine. (Specifically, begin_start in VirtualMachinesOperations, found here.) However, I don't see an option to specify an availability zone -- only the resouce_group_name.

Is there some way to specify the availability zone when creating the VMs?

I've gone through the docs but I can't seem to find any mention of this functionality. I do know the Azure CLI supports this -- unsure why the SDK doesn't.


Solution

  • I created a VM through Azure Python SDK with a specified availability zone.

    • Assign Azure role assignments to contributors.

    Code:

    import os
    from azure.mgmt.compute import ComputeManagementClient
    from azure.mgmt.network import NetworkManagementClient
    from azure.mgmt.resource import ResourceManagementClient
    from azure.identity import DefaultAzureCredential
    from azure.core.exceptions import HttpResponseError
    
    try:
        # Set up the Azure API clients
        subscription_id = 'subscription_id' # Update with your subscription_id
        credentials = DefaultAzureCredential()
    
        network_client = NetworkManagementClient(credentials, subscription_id)
        compute_client = ComputeManagementClient(credentials, subscription_id)
        resource_client = ResourceManagementClient(credentials, subscription_id)
    
        # Create a new resource group
        resource_group_name = 'myresourcegroup'
        location = 'westus2'
        resource_client.resource_groups.create_or_update(
            resource_group_name,
            {'location': location}
        )
    
        print(f'Created resource group: {resource_group_name} in location: {location}')
    
        # Define NIC parameters
        nic_name = 'mynic'
        vnet_name = 'myvnet'
        subnet_name = 'mysubnet'
    
        # Create a virtual network
        network_client.virtual_networks.begin_create_or_update(
            resource_group_name,
            vnet_name,
            {
                'location': location,
                'address_space': {
                    'address_prefixes': ['10.0.0.0/16']
                }
            }
        ).result()
    
        print(f'Created virtual network: {vnet_name}')
    
        # Create a subnet
        network_client.subnets.begin_create_or_update(
            resource_group_name,
            vnet_name,
            subnet_name,
            {'address_prefix': '10.0.0.0/24'}
        ).result()
    
        print(f'Created subnet: {subnet_name}')
    
        # Create a NIC
        nic = network_client.network_interfaces.begin_create_or_update(
            resource_group_name,
            nic_name,
            {
                'location': location,
                'ip_configurations': [{
                    'name': 'myipconfig',
                    'subnet': {'id': f'/subscriptions/{subscription_id}/resourceGroups/{resource_group_name}/providers/Microsoft.Network/virtualNetworks/{vnet_name}/subnets/{subnet_name}'}
                }]
            }
        ).result()
    
        print(f'Created NIC: {nic_name}')
    
        # Define VM parameters
        vm_name = 'myvm'
        vm_size = 'Standard_D2_v2'  # Choose an appropriate VM size
        image_reference = {
            'publisher': 'Canonical',
            'offer': 'UbuntuServer',
            'sku': '18.04-LTS',
            'version': 'latest'
        }
    
        # Specify the availability zone
        availability_zone = '1'  # Change this to the desired zone (e.g., '1', '2', or '3')
    
        # Create a new VM with an availability zone and the created NIC
        vm = compute_client.virtual_machines.begin_create_or_update(
            resource_group_name,
            vm_name,
            {
                'location': location,
                'zones': [availability_zone],  # Specify the availability zone here
                'properties': {
                    'hardwareProfile': {
                        'vmSize': vm_size
                    },
                    'storageProfile': {
                        'imageReference': image_reference
                    },
                    'osProfile': {
                        'computerName': vm_name,
                        'adminUsername': 'adminUsername',# Update with your admin username
                        'adminPassword': 'adminPassword'  # Update with your admin password
                    },
                    'networkProfile': {
                        'networkInterfaces': [{
                            'id': nic.id
                        }]
                    }
                }
            }
        )
    
        vm.result()
    
        print(f'Created VM: {vm_name} in availability zone {availability_zone}')
    
    except HttpResponseError as ex:
        print(f"HTTP Response Error: {ex}")
    except Exception as e:
        print(f"An error occurred: {e}")
    
    

    Output:

    enter image description here

    enter image description here