This sample demonstrates how to create a Virtual Machine (VM) on Microsoft Azure using the Azure SDK for Python.
az login).You need to install the necessary Azure SDK packages for Compute and Authentication.
pip install azure-identity azure-mgmt-compute azure-mgmt-network azure-mgmt-resource
The SDK uses credentials from the Azure CLI if you are logged in. Alternatively, you can use a Service Principal or Managed Identity.
az login in your terminal before executing the script.
Below is a Python script that creates a basic Linux VM. Ensure you replace placeholder values with your actual Azure resource names and desired configuration.
import os
from azure.identity import DefaultAzureCredential
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.network import NetworkManagementClient
from azure.mgmt.compute import ComputeManagementClient
# --- Configuration ---
SUBSCRIPTION_ID = os.environ.get("AZURE_SUBSCRIPTION_ID", "YOUR_SUBSCRIPTION_ID")
RESOURCE_GROUP_NAME = "my-vm-resource-group-python"
VM_NAME = "my-python-vm"
LOCATION = "eastus" # Or any other Azure region
VNET_NAME = "my-vnet"
SUBNET_NAME = "my-subnet"
PUBLIC_IP_NAME = "my-public-ip"
NIC_NAME = "my-nic"
VM_SIZE = "Standard_B1s" # Choose an appropriate VM size
IMAGE_URN = "Canonical:0001-com-ubuntu-server-focal:20_04-lts:latest" # Example Ubuntu 20.04 LTS
ADMIN_USERNAME = "azureuser"
SSH_PUBLIC_KEY = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQD..." # Replace with your actual SSH public key
# --- Authentication ---
credential = DefaultAzureCredential()
# --- Initialize Clients ---
resource_client = ResourceManagementClient(credential, SUBSCRIPTION_ID)
network_client = NetworkManagementClient(credential, SUBSCRIPTION_ID)
compute_client = ComputeManagementClient(credential, SUBSCRIPTION_ID)
# --- Main Logic ---
def create_vm_resources():
print(f"Starting VM creation process for {VM_NAME}...")
# 1. Create Resource Group
print(f"Creating resource group: {RESOURCE_GROUP_NAME} in {LOCATION}...")
resource_client.resource_groups.create_or_update(
RESOURCE_GROUP_NAME, {"location": LOCATION}
)
print("Resource group created.")
# 2. Create Virtual Network (VNet)
print(f"Creating virtual network: {VNET_NAME}...")
poller = network_client.virtual_networks.begin_create_or_update(
RESOURCE_GROUP_NAME,
VNET_NAME,
{
"location": LOCATION,
"address_space": {"address_prefixes": ["10.0.0.0/16"]},
},
)
vnet = poller.result()
print("Virtual network created.")
# 3. Create Subnet
print(f"Creating subnet: {SUBNET_NAME}...")
poller = network_client.subnets.begin_create_or_update(
RESOURCE_GROUP_NAME,
VNET_NAME,
SUBNET_NAME,
{"address_prefix": "10.0.0.0/24"},
)
subnet = poller.result()
print("Subnet created.")
# 4. Create Public IP Address
print(f"Creating public IP address: {PUBLIC_IP_NAME}...")
poller = network_client.public_ip_addresses.begin_create_or_update(
RESOURCE_GROUP_NAME,
PUBLIC_IP_NAME,
{
"location": LOCATION,
"sku": {"name": "Standard"},
"public_ip_allocation_method": "Static",
"public_ip_address_version": "IPv4",
},
)
public_ip = poller.result()
print("Public IP address created.")
# 5. Create Network Interface (NIC)
print(f"Creating network interface: {NIC_NAME}...")
poller = network_client.network_interfaces.begin_create_or_update(
RESOURCE_GROUP_NAME,
NIC_NAME,
{
"location": LOCATION,
"ip_configurations": [
{
"name": "ipconfig1",
"subnet": {"id": subnet.id},
"public_ip_address": {"id": public_ip.id},
}
],
},
)
nic = poller.result()
print("Network interface created.")
# 6. Create Virtual Machine
print(f"Creating virtual machine: {VM_NAME}...")
vm_parameters = {
"location": LOCATION,
"hardware_profile": {"vm_size": VM_SIZE},
"os_profile": {
"computer_name": VM_NAME,
"admin_username": ADMIN_USERNAME,
"linux_configuration": {
"disable_password_authentication": True,
"ssh": {
"public_keys": [
{
"path": f"/home/{ADMIN_USERNAME}/.ssh/authorized_keys",
"key_data": SSH_PUBLIC_KEY,
}
]
},
},
},
"storage_profile": {
"image_reference": {"offer": IMAGE_URN.split(':')[0], "publisher": IMAGE_URN.split(':')[1], "sku": IMAGE_URN.split(':')[2], "version": IMAGE_URN.split(':')[3]},
"os_disk": {
"create_option": "FromImage",
"managed_disk": {"storage_account_type": "Premium_LRS"},
"delete_option": "Delete",
},
},
"network_profile": {
"network_interfaces": [{"id": nic.id}]
},
}
poller = compute_client.virtual_machines.begin_create_or_update(
RESOURCE_GROUP_NAME, VM_NAME, vm_parameters
)
vm = poller.result()
print(f"Virtual machine '{VM_NAME}' created successfully!")
print(f"Public IP Address: {public_ip.ip_address}")
print(f"SSH Command: ssh {ADMIN_USERNAME}@{public_ip.ip_address}")
if __name__ == "__main__":
try:
create_vm_resources()
except Exception as e:
print(f"An error occurred: {e}")
import traceback
traceback.print_exc()
azure-identity: Provides authentication mechanisms like DefaultAzureCredential, which tries multiple authentication methods.azure-mgmt-resource: Used for managing Azure resources, primarily for creating the Resource Group.azure-mgmt-network: Handles network resources like Virtual Networks, Subnets, Public IP Addresses, and Network Interface Cards (NICs).azure-mgmt-compute: Manages compute resources, including Virtual Machines.Important Security Note: Never hardcode sensitive information like SSH keys directly into production code. Use secure methods for managing secrets, such as Azure Key Vault or environment variables.
For more advanced scenarios and detailed parameter explanations, please refer to the official Azure SDK for Python documentation.
Explore More Azure SDK Samples