Search code examples
pythonazure-sdk-python

Azure python sdk, how to deploy a vm and it's a Azure Spot instance


Azure python sdk, how to deploy a vm and it's a Azure Spot instance


Solution

  • If you want to create Azure Spot VM, please refer to the following code. For more deatils, please refer to the doucment and the docuemnt

    from azure.common.credentials import ServicePrincipalCredentials
    from azure.mgmt.compute.v2019_07_01 import ComputeManagementClient
    from azure.mgmt.compute.v2019_07_01.models import VirtualMachinePriorityTypes, VirtualMachineEvictionPolicyTypes, BillingProfile
    SUBSCRIPTION_ID = 'subscription-id'
    GROUP_NAME = 'myResourceGroup'
    LOCATION = 'westus'
    VM_NAME = 'myVM'
    credentials = ServicePrincipalCredentials(
            client_id = 'application-id',
            secret = 'authentication-key',
            tenant = 'tenant-id'
        )
    compute_client = ComputeManagementClient(
        credentials,
        SUBSCRIPTION_ID
    )
    vm_parameters = {
            'location': LOCATION,
            'os_profile': {
                'computer_name': VM_NAME,
                'admin_username': 'azureuser',
                'admin_password': 'Azure12345678'
            },
            'hardware_profile': {
                'vm_size': 'Standard_DS1'
            },
            'storage_profile': {
                'image_reference': {
                    'publisher': 'MicrosoftWindowsServer',
                    'offer': 'WindowsServer',
                    'sku': '2012-R2-Datacenter',
                    'version': 'latest'
                }
            },
            'network_profile': {
                'network_interfaces': [{
                    'id': nic.id
                }]
            },
            'priority':VirtualMachinePriorityTypes.spot, # use Azure spot intance
            'eviction_policy':VirtualMachineEvictionPolicyTypes.deallocate , #For Azure Spot virtual machines, the only supported value is 'Deallocate'
            'billing_profile': BillingProfile(max_price=float(2)) 
    creation_result = compute_client.virtual_machines.create_or_update(
            GROUP_NAME, 
            VM_NAME, 
            vm_parameters
        )
    print(creation_result.result())
        }
    

    enter image description here