-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathvirtual-machine.ts
More file actions
669 lines (609 loc) · 20.9 KB
/
virtual-machine.ts
File metadata and controls
669 lines (609 loc) · 20.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
/**
* Unified Azure Virtual Machine implementation using VersionedAzapiResource framework
*
* This class provides a single, version-aware implementation for Azure Virtual Machines
* that automatically handles version management, schema validation, and property transformation
* across all supported API versions.
*
* Supported API Versions:
* - 2024-07-01 (Active)
* - 2024-11-01 (Active)
* - 2025-04-01 (Active, Latest)
*
* Features:
* - Automatic latest version resolution when no version is specified
* - Explicit version pinning for stability requirements
* - Schema-driven validation and transformation
* - Full JSII compliance for multi-language support
* - Comprehensive support for VM features (networking, storage, identity, etc.)
*/
import * as cdktn from "cdktn";
import { Construct } from "constructs";
import {
ALL_VIRTUAL_MACHINE_VERSIONS,
VIRTUAL_MACHINE_TYPE,
VirtualMachineHardwareProfile,
VirtualMachineStorageProfile,
VirtualMachineNetworkProfile,
VirtualMachineOSProfile,
VirtualMachineIdentity,
VirtualMachinePlan,
VirtualMachineAdditionalCapabilities,
VirtualMachineDiagnosticsProfile,
VirtualMachineSecurityProfile,
VirtualMachineLicenseType,
VirtualMachineAvailabilitySetReference,
VirtualMachineScaleSetReference,
VirtualMachineProximityPlacementGroupReference,
VirtualMachineHostReference,
VirtualMachineBillingProfile,
VirtualMachineMonitoringOptions,
} from "./virtual-machine-schemas";
import {
AzapiResource,
AzapiResourceProps,
MonitoringConfig,
} from "../../core-azure/lib/azapi/azapi-resource";
import { ApiSchema } from "../../core-azure/lib/version-manager/interfaces/version-interfaces";
/**
* Properties for the unified Azure Virtual Machine
*
* Extends AzapiResourceProps with Virtual Machine specific properties
*/
export interface VirtualMachineProps extends AzapiResourceProps {
/**
* The hardware profile for the Virtual Machine (VM size)
* @example { vmSize: "Standard_D2s_v3" }
*/
readonly hardwareProfile: VirtualMachineHardwareProfile;
/**
* The storage profile for the Virtual Machine
* Defines the OS disk, data disks, and image reference
*/
readonly storageProfile: VirtualMachineStorageProfile;
/**
* The network profile for the Virtual Machine
* Defines network interfaces attached to the VM
*/
readonly networkProfile: VirtualMachineNetworkProfile;
/**
* The OS profile for the Virtual Machine
* Defines computer name, admin credentials, and OS-specific configuration
*/
readonly osProfile?: VirtualMachineOSProfile;
/**
* The identity configuration for the Virtual Machine
* @example { type: "SystemAssigned" }
* @example { type: "UserAssigned", userAssignedIdentities: { "/subscriptions/.../resourceGroups/.../providers/Microsoft.ManagedIdentity/userAssignedIdentities/myIdentity": {} } }
*/
readonly identity?: VirtualMachineIdentity;
/**
* Availability zones for the Virtual Machine
* @example ["1", "2"]
*/
readonly zones?: string[];
/**
* Plan information for marketplace images
*/
readonly plan?: VirtualMachinePlan;
/**
* License type for Windows VMs
* @example "Windows_Server"
* @example "Windows_Client"
*/
readonly licenseType?: VirtualMachineLicenseType;
/**
* The priority of the Virtual Machine
* @default "Regular"
* @example "Regular", "Low", "Spot"
*/
readonly priority?: string;
/**
* The eviction policy for Spot VMs
* @example "Deallocate", "Delete"
*/
readonly evictionPolicy?: string;
/**
* The billing profile for Spot VMs
*/
readonly billingProfile?: VirtualMachineBillingProfile;
/**
* The diagnostics profile for boot diagnostics
*/
readonly diagnosticsProfile?: VirtualMachineDiagnosticsProfile;
/**
* Reference to an availability set
*/
readonly availabilitySet?: VirtualMachineAvailabilitySetReference;
/**
* Reference to a virtual machine scale set
*/
readonly virtualMachineScaleSet?: VirtualMachineScaleSetReference;
/**
* Reference to a proximity placement group
*/
readonly proximityPlacementGroup?: VirtualMachineProximityPlacementGroupReference;
/**
* Reference to a dedicated host
*/
readonly host?: VirtualMachineHostReference;
/**
* Additional capabilities like Ultra SSD
*/
readonly additionalCapabilities?: VirtualMachineAdditionalCapabilities;
/**
* Security settings for the Virtual Machine
*/
readonly securityProfile?: VirtualMachineSecurityProfile;
/**
* The lifecycle rules to ignore changes
* Useful for properties that are externally managed or should not trigger updates
* @example ["osProfile.adminPassword"]
*/
readonly ignoreChanges?: string[];
/**
* Resource group ID where the Virtual Machine will be created
*/
readonly resourceGroupId?: string;
}
/**
* Virtual Machine properties for the request body
*/
export interface VirtualMachineBodyProperties {
readonly hardwareProfile: VirtualMachineHardwareProfile;
readonly storageProfile: VirtualMachineStorageProfile;
readonly osProfile?: VirtualMachineOSProfile;
readonly networkProfile: VirtualMachineNetworkProfile;
readonly diagnosticsProfile?: VirtualMachineDiagnosticsProfile;
readonly availabilitySet?: VirtualMachineAvailabilitySetReference;
readonly virtualMachineScaleSet?: VirtualMachineScaleSetReference;
readonly proximityPlacementGroup?: VirtualMachineProximityPlacementGroupReference;
readonly priority?: string;
readonly evictionPolicy?: string;
readonly billingProfile?: VirtualMachineBillingProfile;
readonly host?: VirtualMachineHostReference;
readonly licenseType?: VirtualMachineLicenseType;
readonly additionalCapabilities?: VirtualMachineAdditionalCapabilities;
readonly securityProfile?: VirtualMachineSecurityProfile;
}
/**
* The resource body interface for Azure Virtual Machine API calls
*/
export interface VirtualMachineBody {
readonly location: string;
readonly tags?: { [key: string]: string };
readonly identity?: VirtualMachineIdentity;
readonly zones?: string[];
readonly plan?: VirtualMachinePlan;
readonly properties: VirtualMachineBodyProperties;
}
/**
* Unified Azure Virtual Machine implementation
*
* This class provides a single, version-aware implementation that automatically handles version
* resolution, schema validation, and property transformation while maintaining full JSII compliance.
*
* The class uses the VersionedAzapiResource framework to provide:
* - Automatic latest version resolution (2025-04-01 as of this implementation)
* - Support for explicit version pinning when stability is required
* - Schema-driven property validation and transformation
* - Migration analysis and deprecation warnings
* - Full JSII compliance for multi-language support
*
* @example
* // Basic Linux VM with SSH authentication:
* const vm = new VirtualMachine(this, "vm", {
* name: "my-linux-vm",
* location: "eastus",
* resourceGroupId: resourceGroup.id,
* hardwareProfile: {
* vmSize: "Standard_D2s_v3"
* },
* storageProfile: {
* imageReference: {
* publisher: "Canonical",
* offer: "0001-com-ubuntu-server-jammy",
* sku: "22_04-lts-gen2",
* version: "latest"
* },
* osDisk: {
* createOption: "FromImage",
* managedDisk: {
* storageAccountType: "Premium_LRS"
* }
* }
* },
* osProfile: {
* computerName: "myvm",
* adminUsername: "azureuser",
* linuxConfiguration: {
* disablePasswordAuthentication: true,
* ssh: {
* publicKeys: [{
* path: "/home/azureuser/.ssh/authorized_keys",
* keyData: "ssh-rsa AAAA..."
* }]
* }
* }
* },
* networkProfile: {
* networkInterfaces: [{
* id: networkInterface.id
* }]
* },
* identity: {
* type: "SystemAssigned"
* }
* });
*
* @example
* // Windows VM with password authentication:
* const windowsVm = new VirtualMachine(this, "windows-vm", {
* name: "my-windows-vm",
* location: "eastus",
* resourceGroupId: resourceGroup.id,
* hardwareProfile: {
* vmSize: "Standard_D2s_v3"
* },
* storageProfile: {
* imageReference: {
* publisher: "MicrosoftWindowsServer",
* offer: "WindowsServer",
* sku: "2022-datacenter-azure-edition",
* version: "latest"
* },
* osDisk: {
* createOption: "FromImage",
* managedDisk: {
* storageAccountType: "Premium_LRS"
* }
* }
* },
* osProfile: {
* computerName: "mywinvm",
* adminUsername: "azureuser",
* adminPassword: "P@ssw0rd1234!",
* windowsConfiguration: {
* provisionVMAgent: true,
* enableAutomaticUpdates: true
* }
* },
* networkProfile: {
* networkInterfaces: [{
* id: networkInterface.id
* }]
* },
* licenseType: "Windows_Server"
* });
*
* @stability stable
*/
export class VirtualMachine extends AzapiResource {
// Static initializer runs once when the class is first loaded
static {
AzapiResource.registerSchemas(
VIRTUAL_MACHINE_TYPE,
ALL_VIRTUAL_MACHINE_VERSIONS,
);
}
/**
* Returns a production-ready monitoring configuration for Virtual Machines
*
* This static factory method provides a complete MonitoringConfig with sensible defaults
* for VM monitoring including CPU, memory, disk queue alerts, and deletion tracking.
*
* @param actionGroupId - The resource ID of the action group for alert notifications
* @param workspaceId - Optional Log Analytics workspace ID for diagnostic settings
* @param options - Optional configuration to customize thresholds and enable/disable specific alerts
* @returns A complete MonitoringConfig object ready to use in VirtualMachine props
*
* @example
* // Basic usage with all defaults
* const vm = new VirtualMachine(this, "vm", {
* // ... other properties ...
* monitoring: VirtualMachine.defaultMonitoring(actionGroup.id, workspace.id)
* });
*
* @example
* // Custom thresholds
* const vm = new VirtualMachine(this, "vm", {
* // ... other properties ...
* monitoring: VirtualMachine.defaultMonitoring(
* actionGroup.id,
* workspace.id,
* {
* cpuThreshold: 90,
* memoryThreshold: 536870912, // 512MB
* enableDiskQueueAlert: false
* }
* )
* });
*/
public static defaultMonitoring(
actionGroupId: string,
workspaceId?: string,
options?: VirtualMachineMonitoringOptions,
): MonitoringConfig {
const metricAlerts: any[] = [];
// High CPU Alert
if (options?.enableCpuAlert !== false) {
metricAlerts.push({
name: "high-cpu-alert",
description: "Alert when CPU usage exceeds threshold",
severity: (options?.cpuAlertSeverity ?? 2) as 0 | 1 | 2 | 3 | 4,
scopes: [], // Will be set automatically by base class
evaluationFrequency: "PT5M",
windowSize: "PT15M",
criteria: {
type: "StaticThreshold" as const,
metricName: "Percentage CPU",
metricNamespace: "Microsoft.Compute/virtualMachines",
operator: "GreaterThan" as const,
threshold: options?.cpuThreshold ?? 80,
timeAggregation: "Average" as const,
},
actions: [{ actionGroupId }],
});
}
// Low Memory Alert
if (options?.enableMemoryAlert !== false) {
metricAlerts.push({
name: "low-memory-alert",
description: "Alert when available memory falls below threshold",
severity: (options?.memoryAlertSeverity ?? 2) as 0 | 1 | 2 | 3 | 4,
scopes: [], // Will be set automatically by base class
evaluationFrequency: "PT5M",
windowSize: "PT15M",
criteria: {
type: "StaticThreshold" as const,
metricName: "Available Memory Bytes",
metricNamespace: "Microsoft.Compute/virtualMachines",
operator: "LessThan" as const,
threshold: options?.memoryThreshold ?? 1073741824,
timeAggregation: "Average" as const,
},
actions: [{ actionGroupId }],
});
}
// High Disk Queue Alert
if (options?.enableDiskQueueAlert !== false) {
metricAlerts.push({
name: "high-disk-queue-alert",
description: "Alert when disk queue depth exceeds threshold",
severity: (options?.diskQueueAlertSeverity ?? 2) as 0 | 1 | 2 | 3 | 4,
scopes: [], // Will be set automatically by base class
evaluationFrequency: "PT5M",
windowSize: "PT15M",
criteria: {
type: "StaticThreshold" as const,
metricName: "OS Disk Queue Depth",
metricNamespace: "Microsoft.Compute/virtualMachines",
operator: "GreaterThan" as const,
threshold: options?.diskQueueThreshold ?? 32,
timeAggregation: "Average" as const,
},
actions: [{ actionGroupId }],
});
}
// Build diagnostic settings if workspace ID is provided
const diagnosticSettings = workspaceId
? {
name: "vm-diagnostics",
targetResourceId: "", // Will be set automatically by base class
workspaceId: workspaceId,
logs: [{ categoryGroup: "allLogs", enabled: true }],
metrics: [{ category: "AllMetrics", enabled: true }],
}
: undefined;
// Build activity log alerts
const activityLogAlerts =
options?.enableDeletionAlert !== false
? [
{
name: "vm-deletion-alert",
description: "Alert when virtual machine is deleted",
scopes: [], // Will be set automatically by base class
condition: {
allOf: [
{
field: "operationName",
equalsValue: "Microsoft.Compute/virtualMachines/delete",
},
],
},
actions: {
actionGroups: [{ actionGroupId }],
},
},
]
: undefined;
// Return complete config object
return {
enabled: true,
diagnosticSettings: diagnosticSettings,
metricAlerts: metricAlerts,
activityLogAlerts: activityLogAlerts,
};
}
/**
* The input properties for this Virtual Machine instance
*/
public readonly props: VirtualMachineProps;
// Output properties for easy access and referencing
public readonly idOutput: cdktn.TerraformOutput;
public readonly locationOutput: cdktn.TerraformOutput;
public readonly nameOutput: cdktn.TerraformOutput;
public readonly tagsOutput: cdktn.TerraformOutput;
public readonly vmIdOutput: cdktn.TerraformOutput;
// Public properties that match common VM interface patterns
/**
* Creates a new Azure Virtual Machine using the VersionedAzapiResource framework
*
* The constructor automatically handles version resolution, schema registration,
* validation, and resource creation.
*
* @param scope - The scope in which to define this construct
* @param id - The unique identifier for this instance
* @param props - Configuration properties for the Virtual Machine
*/
constructor(scope: Construct, id: string, props: VirtualMachineProps) {
super(scope, id, props);
this.props = props;
// Extract properties from the AZAPI resource outputs using Terraform interpolation
// Create Terraform outputs for easy access and referencing from other resources
this.idOutput = new cdktn.TerraformOutput(this, "id", {
value: this.id,
description: "The ID of the Virtual Machine",
});
this.locationOutput = new cdktn.TerraformOutput(this, "location", {
value: `\${${this.terraformResource.fqn}.location}`,
description: "The location of the Virtual Machine",
});
this.nameOutput = new cdktn.TerraformOutput(this, "name", {
value: `\${${this.terraformResource.fqn}.name}`,
description: "The name of the Virtual Machine",
});
this.tagsOutput = new cdktn.TerraformOutput(this, "tags", {
value: `\${${this.terraformResource.fqn}.tags}`,
description: "The tags assigned to the Virtual Machine",
});
this.vmIdOutput = new cdktn.TerraformOutput(this, "vmId", {
value: `\${${this.terraformResource.fqn}.output.properties.vmId}`,
description: "The unique identifier of the Virtual Machine",
});
// Override logical IDs to match naming convention
this.idOutput.overrideLogicalId("id");
this.locationOutput.overrideLogicalId("location");
this.nameOutput.overrideLogicalId("name");
this.tagsOutput.overrideLogicalId("tags");
this.vmIdOutput.overrideLogicalId("vmId");
// Apply ignore changes if specified
this._applyIgnoreChanges();
}
// =============================================================================
// REQUIRED ABSTRACT METHODS FROM AzapiResource
// =============================================================================
/**
* Gets the default API version to use when no explicit version is specified
* Returns the most recent stable version as the default
*/
protected defaultVersion(): string {
return "2025-04-01";
}
/**
* Gets the Azure resource type for Virtual Machines
*/
protected resourceType(): string {
return VIRTUAL_MACHINE_TYPE;
}
/**
* Gets the API schema for the resolved version
* Uses the framework's schema resolution to get the appropriate schema
*/
protected apiSchema(): ApiSchema {
return this.resolveSchema();
}
/**
* Indicates that location is required for Virtual Machines
*/
protected requiresLocation(): boolean {
return true;
}
/**
* Creates the resource body for the Azure API call
* Transforms the input properties into the JSON format expected by Azure REST API
*/
protected createResourceBody(props: any): any {
const typedProps = props as VirtualMachineProps;
return {
location: this.location,
tags: this.allTags(),
identity: typedProps.identity,
zones: typedProps.zones,
plan: typedProps.plan,
properties: {
hardwareProfile: typedProps.hardwareProfile,
storageProfile: typedProps.storageProfile,
osProfile: typedProps.osProfile,
networkProfile: typedProps.networkProfile,
diagnosticsProfile: typedProps.diagnosticsProfile,
availabilitySet: typedProps.availabilitySet,
virtualMachineScaleSet: typedProps.virtualMachineScaleSet,
proximityPlacementGroup: typedProps.proximityPlacementGroup,
priority: typedProps.priority,
evictionPolicy: typedProps.evictionPolicy,
billingProfile: typedProps.billingProfile,
host: typedProps.host,
licenseType: typedProps.licenseType,
additionalCapabilities: typedProps.additionalCapabilities,
securityProfile: typedProps.securityProfile,
},
};
}
// =============================================================================
// PUBLIC METHODS FOR VIRTUAL MACHINE OPERATIONS
// =============================================================================
/**
* Get the VM ID (unique identifier assigned by Azure)
*/
public get vmId(): string {
return `\${${this.terraformResource.fqn}.output.properties.vmId}`;
}
/**
* Get the provisioning state of the Virtual Machine
*/
public get provisioningState(): string {
return `\${${this.terraformResource.fqn}.output.properties.provisioningState}`;
}
/**
* Get the OS profile computer name
*/
public get computerName(): string | undefined {
return this.props.osProfile?.computerName;
}
/**
* Get the VM size
*/
public get vmSize(): string {
return this.props.hardwareProfile.vmSize;
}
/**
* Add a tag to the Virtual Machine
* Note: This modifies the construct props but requires a new deployment to take effect
*/
public addTag(key: string, value: string): void {
if (!this.props.tags) {
(this.props as any).tags = {};
}
this.props.tags![key] = value;
}
/**
* Remove a tag from the Virtual Machine
* Note: This modifies the construct props but requires a new deployment to take effect
*/
public removeTag(key: string): void {
if (this.props.tags && this.props.tags[key]) {
delete this.props.tags[key];
}
}
// =============================================================================
// PRIVATE HELPER METHODS
// =============================================================================
/**
* Applies ignore changes lifecycle rules if specified in props
*/
private _applyIgnoreChanges(): void {
if (this.props.ignoreChanges && this.props.ignoreChanges.length > 0) {
// Common properties that are safe to ignore for Virtual Machines
// adminPassword should often be ignored to prevent drift
const validIgnoreChanges = this.props.ignoreChanges.filter(
(change) => change !== "name", // name cannot be changed after creation
);
if (validIgnoreChanges.length > 0) {
this.terraformResource.addOverride("lifecycle", {
ignore_changes: validIgnoreChanges,
});
}
}
}
}