0
# Virtual Machine Management
1
2
Comprehensive lifecycle management of Azure Virtual Machines including creation, configuration, monitoring, scaling, and deletion. The VirtualMachinesOperations class provides complete VM management capabilities with support for both Windows and Linux VMs, extensive customization options, and integration with Azure's security and monitoring services.
3
4
## Capabilities
5
6
### VM Lifecycle Operations
7
8
Core operations for managing virtual machine lifecycle from creation to deletion.
9
10
```python { .api }
11
def begin_create_or_update(
12
resource_group_name: str,
13
vm_name: str,
14
parameters: VirtualMachine
15
) -> LROPoller[VirtualMachine]:
16
"""
17
Create or update a virtual machine.
18
19
Args:
20
resource_group_name: Name of the resource group
21
vm_name: Name of the virtual machine
22
parameters: Virtual machine configuration
23
24
Returns:
25
Long-running operation poller for VirtualMachine
26
"""
27
28
def begin_delete(resource_group_name: str, vm_name: str) -> LROPoller[None]:
29
"""
30
Delete a virtual machine.
31
32
Args:
33
resource_group_name: Name of the resource group
34
vm_name: Name of the virtual machine
35
36
Returns:
37
Long-running operation poller
38
"""
39
40
def get(resource_group_name: str, vm_name: str) -> VirtualMachine:
41
"""
42
Get virtual machine details.
43
44
Args:
45
resource_group_name: Name of the resource group
46
vm_name: Name of the virtual machine
47
48
Returns:
49
Virtual machine details
50
"""
51
52
def list(resource_group_name: str) -> Iterable[VirtualMachine]:
53
"""
54
List virtual machines in a resource group.
55
56
Args:
57
resource_group_name: Name of the resource group
58
59
Returns:
60
Iterable of virtual machines
61
"""
62
63
def list_all() -> Iterable[VirtualMachine]:
64
"""
65
List all virtual machines in the subscription.
66
67
Returns:
68
Iterable of virtual machines across all resource groups
69
"""
70
```
71
72
### VM Power Management
73
74
Operations for controlling virtual machine power state.
75
76
```python { .api }
77
def begin_start(resource_group_name: str, vm_name: str) -> LROPoller[None]:
78
"""
79
Start a virtual machine.
80
81
Args:
82
resource_group_name: Name of the resource group
83
vm_name: Name of the virtual machine
84
85
Returns:
86
Long-running operation poller
87
"""
88
89
def begin_restart(resource_group_name: str, vm_name: str) -> LROPoller[None]:
90
"""
91
Restart a virtual machine.
92
93
Args:
94
resource_group_name: Name of the resource group
95
vm_name: Name of the virtual machine
96
97
Returns:
98
Long-running operation poller
99
"""
100
101
def begin_power_off(resource_group_name: str, vm_name: str) -> LROPoller[None]:
102
"""
103
Power off a virtual machine.
104
105
Args:
106
resource_group_name: Name of the resource group
107
vm_name: Name of the virtual machine
108
109
Returns:
110
Long-running operation poller
111
"""
112
113
def begin_deallocate(resource_group_name: str, vm_name: str) -> LROPoller[None]:
114
"""
115
Deallocate a virtual machine to release compute resources.
116
117
Args:
118
resource_group_name: Name of the resource group
119
vm_name: Name of the virtual machine
120
121
Returns:
122
Long-running operation poller
123
"""
124
```
125
126
### VM Status and Monitoring
127
128
Operations for retrieving virtual machine status and diagnostic information.
129
130
```python { .api }
131
def instance_view(resource_group_name: str, vm_name: str) -> VirtualMachineInstanceView:
132
"""
133
Get instance view of a virtual machine including power state and status.
134
135
Args:
136
resource_group_name: Name of the resource group
137
vm_name: Name of the virtual machine
138
139
Returns:
140
Virtual machine instance view with current status
141
"""
142
```
143
144
### VM Sizing and Updates
145
146
Operations for resizing and updating virtual machine configuration.
147
148
```python { .api }
149
def begin_update(
150
resource_group_name: str,
151
vm_name: str,
152
parameters: VirtualMachineUpdate
153
) -> LROPoller[VirtualMachine]:
154
"""
155
Update virtual machine configuration.
156
157
Args:
158
resource_group_name: Name of the resource group
159
vm_name: Name of the virtual machine
160
parameters: Update parameters
161
162
Returns:
163
Long-running operation poller for updated VirtualMachine
164
"""
165
166
def begin_redeploy(resource_group_name: str, vm_name: str) -> LROPoller[None]:
167
"""
168
Redeploy a virtual machine to a different physical host.
169
170
Args:
171
resource_group_name: Name of the resource group
172
vm_name: Name of the virtual machine
173
174
Returns:
175
Long-running operation poller
176
"""
177
```
178
179
### VM Run Commands
180
181
Execute commands on virtual machines remotely.
182
183
```python { .api }
184
def begin_run_command(
185
resource_group_name: str,
186
vm_name: str,
187
parameters: RunCommandInput
188
) -> LROPoller[RunCommandResult]:
189
"""
190
Run a command on a virtual machine.
191
192
Args:
193
resource_group_name: Name of the resource group
194
vm_name: Name of the virtual machine
195
parameters: Command parameters including script and arguments
196
197
Returns:
198
Long-running operation poller for command result
199
"""
200
```
201
202
## Data Types
203
204
```python { .api }
205
class VirtualMachine:
206
"""Describes a Virtual Machine."""
207
id: Optional[str]
208
name: Optional[str]
209
type: Optional[str]
210
location: str
211
tags: Optional[Dict[str, str]]
212
plan: Optional[Plan]
213
hardware_profile: Optional[HardwareProfile]
214
storage_profile: Optional[StorageProfile]
215
additional_capabilities: Optional[AdditionalCapabilities]
216
os_profile: Optional[OSProfile]
217
network_profile: Optional[NetworkProfile]
218
security_profile: Optional[SecurityProfile]
219
diagnostics_profile: Optional[DiagnosticsProfile]
220
availability_set: Optional[SubResource]
221
virtual_machine_scale_set: Optional[SubResource]
222
proximity_placement_group: Optional[SubResource]
223
priority: Optional[VirtualMachinePriorityTypes]
224
eviction_policy: Optional[VirtualMachineEvictionPolicyTypes]
225
billing_profile: Optional[BillingProfile]
226
host: Optional[SubResource]
227
host_group: Optional[SubResource]
228
provisioning_state: Optional[str]
229
instance_view: Optional[VirtualMachineInstanceView]
230
license_type: Optional[str]
231
vm_id: Optional[str]
232
extensions_time_budget: Optional[str]
233
platform_fault_domain: Optional[int]
234
235
class HardwareProfile:
236
"""Specifies the hardware settings for the virtual machine."""
237
vm_size: Optional[VirtualMachineSizeTypes]
238
vm_size_properties: Optional[VMSizeProperties]
239
240
class StorageProfile:
241
"""Specifies the storage settings for the virtual machine disks."""
242
image_reference: Optional[ImageReference]
243
os_disk: Optional[OSDisk]
244
data_disks: Optional[List[DataDisk]]
245
disk_controller_type: Optional[DiskControllerTypes]
246
247
class OSProfile:
248
"""Specifies the operating system settings for the virtual machine."""
249
computer_name: Optional[str]
250
admin_username: Optional[str]
251
admin_password: Optional[str]
252
custom_data: Optional[str]
253
windows_configuration: Optional[WindowsConfiguration]
254
linux_configuration: Optional[LinuxConfiguration]
255
secrets: Optional[List[VaultSecretGroup]]
256
allow_extension_operations: Optional[bool]
257
require_guest_provision_signal: Optional[bool]
258
259
class NetworkProfile:
260
"""Specifies the network interfaces of the virtual machine."""
261
network_interfaces: Optional[List[NetworkInterfaceReference]]
262
network_api_version: Optional[NetworkApiVersion]
263
network_interface_configurations: Optional[List[VirtualMachineNetworkInterfaceConfiguration]]
264
265
class VirtualMachineInstanceView:
266
"""The instance view of a virtual machine."""
267
platform_update_domain: Optional[int]
268
platform_fault_domain: Optional[int]
269
computer_name: Optional[str]
270
os_name: Optional[str]
271
os_version: Optional[str]
272
hyper_v_generation: Optional[HyperVGenerationType]
273
rdp_thumb_print: Optional[str]
274
vm_agent: Optional[VirtualMachineAgentInstanceView]
275
maintenance_redeploy_status: Optional[MaintenanceRedeployStatus]
276
disks: Optional[List[DiskInstanceView]]
277
extensions: Optional[List[VirtualMachineExtensionInstanceView]]
278
vm_health: Optional[VirtualMachineHealthStatus]
279
boot_diagnostics: Optional[BootDiagnosticsInstanceView]
280
assigned_host: Optional[str]
281
statuses: Optional[List[InstanceViewStatus]]
282
patch_status: Optional[VirtualMachinePatchStatus]
283
284
class VirtualMachineUpdate:
285
"""Describes a Virtual Machine Update."""
286
tags: Optional[Dict[str, str]]
287
plan: Optional[Plan]
288
hardware_profile: Optional[HardwareProfile]
289
storage_profile: Optional[StorageProfile]
290
additional_capabilities: Optional[AdditionalCapabilities]
291
os_profile: Optional[OSProfile]
292
network_profile: Optional[NetworkProfile]
293
security_profile: Optional[SecurityProfile]
294
diagnostics_profile: Optional[DiagnosticsProfile]
295
availability_set: Optional[SubResource]
296
virtual_machine_scale_set: Optional[SubResource]
297
proximity_placement_group: Optional[SubResource]
298
priority: Optional[VirtualMachinePriorityTypes]
299
eviction_policy: Optional[VirtualMachineEvictionPolicyTypes]
300
billing_profile: Optional[BillingProfile]
301
host: Optional[SubResource]
302
host_group: Optional[SubResource]
303
license_type: Optional[str]
304
extensions_time_budget: Optional[str]
305
306
class RunCommandInput:
307
"""Captures the command input for running command on Virtual Machine."""
308
command_id: str
309
script: Optional[List[str]]
310
parameters: Optional[List[RunCommandInputParameter]]
311
protected_parameters: Optional[List[RunCommandInputParameter]]
312
run_as_user: Optional[str]
313
run_as_password: Optional[str]
314
async_execution: Optional[bool]
315
output_blob_uri: Optional[str]
316
error_blob_uri: Optional[str]
317
timeout_in_seconds: Optional[int]
318
319
class RunCommandResult:
320
"""Contains the results of running a command on a Virtual Machine."""
321
value: Optional[List[InstanceViewStatus]]
322
```
323
324
## Usage Examples
325
326
### Create a Linux Virtual Machine
327
328
```python
329
from azure.identity import DefaultAzureCredential
330
from azure.mgmt.compute import ComputeManagementClient
331
332
credential = DefaultAzureCredential()
333
compute_client = ComputeManagementClient(credential, "subscription-id")
334
335
vm_parameters = {
336
'location': 'East US',
337
'hardware_profile': {
338
'vm_size': 'Standard_B1ms'
339
},
340
'storage_profile': {
341
'image_reference': {
342
'publisher': 'Canonical',
343
'offer': '0001-com-ubuntu-server-focal',
344
'sku': '20_04-lts-gen2',
345
'version': 'latest'
346
},
347
'os_disk': {
348
'create_option': 'FromImage',
349
'managed_disk': {
350
'storage_account_type': 'Premium_LRS'
351
}
352
}
353
},
354
'os_profile': {
355
'computer_name': 'myvm',
356
'admin_username': 'azureuser',
357
'disable_password_authentication': True,
358
'linux_configuration': {
359
'ssh': {
360
'public_keys': [{
361
'path': '/home/azureuser/.ssh/authorized_keys',
362
'key_data': 'ssh-rsa AAAAB3NzaC1yc2E...'
363
}]
364
}
365
}
366
},
367
'network_profile': {
368
'network_interfaces': [{
369
'id': '/subscriptions/.../networkInterfaces/mynic',
370
'properties': {'primary': True}
371
}]
372
}
373
}
374
375
operation = compute_client.virtual_machines.begin_create_or_update(
376
'myResourceGroup',
377
'myVM',
378
vm_parameters
379
)
380
vm = operation.result()
381
print(f"VM {vm.name} created successfully")
382
```
383
384
### Monitor VM Status
385
386
```python
387
# Get detailed instance view
388
instance_view = compute_client.virtual_machines.instance_view(
389
'myResourceGroup',
390
'myVM'
391
)
392
393
print(f"Computer Name: {instance_view.computer_name}")
394
print(f"OS Name: {instance_view.os_name}")
395
396
# Check power state
397
for status in instance_view.statuses:
398
if status.code.startswith('PowerState'):
399
print(f"Power State: {status.display_status}")
400
401
# Check provisioning state
402
vm = compute_client.virtual_machines.get('myResourceGroup', 'myVM')
403
print(f"Provisioning State: {vm.provisioning_state}")
404
```
405
406
### Execute Remote Command
407
408
```python
409
run_command_parameters = {
410
'command_id': 'RunShellScript', # For Linux VMs
411
'script': [
412
'df -h',
413
'free -m',
414
'uname -a'
415
]
416
}
417
418
operation = compute_client.virtual_machines.begin_run_command(
419
'myResourceGroup',
420
'myVM',
421
run_command_parameters
422
)
423
result = operation.result()
424
425
for status in result.value:
426
print(f"Message: {status.message}")
427
```