Python script to launch instance (Virtual Machine) in Microsoft Azure!

Arpit Bisane
2 min readJan 25, 2023

Here is an example of a Python script that uses the Azure SDK (azure-sdk-for-python) to launch an instance (Virtual Machine) in Azure:

from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.compute import ComputeManagementClient

# Set the subscription ID
subscription_id = 'your-subscription-id'

# Set the credentials
client_id = 'your-client-id'
secret = 'your-client-secret'
tenant = 'your-tenant-id'

credentials = ServicePrincipalCredentials(client_id, secret, tenant=tenant)

# Set the resource group and VM name
resource_group_name = 'my-resource-group'
vm_name = 'my-vm'

# Set the location and VM parameters
location = 'eastus'
vm_parameters = {
'location': location,
'os_profile': {
'computer_name': vm_name,
'admin_username': 'adminuser',
'admin_password': 'myAdminPassword123'
},
'hardware_profile': {
'vm_size': 'Standard_D2s_v3'
},
'storage_profile': {
'image_reference': {
'publisher': 'Canonical',
'offer': 'UbuntuServer',
'sku': '20.04-LTS',
'version': 'latest'
}
}
}

# Create the compute client
compute_client = ComputeManagementClient(credentials, subscription_id)

# Create the VM
async_vm_creation = compute_client.virtual_machines.create_or_update(
resource_group_name, vm_name, vm_parameters
)
async_vm_creation.wait()

print(f'Virtual machine {vm_name} created successfully!')

This script uses the azure-sdk-for-python library, which provides an SDK for interacting with Azure services. The script sets various parameters such as the subscription ID, credentials, resource group, and VM name, and then uses these parameters to create a virtual machine.

It’s important to note that before running this script you should have the Azure SDK for python installed and you should have also authenticated the SDK with your Azure account. You also need to have the necessary permissions to create instances on your subscription, otherwise the script will fail.

It’s highly recommended to take a look at the official documentation of Azure SDK for python in order to understand the different parameters that you can use to launch an instance and also to learn how to handle the authentication and authorization.

--

--