I am having RDP access issues when trying to create a spot instance on azure through azure api for python

103 Views Asked by At

I am trying to create a spot instance on azure from azure API through python code. The following code successfully creates the spot instance machine on Azure but when I try to connect through RDP, the credentials given in the API does not work.

import secrets
from datetime import datetime

from azure.identity import ClientSecretCredential
from azure.mgmt.compute import ComputeManagementClient

from azure.mgmt.network import NetworkManagementClient
from azure.mgmt.compute.models import (
    VirtualMachine,
    HardwareProfile,
    StorageProfile,
    InstanceViewTypes,
    OSDisk,
    ManagedDiskParameters,
    DiskCreateOptionTypes,
    OSProfile,
    NetworkProfile,
    NetworkInterfaceReference,
    VirtualMachinePriorityTypes,
    VirtualMachineEvictionPolicyTypes,
    BillingProfile
)
from azure.mgmt.network.models import PublicIPAddress, IPAllocationMethod, NetworkSecurityGroup, SecurityRule
from constance import config

from instance.client_utils.ssh_client import SSHClient
from instance.models import VMInstance
from syntric_cr.settings import (
    AZURE_CLIENT_ID,
    AZURE_CLIENT_SECRET,
    AZURE_TENANT,
    AZURE_SUBSCRIPTION_ID,
    AZURE_CAPTURE_IMAGE,
    AZURE_RESOURCE_GROUP,
    AZURE_RDP_USERNAME,
    AZURE_LOCATION, AZURE_EXISTING_NIC_NAME, AZURE_EXISTING_NSG_NAME,
)


def create_spot_instance(self):
        current_timestamp = round(datetime.timestamp(datetime.now()))

        vm_name = f"spot-{current_timestamp}"

        vm_username = AZURE_RDP_USERNAME
        vm_password = secrets.token_urlsafe(13)
        vm_location = AZURE_LOCATION
        vm_image_id = self.get_image_id(AZURE_RESOURCE_GROUP, AZURE_CAPTURE_IMAGE)
        new_nic = self.creating_nic_and_ip_from_existing_vm(vm_name, vm_location)

        vm_params = VirtualMachine(
            location=vm_location,
            hardware_profile=HardwareProfile(vm_size=config.AZURE_VIRTUAL_MACHINE_SIZE),
            storage_profile=StorageProfile(
                image_reference={'id': vm_image_id},
                os_disk=OSDisk(
                    name=vm_name,
                    create_option=DiskCreateOptionTypes.from_image,
                    managed_disk=ManagedDiskParameters(storage_account_type='Standard_LRS')
                )
            ),
            os_profile=OSProfile(
                computer_name=vm_name,
                admin_username='hello',
                admin_password='hello_123'
            ),
            network_profile=NetworkProfile(
                network_interfaces=[
                    NetworkInterfaceReference(id=new_nic.id)
                ]
            ),
            priority=VirtualMachinePriorityTypes.spot,
            eviction_policy=VirtualMachineEvictionPolicyTypes.deallocate,
            billing_profile=BillingProfile(max_price=config.AZURE_MAX_SPOT_INSTANCE_BUDGET)
        )

        try:
            self.service.virtual_machines.begin_create_or_update(AZURE_RESOURCE_GROUP, vm_name, vm_params)
            return VMInstance.objects.create(
                instance=vm_name, project=AZURE_RESOURCE_GROUP, provider='AZURE', status=False,
                script_run_on_start=False, username=vm_username, password=vm_password)
        except Exception as ex:
            return


The username 'hello' and the password 'hello_123' does not work for the RDP access when the spot instance is created. I have to then manually reset the password in order to make it work

I tried the code above and copied this from the official Azure docs

1

There are 1 best solutions below

2
SiddheshDesai On

The username 'hello' and the password 'hello_123' does not work for the RDP access when the spot instance is created. I have to then manually reset the password in order to make it work

By default hello_123 is not supported as a password due to username and password limitations while deploying Azure VM, I tried creating a Spot VM with hello_123 password and the password was not selected due to the naming conventions and a Warning - The value must be between 12 and 123 characters long, Refer below:-

enter image description here

I tried creating a Spot VM with Python SDK by following the username and password naming conventions as mentioned in this Document:-

Username- FAQ about Windows VMs in Azure - Azure Virtual Machines | Microsoft Learn

Password- FAQ about Windows VMs in Azure - Azure Virtual Machines | Microsoft Learn

My Python code to Deploy a SpotVM:-

# from azure.common.credentials import ServicePrincipalCredentials

from  azure.identity  import  DefaultAzureCredential

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 = '<resource-group-name>'

LOCATION = 'Australia East'

VM_NAME = '<vm-name>'

credentials = DefaultAzureCredential()

compute_client = ComputeManagementClient(

credentials,

SUBSCRIPTION_ID

)

vm_parameters = {

'location': LOCATION,

'os_profile': {

'computer_name': VM_NAME,

'admin_username': '<username-accroding-to-naming-convention>',

'admin_password': '<password-according-to-naming-convention>'

},

'hardware_profile': {

'vm_size': 'Standard_D2s_v3'

},

'storage_profile': {

'image_reference': {

'publisher': 'MicrosoftWindowsServer',

'offer': 'WindowsServer',

'sku': '2019-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.begin_create_or_update(

GROUP_NAME,

VM_NAME,

vm_parameters

)

print(creation_result.result())

Output:-

enter image description here

VM got created on Portal and I attached NSG and Public IP to the VM and tried to RDP into it with the credentials given in the code and it was successful, Refer below:-

enter image description here

RDP:-

enter image description here

enter image description here

enter image description here

Reference:-

Azure python sdk, how to deploy a vm and it's a Azure Spot instance - Stack Overflow By Jim Xu