-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy path_template_builder.py
More file actions
1861 lines (1587 loc) · 74.3 KB
/
_template_builder.py
File metadata and controls
1861 lines (1587 loc) · 74.3 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
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
from enum import Enum
from knack.log import get_logger
from knack.util import CLIError
from azure.cli.core.azclierror import ValidationError, InvalidArgumentValueError
from azure.cli.core.util import b64encode
from azure.cli.core.profiles import ResourceType
from azure.cli.core.commands.arm import ArmTemplateBuilder
from azure.cli.command_modules.vm._vm_utils import get_target_network_api
logger = get_logger(__name__)
# pylint: disable=too-few-public-methods
class StorageProfile(Enum):
SAPirImage = 1
SACustomImage = 2
SASpecializedOSDisk = 3
ManagedPirImage = 4 # this would be the main scenarios
ManagedCustomImage = 5
ManagedSpecializedOSDisk = 6
SharedGalleryImage = 7
CommunityGalleryImage = 8
def build_deployment_resource(name, template, dependencies=None):
dependencies = dependencies or []
deployment = {
'name': name,
'type': 'Microsoft.Resources/deployments',
'apiVersion': '2015-01-01',
'dependsOn': dependencies,
'properties': {
'mode': 'Incremental',
'template': template,
}
}
return deployment
def build_output_deployment_resource(key, property_name, property_provider, property_type,
parent_name=None, output_type='object', path=None):
from azure.cli.core.util import random_string
output_tb = ArmTemplateBuilder()
output_tb.add_output(key, property_name, property_provider, property_type,
output_type=output_type, path=path)
output_template = output_tb.build()
deployment_name = '{}_{}'.format(property_name, random_string(16))
deployment = {
'name': deployment_name,
'type': 'Microsoft.Resources/deployments',
'apiVersion': '2015-01-01',
'properties': {
'mode': 'Incremental',
'template': output_template,
}
}
deployment['dependsOn'] = [] if not parent_name \
else ['Microsoft.Resources/deployments/{}'.format(parent_name)]
return deployment
def build_storage_account_resource(_, name, location, tags, sku, edge_zone=None):
storage_account = {
'type': 'Microsoft.Storage/storageAccounts',
'name': name,
'apiVersion': '2015-06-15',
'location': location,
'tags': tags,
'dependsOn': [],
'properties': {'accountType': sku}
}
if edge_zone:
storage_account['apiVersion'] = '2021-04-01'
storage_account['extendedLocation'] = edge_zone
return storage_account
def build_public_ip_resource(cmd, name, location, tags, address_allocation, dns_name, sku, zone, count=None,
edge_zone=None):
public_ip_properties = {'publicIPAllocationMethod': address_allocation}
if dns_name:
public_ip_properties['dnsSettings'] = {'domainNameLabel': dns_name}
public_ip = {
'apiVersion': get_target_network_api(cmd.cli_ctx),
'type': 'Microsoft.Network/publicIPAddresses',
'name': name,
'location': location,
'tags': tags,
'dependsOn': [],
'properties': public_ip_properties
}
if count:
public_ip['name'] = "[concat('{}', copyIndex())]".format(name)
public_ip['copy'] = {
'name': 'publicipcopy',
'mode': 'parallel',
'count': count
}
# when multiple zones are provided(through a x-zone scale set), we don't propagate to PIP becasue it doesn't
# support x-zone; rather we will rely on the Standard LB to work with such scale sets
if zone and len(zone) == 1:
public_ip['zones'] = zone
if sku and cmd.supported_api_version(ResourceType.MGMT_NETWORK, min_api='2017-08-01'):
public_ip['sku'] = {'name': sku}
# The edge zones are only built out using Standard SKU Public IPs
if edge_zone and sku.lower() == 'standard':
public_ip['apiVersion'] = '2021-02-01'
public_ip['extendedLocation'] = edge_zone
return public_ip
def build_nic_resource(_, name, location, tags, vm_name, subnet_id, private_ip_address=None,
nsg_id=None, public_ip_id=None, application_security_groups=None, accelerated_networking=None,
count=None, edge_zone=None):
private_ip_allocation = 'Static' if private_ip_address else 'Dynamic'
ip_config_properties = {
'privateIPAllocationMethod': private_ip_allocation,
'subnet': {'id': subnet_id}
}
if private_ip_address:
ip_config_properties['privateIPAddress'] = private_ip_address
if public_ip_id:
ip_config_properties['publicIPAddress'] = {'id': public_ip_id}
if count:
ip_config_properties['publicIPAddress']['id'] = "[concat('{}', copyIndex())]".format(public_ip_id)
ipconfig_name = 'ipconfig{}'.format(vm_name)
nic_properties = {
'ipConfigurations': [
{
'name': ipconfig_name,
'properties': ip_config_properties
}
]
}
if count:
nic_properties['ipConfigurations'][0]['name'] = "[concat('{}', copyIndex())]".format(ipconfig_name)
if nsg_id:
nic_properties['networkSecurityGroup'] = {'id': nsg_id}
api_version = '2015-06-15'
if application_security_groups:
asg_ids = [{'id': x['id']} for x in application_security_groups]
nic_properties['ipConfigurations'][0]['properties']['applicationSecurityGroups'] = asg_ids
api_version = '2017-09-01'
if accelerated_networking is not None:
nic_properties['enableAcceleratedNetworking'] = accelerated_networking
api_version = '2016-09-01' if api_version < '2016-09-01' else api_version
nic = {
'apiVersion': api_version,
'type': 'Microsoft.Network/networkInterfaces',
'name': name,
'location': location,
'tags': tags,
'dependsOn': [],
'properties': nic_properties
}
if count:
nic['name'] = "[concat('{}', copyIndex())]".format(name)
nic['copy'] = {
'name': 'niccopy',
'mode': 'parallel',
'count': count
}
if edge_zone:
nic['extendedLocation'] = edge_zone
nic['apiVersion'] = '2021-02-01'
return nic
def build_nsg_resource(_, name, location, tags, nsg_rule):
nsg = {
'type': 'Microsoft.Network/networkSecurityGroups',
'name': name,
'apiVersion': '2015-06-15',
'location': location,
'tags': tags,
'dependsOn': []
}
if nsg_rule != 'NONE':
rule_name = 'rdp' if nsg_rule == 'RDP' else 'default-allow-ssh'
rule_dest_port = '3389' if nsg_rule == 'RDP' else '22'
nsg_properties = {
'securityRules': [
{
'name': rule_name,
'properties': {
'protocol': 'Tcp',
'sourcePortRange': '*',
'destinationPortRange': rule_dest_port,
'sourceAddressPrefix': '*',
'destinationAddressPrefix': '*',
'access': 'Allow',
'priority': 1000,
'direction': 'Inbound'
}
}
]
}
nsg['properties'] = nsg_properties
return nsg
def build_vnet_resource(_, name, location, tags, vnet_prefix=None, subnet=None,
subnet_prefix=None, dns_servers=None, edge_zone=None):
vnet = {
'name': name,
'type': 'Microsoft.Network/virtualNetworks',
'location': location,
'apiVersion': '2015-06-15',
'dependsOn': [],
'tags': tags,
'properties': {
'addressSpace': {'addressPrefixes': [vnet_prefix]},
}
}
if dns_servers:
vnet['properties']['dhcpOptions'] = {
'dnsServers': dns_servers
}
if subnet:
vnet['properties']['subnets'] = [{
'name': subnet,
'properties': {
'addressPrefix': subnet_prefix
}
}]
if edge_zone:
vnet['extendedLocation'] = edge_zone
vnet['apiVersion'] = '2021-02-01'
return vnet
def build_msi_role_assignment(vm_vmss_name, vm_vmss_resource_id, role_definition_id,
role_assignment_guid, identity_scope, is_vm=True):
from azure.mgmt.core.tools import parse_resource_id
result = parse_resource_id(identity_scope)
if result.get('type'): # is a resource id?
name = '{}/Microsoft.Authorization/{}'.format(result['name'], role_assignment_guid)
assignment_type = '{}/{}/providers/roleAssignments'.format(result['namespace'], result['type'])
else:
name = role_assignment_guid
assignment_type = 'Microsoft.Authorization/roleAssignments'
# pylint: disable=line-too-long
msi_rp_api_version = '2019-07-01'
return {
'name': name,
'type': assignment_type,
'apiVersion': '2015-07-01', # the minimum api-version to create the assignment
'dependsOn': [
'Microsoft.Compute/{}/{}'.format('virtualMachines' if is_vm else 'virtualMachineScaleSets', vm_vmss_name)
],
'properties': {
'roleDefinitionId': role_definition_id,
'principalId': "[reference('{}', '{}', 'Full').identity.principalId]".format(
vm_vmss_resource_id, msi_rp_api_version),
'scope': identity_scope
}
}
def build_vm_resource( # pylint: disable=too-many-locals, too-many-statements, too-many-branches
name, location, tags, size, storage_profile, nics, admin_username,
availability_set_id=None, admin_password=None, ssh_key_values=None, ssh_key_path=None,
image_reference=None, os_disk_name=None, custom_image_os_type=None, authentication_type=None,
os_publisher=None, os_offer=None, os_sku=None, os_version=None, os_vhd_uri=None,
attach_os_disk=None, os_disk_size_gb=None, custom_data=None, secrets=None, license_type=None, zone=None,
disk_info=None, boot_diagnostics_storage_uri=None, ultra_ssd_enabled=None, proximity_placement_group=None,
computer_name=None, dedicated_host=None, priority=None, max_price=None, eviction_policy=None,
enable_agent=None, vmss=None, os_disk_encryption_set=None, data_disk_encryption_sets=None, specialized=None,
encryption_at_host=None, dedicated_host_group=None, enable_auto_update=None, patch_mode=None,
enable_hotpatching=None, platform_fault_domain=None, security_type=None, enable_secure_boot=None,
enable_vtpm=None, count=None, edge_zone=None, os_disk_delete_option=None, user_data=None,
capacity_reservation_group=None, enable_hibernation=None, v_cpus_available=None, v_cpus_per_core=None,
os_disk_security_encryption_type=None, os_disk_secure_vm_disk_encryption_set=None, disk_controller_type=None,
enable_proxy_agent=None, proxy_agent_mode=None, additional_scheduled_events=None,
enable_user_reboot_scheduled_events=None, enable_user_redeploy_scheduled_events=None,
zone_placement_policy=None, include_zones=None, exclude_zones=None, align_regional_disks_to_vm_zone=None,
wire_server_mode=None, imds_mode=None, wire_server_access_control_profile_reference_id=None,
imds_access_control_profile_reference_id=None, key_incarnation_id=None, add_proxy_agent_extension=None,
disk_iops_read_write=None, disk_mbps_read_write=None, zone_movement=None):
os_caching = disk_info['os'].get('caching')
def _build_os_profile():
special_chars = '`~!@#$%^&*()=+_[]{}\\|;:\'\",<>/?'
# _computer_name is used to avoid shadow names
_computer_name = computer_name or ''.join(filter(lambda x: x not in special_chars, name))
os_profile = {
# Use name as computer_name if it's not provided. Remove special characters from name.
'computerName': _computer_name,
'adminUsername': admin_username
}
if count:
os_profile['computerName'] = "[concat('{}', copyIndex())]".format(_computer_name)
if admin_password:
os_profile['adminPassword'] = "[parameters('adminPassword')]"
if custom_data:
os_profile['customData'] = b64encode(custom_data)
if ssh_key_values and ssh_key_path:
os_profile['linuxConfiguration'] = {
'disablePasswordAuthentication': authentication_type == 'ssh',
'ssh': {
'publicKeys': [
{
'keyData': ssh_key_value,
'path': ssh_key_path
} for ssh_key_value in ssh_key_values
]
}
}
if enable_agent is not None:
if custom_image_os_type.lower() == 'linux':
if 'linuxConfiguration' not in os_profile:
os_profile['linuxConfiguration'] = {}
os_profile['linuxConfiguration']['provisionVMAgent'] = enable_agent
elif custom_image_os_type.lower() == 'windows':
if 'windowsConfiguration' not in os_profile:
os_profile['windowsConfiguration'] = {}
os_profile['windowsConfiguration']['provisionVMAgent'] = enable_agent
if secrets:
os_profile['secrets'] = secrets
if enable_auto_update is not None and custom_image_os_type.lower() == 'windows':
if 'windowsConfiguration' not in os_profile:
os_profile['windowsConfiguration'] = {}
os_profile['windowsConfiguration']['enableAutomaticUpdates'] = enable_auto_update
# Windows patch settings
if patch_mode is not None and custom_image_os_type.lower() == 'windows':
if patch_mode.lower() not in ['automaticbyos', 'automaticbyplatform', 'manual']:
raise ValidationError(
'Invalid value of --patch-mode for Windows VM. Valid values are AutomaticByOS, '
'AutomaticByPlatform, Manual.')
if 'windowsConfiguration' not in os_profile:
os_profile['windowsConfiguration'] = {}
os_profile['windowsConfiguration']['patchSettings'] = {
'patchMode': patch_mode,
'enableHotpatching': enable_hotpatching
}
# Linux patch settings
if patch_mode is not None and custom_image_os_type.lower() == 'linux':
if patch_mode.lower() not in ['automaticbyplatform', 'imagedefault']:
raise ValidationError(
'Invalid value of --patch-mode for Linux VM. Valid values are AutomaticByPlatform, ImageDefault.')
if 'linuxConfiguration' not in os_profile:
os_profile['linuxConfiguration'] = {}
os_profile['linuxConfiguration']['patchSettings'] = {
'patchMode': patch_mode
}
return os_profile
def _build_storage_profile():
storage_profiles = {
'SACustomImage': {
'osDisk': {
'createOption': 'fromImage',
'name': os_disk_name,
'caching': os_caching,
'osType': custom_image_os_type,
'image': {'uri': image_reference},
'vhd': {'uri': os_vhd_uri}
}
},
'SAPirImage': {
'osDisk': {
'createOption': 'fromImage',
'name': os_disk_name,
'caching': os_caching,
'vhd': {'uri': os_vhd_uri}
},
'imageReference': {
'publisher': os_publisher,
'offer': os_offer,
'sku': os_sku,
'version': os_version
}
},
'SASpecializedOSDisk': {
'osDisk': {
'createOption': 'attach',
'osType': custom_image_os_type,
'name': os_disk_name,
'vhd': {'uri': attach_os_disk}
}
},
'ManagedPirImage': {
'osDisk': {
'createOption': 'fromImage',
'name': os_disk_name,
'caching': os_caching,
'managedDisk': {
'storageAccountType': disk_info['os'].get('storageAccountType'),
}
},
'imageReference': {
'publisher': os_publisher,
'offer': os_offer,
'sku': os_sku,
'version': os_version
}
},
'ManagedCustomImage': {
'osDisk': {
'createOption': 'fromImage',
'name': os_disk_name,
'caching': os_caching,
'managedDisk': {
'storageAccountType': disk_info['os'].get('storageAccountType'),
}
},
"imageReference": {
'id': image_reference
}
},
'ManagedSpecializedOSDisk': {
'osDisk': {
'createOption': 'attach',
'osType': custom_image_os_type,
'managedDisk': {
'id': attach_os_disk
}
}
},
'SharedGalleryImage': {
"osDisk": {
"caching": os_caching,
"managedDisk": {
"storageAccountType": disk_info['os'].get('storageAccountType'),
},
"name": os_disk_name,
"createOption": "fromImage"
},
"imageReference": {
'sharedGalleryImageId': image_reference
}
},
'CommunityGalleryImage': {
"osDisk": {
"caching": os_caching,
"managedDisk": {
"storageAccountType": disk_info['os'].get('storageAccountType'),
},
"name": os_disk_name,
"createOption": "fromImage"
},
"imageReference": {
'communityGalleryImageId': image_reference
}
}
}
if os_disk_encryption_set is not None:
storage_profiles['ManagedPirImage']['osDisk']['managedDisk']['diskEncryptionSet'] = {
'id': os_disk_encryption_set,
}
storage_profiles['ManagedCustomImage']['osDisk']['managedDisk']['diskEncryptionSet'] = {
'id': os_disk_encryption_set,
}
storage_profiles['SharedGalleryImage']['osDisk']['managedDisk']['diskEncryptionSet'] = {
'id': os_disk_encryption_set,
}
storage_profiles['CommunityGalleryImage']['osDisk']['managedDisk']['diskEncryptionSet'] = {
'id': os_disk_encryption_set,
}
if os_disk_security_encryption_type is not None:
storage_profiles['ManagedPirImage']['osDisk']['managedDisk'].update({
'securityProfile': {
'securityEncryptionType': os_disk_security_encryption_type,
}
})
storage_profiles['ManagedCustomImage']['osDisk']['managedDisk'].update({
'securityProfile': {
'securityEncryptionType': os_disk_security_encryption_type,
}
})
storage_profiles['SharedGalleryImage']['osDisk']['managedDisk'].update({
'securityProfile': {
'securityEncryptionType': os_disk_security_encryption_type,
}
})
storage_profiles['CommunityGalleryImage']['osDisk']['managedDisk'].update({
'securityProfile': {
'securityEncryptionType': os_disk_security_encryption_type,
}
})
if os_disk_secure_vm_disk_encryption_set is not None:
storage_profiles['ManagedPirImage']['osDisk']['managedDisk']['securityProfile'].update({
'diskEncryptionSet': {
'id': os_disk_secure_vm_disk_encryption_set
}
})
storage_profiles['ManagedCustomImage']['osDisk']['managedDisk']['securityProfile'].update({
'diskEncryptionSet': {
'id': os_disk_secure_vm_disk_encryption_set
}
})
storage_profiles['SharedGalleryImage']['osDisk']['managedDisk']['securityProfile'].update({
'diskEncryptionSet': {
'id': os_disk_secure_vm_disk_encryption_set
}
})
storage_profiles['CommunityGalleryImage']['osDisk']['managedDisk']['securityProfile'].update({
'diskEncryptionSet': {
'id': os_disk_secure_vm_disk_encryption_set
}
})
profile = storage_profiles[storage_profile.name]
if os_disk_size_gb:
profile['osDisk']['diskSizeGb'] = os_disk_size_gb
if disk_info['os'].get('writeAcceleratorEnabled') is not None:
profile['osDisk']['writeAcceleratorEnabled'] = disk_info['os']['writeAcceleratorEnabled']
if os_disk_delete_option is not None:
profile['osDisk']['deleteOption'] = os_disk_delete_option
data_disks = [v for k, v in disk_info.items() if k != 'os']
if data_disk_encryption_sets:
if len(data_disk_encryption_sets) != len(data_disks):
raise CLIError(
'usage error: Number of --data-disk-encryption-sets mismatches with number of data disks.')
for i, data_disk in enumerate(data_disks):
data_disk['managedDisk']['diskEncryptionSet'] = {'id': data_disk_encryption_sets[i]}
if data_disks:
profile['dataDisks'] = data_disks
for data_disk in profile['dataDisks']:
if disk_iops_read_write is not None:
data_disk['diskIOPSReadWrite'] = disk_iops_read_write
if disk_mbps_read_write is not None:
data_disk['diskMBPSReadWrite'] = disk_mbps_read_write
if disk_info['os'].get('diffDiskSettings'):
profile['osDisk']['diffDiskSettings'] = disk_info['os']['diffDiskSettings']
if disk_controller_type is not None:
profile['diskControllerType'] = disk_controller_type
if align_regional_disks_to_vm_zone is not None:
profile['alignRegionalDisksToVMZone'] = align_regional_disks_to_vm_zone
return profile
vm_properties = {'hardwareProfile': {'vmSize': size}, 'networkProfile': {'networkInterfaces': nics},
'storageProfile': _build_storage_profile()}
resiliency_profile = {}
if zone_movement is not None:
resiliency_profile.update({
'zoneMovement': {
'isEnabled': zone_movement
}
})
if resiliency_profile:
vm_properties['resiliencyProfile'] = resiliency_profile
scheduled_events_policy = {}
if additional_scheduled_events is not None:
scheduled_events_policy.update({
"scheduledEventsAdditionalPublishingTargets": {
"eventGridAndResourceGraph": {
"enable": additional_scheduled_events
}
}
})
if enable_user_redeploy_scheduled_events is not None:
scheduled_events_policy.update({
"userInitiatedRedeploy": {
"automaticallyApprove": enable_user_redeploy_scheduled_events
}
})
if enable_user_reboot_scheduled_events is not None:
scheduled_events_policy.update({
"userInitiatedReboot": {
"automaticallyApprove": enable_user_reboot_scheduled_events
}
})
if scheduled_events_policy:
vm_properties['scheduledEventsPolicy'] = scheduled_events_policy
vm_size_properties = {}
if v_cpus_available is not None:
vm_size_properties['vCPUsAvailable'] = v_cpus_available
if v_cpus_per_core is not None:
vm_size_properties['vCPUsPerCore'] = v_cpus_per_core
if vm_size_properties:
vm_properties['hardwareProfile']['vmSizeProperties'] = vm_size_properties
if availability_set_id:
vm_properties['availabilitySet'] = {'id': availability_set_id}
# vmss is ID
if vmss is not None:
vm_properties['virtualMachineScaleSet'] = {'id': vmss}
if not attach_os_disk and not specialized:
vm_properties['osProfile'] = _build_os_profile()
if license_type:
vm_properties['licenseType'] = license_type
if boot_diagnostics_storage_uri:
vm_properties['diagnosticsProfile'] = {
'bootDiagnostics': {
"enabled": True,
"storageUri": boot_diagnostics_storage_uri
}
}
if any((ultra_ssd_enabled, enable_hibernation)):
vm_properties['additionalCapabilities'] = {}
if ultra_ssd_enabled is not None:
vm_properties['additionalCapabilities']['ultraSSDEnabled'] = ultra_ssd_enabled
if enable_hibernation is not None:
vm_properties['additionalCapabilities']['hibernationEnabled'] = enable_hibernation
if proximity_placement_group:
vm_properties['proximityPlacementGroup'] = {'id': proximity_placement_group}
if dedicated_host:
vm_properties['host'] = {'id': dedicated_host}
if dedicated_host_group:
vm_properties['hostGroup'] = {'id': dedicated_host_group}
if priority is not None:
vm_properties['priority'] = priority
if eviction_policy is not None:
vm_properties['evictionPolicy'] = eviction_policy
if max_price is not None:
vm_properties['billingProfile'] = {'maxPrice': max_price}
vm_properties['securityProfile'] = {}
if encryption_at_host is not None:
vm_properties['securityProfile']['encryptionAtHost'] = encryption_at_host
proxy_agent_settings = {}
wire_server = {}
imds = {}
if enable_proxy_agent is not None:
proxy_agent_settings['enabled'] = enable_proxy_agent
if proxy_agent_mode is not None:
proxy_agent_settings['mode'] = proxy_agent_mode
if key_incarnation_id is not None:
proxy_agent_settings['keyIncarnationId'] = key_incarnation_id
if wire_server_mode is not None or wire_server_access_control_profile_reference_id is not None:
wire_server['mode'] = wire_server_mode
wire_server['inVMAccessControlProfileReferenceId'] = wire_server_access_control_profile_reference_id
if imds_mode is not None or imds_access_control_profile_reference_id is not None:
imds['mode'] = imds_mode
imds['inVMAccessControlProfileReferenceId'] = imds_access_control_profile_reference_id
if wire_server:
proxy_agent_settings['wireServer'] = wire_server
if imds:
proxy_agent_settings['imds'] = imds
if add_proxy_agent_extension is not None:
proxy_agent_settings['addProxyAgentExtension'] = add_proxy_agent_extension
if proxy_agent_settings:
vm_properties['securityProfile']['proxyAgentSettings'] = proxy_agent_settings
# The `Standard` is used for backward compatibility to allow customers to keep their current behavior
# after changing the default values to Trusted Launch VMs in the future.
if security_type is not None:
vm_properties['securityProfile']['securityType'] = security_type
from ._constants import COMPATIBLE_SECURITY_TYPE_VALUE
if security_type != COMPATIBLE_SECURITY_TYPE_VALUE and (
enable_secure_boot is not None or enable_vtpm is not None):
vm_properties['securityProfile']['uefiSettings'] = {
'secureBootEnabled': enable_secure_boot,
'vTpmEnabled': enable_vtpm
}
# Compatibility of various API versions
if vm_properties['securityProfile'] == {}:
del vm_properties['securityProfile']
if platform_fault_domain is not None:
vm_properties['platformFaultDomain'] = platform_fault_domain
if user_data:
vm_properties['userData'] = b64encode(user_data)
if capacity_reservation_group:
vm_properties['capacityReservation'] = {
'capacityReservationGroup': {
'id': capacity_reservation_group
}
}
vm = {
'apiVersion': '2025-04-01',
'type': 'Microsoft.Compute/virtualMachines',
'name': name,
'location': location,
'tags': tags,
'dependsOn': [],
'properties': vm_properties,
}
if zone:
vm['zones'] = zone
if count:
vm['copy'] = {
'name': 'vmcopy',
'mode': 'parallel',
'count': count
}
vm['name'] = "[concat('{}', copyIndex())]".format(name)
if edge_zone:
vm['extendedLocation'] = edge_zone
placement = {}
if zone_placement_policy is not None:
placement['zonePlacementPolicy'] = zone_placement_policy
if include_zones is not None:
placement['includeZones'] = include_zones
if exclude_zones is not None:
placement['excludeZones'] = exclude_zones
if placement:
vm['placement'] = placement
return vm
def _build_frontend_ip_config(name, public_ip_id=None, private_ip_address=None,
private_ip_allocation=None, subnet_id=None):
frontend_ip_config = {
'name': name
}
if public_ip_id:
frontend_ip_config.update({
'properties': {
'publicIPAddress': {
'id': public_ip_id
}
}
})
else:
frontend_ip_config.update({
'properties': {
'privateIPAllocationMethod': private_ip_allocation,
'privateIPAddress': private_ip_address,
'subnet': {
'id': subnet_id
}
}
})
return frontend_ip_config
def build_application_gateway_resource(_, name, location, tags, backend_pool_name, backend_port, frontend_ip_name,
public_ip_id, subnet_id, gateway_subnet_id,
private_ip_address, private_ip_allocation, sku, capacity):
frontend_ip_config = _build_frontend_ip_config(frontend_ip_name, public_ip_id,
private_ip_address, private_ip_allocation,
subnet_id)
def _ag_subresource_id(_type, name):
return "[concat(variables('appGwID'), '/{}/{}')]".format(_type, name)
frontend_ip_config_id = _ag_subresource_id('frontendIPConfigurations', frontend_ip_name)
frontend_port_id = _ag_subresource_id('frontendPorts', 'appGwFrontendPort')
http_listener_id = _ag_subresource_id('httpListeners', 'appGwHttpListener')
backend_address_pool_id = _ag_subresource_id('backendAddressPools', backend_pool_name)
backend_http_settings_id = _ag_subresource_id(
'backendHttpSettingsCollection', 'appGwBackendHttpSettings')
ag_properties = {
'backendAddressPools': [
{
'name': backend_pool_name
}
],
'backendHttpSettingsCollection': [
{
'name': 'appGwBackendHttpSettings',
'properties': {
'Port': backend_port,
'Protocol': 'Http',
'CookieBasedAffinity': 'Disabled'
}
}
],
'frontendIPConfigurations': [frontend_ip_config],
'frontendPorts': [
{
'name': 'appGwFrontendPort',
'properties': {
'Port': 80
}
}
],
'gatewayIPConfigurations': [
{
'name': 'appGwIpConfig',
'properties': {
'subnet': {'id': gateway_subnet_id}
}
}
],
'httpListeners': [
{
'name': 'appGwHttpListener',
'properties': {
'FrontendIPConfiguration': {'Id': frontend_ip_config_id},
'FrontendPort': {'Id': frontend_port_id},
'Protocol': 'Http',
'SslCertificate': None
}
}
],
'sku': {
'name': sku,
'tier': sku.split('_')[0],
'capacity': capacity
},
'requestRoutingRules': [
{
'Name': 'rule1',
'properties': {
'RuleType': 'Basic',
'httpListener': {'id': http_listener_id},
'backendAddressPool': {'id': backend_address_pool_id},
'backendHttpSettings': {'id': backend_http_settings_id}
}
}
]
}
ag = {
'type': 'Microsoft.Network/applicationGateways',
'name': name,
'location': location,
'tags': tags,
'apiVersion': '2015-06-15',
'dependsOn': [],
'properties': ag_properties
}
return ag
def build_load_balancer_resource(cmd, name, location, tags, backend_pool_name, nat_pool_name,
backend_port, frontend_ip_name, public_ip_id, subnet_id, private_ip_address,
private_ip_allocation, sku, instance_count, disable_overprovision, edge_zone=None):
lb_id = "resourceId('Microsoft.Network/loadBalancers', '{}')".format(name)
frontend_ip_config = _build_frontend_ip_config(frontend_ip_name, public_ip_id,
private_ip_address, private_ip_allocation,
subnet_id)
lb_properties = {
'backendAddressPools': [
{
'name': backend_pool_name
}
],
'frontendIPConfigurations': [frontend_ip_config]
}
if nat_pool_name:
lb_properties['inboundNatPools'] = [{
'name': nat_pool_name,
'properties': {
'frontendIPConfiguration': {
'id': "[concat({}, '/frontendIPConfigurations/', '{}')]".format(
lb_id, frontend_ip_name)
},
'protocol': 'tcp',
'frontendPortRangeStart': '50000',
# keep 50119 as minimum for backward compat, and ensure over-provision is taken care of
'frontendPortRangeEnd': str(max(50119, 49999 + instance_count * (1 if disable_overprovision else 2))),
'backendPort': backend_port
}
}]
lb = {
'type': 'Microsoft.Network/loadBalancers',
'name': name,
'location': location,
'tags': tags,
'apiVersion': get_target_network_api(cmd.cli_ctx),
'dependsOn': [],
'properties': lb_properties
}
if sku and cmd.supported_api_version(ResourceType.MGMT_NETWORK, min_api='2017-08-01'):
lb['sku'] = {'name': sku}
# LB rule is the way to enable SNAT so outbound connections are possible
if sku.lower() == 'standard':
lb_properties['loadBalancingRules'] = [{
"name": "LBRule",
"properties": {
"frontendIPConfiguration": {
'id': "[concat({}, '/frontendIPConfigurations/', '{}')]".format(lb_id, frontend_ip_name)
},
"backendAddressPool": {
"id": "[concat({}, '/backendAddressPools/', '{}')]".format(lb_id, backend_pool_name)
},
"protocol": "tcp",
"frontendPort": 80,
"backendPort": 80,
"enableFloatingIP": False,
"idleTimeoutInMinutes": 5,
}
}]
if edge_zone:
lb['apiVersion'] = '2021-02-01'
lb['extendedLocation'] = edge_zone
return lb
def build_nat_rule_v2(cmd, name, location, lb_name, frontend_ip_name, backend_pool_name, backend_port, instance_count,
disable_overprovision):
lb_id = "resourceId('Microsoft.Network/loadBalancers', '{}')".format(lb_name)
nat_rule = {
"type": "Microsoft.Network/loadBalancers/inboundNatRules",
"apiVersion": get_target_network_api(cmd.cli_ctx),
"name": name,
"location": location,
"properties": {
"frontendIPConfiguration": {
'id': "[concat({}, '/frontendIPConfigurations/', '{}')]".format(lb_id, frontend_ip_name)
},
"backendAddressPool": {
"id": "[concat({}, '/backendAddressPools/', '{}')]".format(lb_id, backend_pool_name)
},
"backendPort": backend_port,
"frontendPortRangeStart": "50000",
# This logic comes from the template of `inboundNatPools` to keep consistent with NAT pool
# keep 50119 as minimum for backward compat, and ensure over-provision is taken care of
"frontendPortRangeEnd": str(max(50119, 49999 + instance_count * (1 if disable_overprovision else 2))),
"protocol": "tcp",
"idleTimeoutInMinutes": 5
},
"dependsOn": [
"[concat('Microsoft.Network/loadBalancers/', '{}')]".format(lb_name)
]