-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy path_validators.py
More file actions
2891 lines (2417 loc) · 144 KB
/
_validators.py
File metadata and controls
2891 lines (2417 loc) · 144 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.
# --------------------------------------------------------------------------------------------
# pylint:disable=too-many-lines
import os
from urllib.parse import urlparse
from knack.log import get_logger
from knack.util import CLIError
from azure.cli.core.azclierror import (ValidationError, ArgumentUsageError, RequiredArgumentMissingError,
MutuallyExclusiveArgumentError, CLIInternalError)
from azure.cli.core.commands.validators import (
get_default_location_from_resource_group, validate_file_or_dict, validate_parameter_set, validate_tags)
from azure.cli.core.util import (hash_string, DISALLOWED_USER_NAMES, get_default_admin_username)
from azure.cli.command_modules.vm._vm_utils import (check_existence, get_storage_blob_uri, list_sku_info,
import_aaz_by_profile)
from azure.cli.command_modules.vm._template_builder import StorageProfile
from azure.cli.core import keys
from azure.core.exceptions import ResourceNotFoundError
from ._client_factory import _compute_client_factory
from ._actions import _get_latest_image_version_by_aaz
logger = get_logger(__name__)
def validate_asg_names_or_ids(cmd, namespace):
from azure.mgmt.core.tools import is_valid_resource_id, resource_id
from azure.cli.core.commands.client_factory import get_subscription_id
resource_group = namespace.resource_group_name
subscription_id = get_subscription_id(cmd.cli_ctx)
names_or_ids = getattr(namespace, 'application_security_groups')
ids = []
if names_or_ids == [""] or not names_or_ids:
return
for val in names_or_ids:
if not is_valid_resource_id(val):
val = resource_id(
subscription=subscription_id,
resource_group=resource_group,
namespace='Microsoft.Network', type='applicationSecurityGroups',
name=val
)
ids.append({'id': val})
setattr(namespace, 'application_security_groups', ids)
def validate_nsg_name(cmd, namespace):
from azure.mgmt.core.tools import resource_id
from azure.cli.core.commands.client_factory import get_subscription_id
vm_id = resource_id(name=namespace.vm_name, resource_group=namespace.resource_group_name,
namespace='Microsoft.Compute', type='virtualMachines',
subscription=get_subscription_id(cmd.cli_ctx))
namespace.network_security_group_name = namespace.network_security_group_name \
or '{}_NSG_{}'.format(namespace.vm_name, hash_string(vm_id, length=8))
def validate_keyvault(cmd, namespace):
namespace.keyvault = _get_resource_id(cmd.cli_ctx, namespace.keyvault, namespace.resource_group_name,
'vaults', 'Microsoft.KeyVault')
def validate_vm_name_for_monitor_metrics(cmd, namespace):
if hasattr(namespace, 'resource'):
namespace.resource = _get_resource_id(cmd.cli_ctx, namespace.resource, namespace.resource_group_name,
'virtualMachines', 'Microsoft.Compute')
elif hasattr(namespace, 'resource_uri'):
namespace.resource_uri = _get_resource_id(cmd.cli_ctx, namespace.resource_uri, namespace.resource_group_name,
'virtualMachines', 'Microsoft.Compute')
del namespace.resource_group_name
def _validate_proximity_placement_group(cmd, namespace):
from azure.mgmt.core.tools import parse_resource_id
if namespace.proximity_placement_group:
namespace.proximity_placement_group = _get_resource_id(cmd.cli_ctx, namespace.proximity_placement_group,
namespace.resource_group_name,
'proximityPlacementGroups', 'Microsoft.Compute')
parsed = parse_resource_id(namespace.proximity_placement_group)
rg, name = parsed['resource_group'], parsed['name']
if not check_existence(cmd.cli_ctx, name, rg, 'Microsoft.Compute',
'proximityPlacementGroups', static_version='2024-07-01'):
raise CLIError("Proximity Placement Group '{}' does not exist.".format(name))
def process_vm_secret_format(cmd, namespace):
from azure.mgmt.core.tools import is_valid_resource_id
from azure.cli.core._output import (get_output_format, set_output_format)
keyvault_usage = CLIError('usage error: [--keyvault NAME --resource-group NAME | --keyvault ID]')
kv = namespace.keyvault
rg = namespace.resource_group_name
if rg:
if not kv or is_valid_resource_id(kv):
raise keyvault_usage
validate_keyvault(cmd, namespace)
else:
if kv and not is_valid_resource_id(kv):
raise keyvault_usage
warning_msg = "This command does not support the {} output format. Showing JSON format instead."
desired_formats = ["json", "jsonc"]
output_format = get_output_format(cmd.cli_ctx)
if output_format not in desired_formats:
warning_msg = warning_msg.format(output_format)
logger.warning(warning_msg)
set_output_format(cmd.cli_ctx, desired_formats[0])
def _get_resource_group_from_vault_name(cli_ctx, vault_name):
"""
Fetch resource group from vault name
:param str vault_name: name of the key vault
:return: resource group name or None
:rtype: str
"""
from azure.cli.core.profiles import ResourceType
from azure.cli.core.commands.client_factory import get_mgmt_service_client
from azure.mgmt.core.tools import parse_resource_id
client = get_mgmt_service_client(cli_ctx, ResourceType.MGMT_KEYVAULT).vaults
for vault in client.list():
id_comps = parse_resource_id(vault.id)
if id_comps['name'] == vault_name:
return id_comps['resource_group']
return None
def _get_resource_id(cli_ctx, val, resource_group, resource_type, resource_namespace):
from azure.mgmt.core.tools import resource_id, is_valid_resource_id
from azure.cli.core.commands.client_factory import get_subscription_id
if is_valid_resource_id(val):
return val
kwargs = {
'name': val,
'resource_group': resource_group,
'namespace': resource_namespace,
'type': resource_type,
'subscription': get_subscription_id(cli_ctx)
}
missing_kwargs = {k: v for k, v in kwargs.items() if not v}
return resource_id(**kwargs) if not missing_kwargs else None
def _get_nic_id(cli_ctx, val, resource_group):
return _get_resource_id(cli_ctx, val, resource_group,
'networkInterfaces', 'Microsoft.Network')
def validate_vm_nic(cmd, namespace):
namespace.nic = _get_nic_id(cmd.cli_ctx, namespace.nic, namespace.resource_group_name)
def validate_vm_nics(cmd, namespace):
rg = namespace.resource_group_name
nic_ids = []
for n in namespace.nics:
nic_ids.append(_get_nic_id(cmd.cli_ctx, n, rg))
namespace.nics = nic_ids
if hasattr(namespace, 'primary_nic') and namespace.primary_nic:
namespace.primary_nic = _get_nic_id(cmd.cli_ctx, namespace.primary_nic, rg)
def _validate_secrets(secrets, os_type):
"""
Validates a parsed JSON array containing secrets for use in VM Creation
Secrets JSON structure
[{
"sourceVault": { "id": "value" },
"vaultCertificates": [{
"certificateUrl": "value",
"certificateStore": "cert store name (only on windows)"
}]
}]
:param dict secrets: Dict fitting the JSON description above
:param string os_type: the type of OS (linux or windows)
:return: errors if any were found
:rtype: list
"""
is_windows = os_type == 'windows'
errors = []
try:
loaded_secret = [validate_file_or_dict(secret) for secret in secrets]
except Exception as err:
raise CLIError('Error decoding secrets: {0}'.format(err))
for idx_arg, narg_secret in enumerate(loaded_secret):
for idx, secret in enumerate(narg_secret):
if 'sourceVault' not in secret:
errors.append(
'Secret is missing sourceVault key at index {0} in arg {1}'.format(
idx, idx_arg))
if 'sourceVault' in secret and 'id' not in secret['sourceVault']:
errors.append(
'Secret is missing sourceVault.id key at index {0} in arg {1}'.format(
idx, idx_arg))
if 'vaultCertificates' not in secret or not secret['vaultCertificates']:
err = 'Secret is missing vaultCertificates array or it is empty at index {0} in ' \
'arg {1} '
errors.append(err.format(idx, idx_arg))
else:
for jdx, cert in enumerate(secret['vaultCertificates']):
message = 'Secret is missing {0} within vaultCertificates array at secret ' \
'index {1} and vaultCertificate index {2} in arg {3}'
if 'certificateUrl' not in cert:
errors.append(message.format('certificateUrl', idx, jdx, idx_arg))
if is_windows and 'certificateStore' not in cert:
errors.append(message.format('certificateStore', idx, jdx, idx_arg))
if errors:
raise CLIError('\n'.join(errors))
# region VM Create Validators
# pylint: disable=too-many-return-statements
def _parse_image_argument(cmd, namespace):
""" Systematically determines what type is supplied for the --image parameter. Updates the
namespace and returns the type for subsequent processing. """
from azure.mgmt.core.tools import is_valid_resource_id
from azure.core.exceptions import HttpResponseError
import re
# 1 - check if a fully-qualified ID (assumes it is an image ID)
if is_valid_resource_id(namespace.image):
return 'image_id'
from ._vm_utils import is_shared_gallery_image_id, is_community_gallery_image_id
if is_shared_gallery_image_id(namespace.image):
return 'shared_gallery_image_id'
if is_community_gallery_image_id(namespace.image):
return 'community_gallery_image_id'
# 2 - attempt to match an URN pattern
urn_match = re.match('([^:]*):([^:]*):([^:]*):([^:]*)', namespace.image)
if urn_match:
namespace.os_publisher = urn_match.group(1)
namespace.os_offer = urn_match.group(2)
namespace.os_sku = urn_match.group(3)
namespace.os_version = urn_match.group(4)
if not any([namespace.plan_name, namespace.plan_product, namespace.plan_publisher]):
image_plan = _get_image_plan_info_if_exists(cmd, namespace)
if image_plan and image_plan.get('name') and image_plan.get('product') and image_plan.get('publisher'):
namespace.plan_name = image_plan['name']
namespace.plan_product = image_plan['product']
namespace.plan_publisher = image_plan['publisher']
return 'urn'
# 3 - unmanaged vhd based images?
if urlparse(namespace.image).scheme and "://" in namespace.image:
return 'uri'
# 4 - attempt to match an URN alias (most likely)
from azure.cli.command_modules.vm._actions import load_images_from_aliases_doc
import requests
try:
images = None
images = load_images_from_aliases_doc(cmd.cli_ctx)
matched = next((x for x in images if x['urnAlias'].lower() == namespace.image.lower()), None)
if matched:
namespace.os_publisher = matched['publisher']
namespace.os_offer = matched['offer']
namespace.os_sku = matched['sku']
namespace.os_version = matched['version']
if not any([namespace.plan_name, namespace.plan_product, namespace.plan_publisher]):
image_plan = _get_image_plan_info_if_exists(cmd, namespace)
if image_plan and image_plan.get('name') and image_plan.get('product') and image_plan.get('publisher'):
namespace.plan_name = image_plan['name']
namespace.plan_product = image_plan['product']
namespace.plan_publisher = image_plan['publisher']
return 'urn'
except requests.exceptions.ConnectionError:
pass
# 5 - check if an existing managed disk image resource
try:
from .aaz.latest.image import Show as ImageShow
command_args = {
'image_name': namespace.image,
'resource_group': namespace.resource_group_name
}
# Purpose of calling ImageShow is just to check its existence
ImageShow(cli_ctx=cmd.cli_ctx, command_args=command_args)
namespace.image = _get_resource_id(cmd.cli_ctx, namespace.image, namespace.resource_group_name,
'images', 'Microsoft.Compute')
return 'image_id'
except HttpResponseError:
if images is not None:
err = 'Invalid image "{}". Use a valid image URN, custom image name, custom image id, ' \
'VHD blob URI, or pick an image from {}.\nSee vm create -h for more information ' \
'on specifying an image.'.format(namespace.image, [x['urnAlias'] for x in images])
else:
err = 'Failed to connect to remote source of image aliases or find a local copy. Invalid image "{}". ' \
'Use a valid image URN, custom image name, custom image id, or VHD blob URI.\nSee vm ' \
'create -h for more information on specifying an image.'.format(namespace.image)
raise CLIError(err)
def _get_image_plan_info_if_exists(cmd, namespace):
try:
from .aaz.latest.vm.image import Show as VmImageShow
if namespace.os_version.lower() == 'latest':
image_version = _get_latest_image_version_by_aaz(cmd.cli_ctx, namespace.location, namespace.os_publisher,
namespace.os_offer, namespace.os_sku)
else:
image_version = namespace.os_version
command_args = {
'location': namespace.location,
'offer': namespace.os_offer,
'publisher': namespace.os_publisher,
'sku': namespace.os_sku,
'version': image_version,
}
image = VmImageShow(cli_ctx=cmd.cli_ctx)(command_args=command_args)
return image.get('plan')
except ResourceNotFoundError as ex:
logger.warning("Querying the image of '%s' failed for an error '%s'. Configuring plan settings "
"will be skipped", namespace.image, ex.message)
# pylint: disable=inconsistent-return-statements, too-many-return-statements
def _get_storage_profile_description(profile):
if profile == StorageProfile.SACustomImage:
return 'create unmanaged OS disk created from generalized VHD'
if profile == StorageProfile.SAPirImage:
return 'create unmanaged OS disk from Azure Marketplace image'
if profile == StorageProfile.SASpecializedOSDisk:
return 'attach to existing unmanaged OS disk'
if profile == StorageProfile.ManagedCustomImage:
return 'create managed OS disk from custom image'
if profile == StorageProfile.ManagedPirImage:
return 'create managed OS disk from Azure Marketplace image'
if profile == StorageProfile.ManagedSpecializedOSDisk:
return 'attach existing managed OS disk'
if profile == StorageProfile.SharedGalleryImage:
return 'create OS disk from shared gallery image'
if profile == StorageProfile.CommunityGalleryImage:
return 'create OS disk from community gallery image'
def _validate_location(cmd, namespace, zone_info, size_info):
if not namespace.location:
get_default_location_from_resource_group(cmd, namespace)
if zone_info and size_info:
sku_infos = list_sku_info(cmd.cli_ctx, namespace.location)
temp = next((x for x in sku_infos if x['name'].lower() == size_info.lower()), None)
# For Stack (compute - 2017-03-30), Resource_sku doesn't implement location_info property
if not temp.get('locationInfo', None):
return
if not temp or not [x for x in temp.get('locationInfo', []) if x.get('zones', None)]:
raise CLIError("{}'s location can't be used to create the VM/VMSS because availability zone is not yet "
"supported. Please use '--location' to specify a capable one. 'az vm list-skus' can be "
"used to find such locations".format(namespace.resource_group_name))
# pylint: disable=too-many-branches, too-many-statements, too-many-locals
def _validate_vm_create_storage_profile(cmd, namespace, for_scale_set=False):
from azure.mgmt.core.tools import parse_resource_id
_validate_vm_vmss_create_ephemeral_placement(namespace)
# specialized is only for image
if getattr(namespace, 'specialized', None) is not None and namespace.image is None:
raise CLIError('usage error: --specialized is only configurable when --image is specified.')
# use minimal parameters to resolve the expected storage profile
if getattr(namespace, 'attach_os_disk', None) and not namespace.image:
if namespace.use_unmanaged_disk:
# STORAGE PROFILE #3
namespace.storage_profile = StorageProfile.SASpecializedOSDisk
else:
# STORAGE PROFILE #6
namespace.storage_profile = StorageProfile.ManagedSpecializedOSDisk
elif namespace.image and not getattr(namespace, 'attach_os_disk', None):
image_type = _parse_image_argument(cmd, namespace)
if image_type == 'uri':
# STORAGE PROFILE #2
namespace.storage_profile = StorageProfile.SACustomImage
elif image_type == 'image_id':
# STORAGE PROFILE #5
namespace.storage_profile = StorageProfile.ManagedCustomImage
elif image_type == 'shared_gallery_image_id':
namespace.storage_profile = StorageProfile.SharedGalleryImage
elif image_type == 'community_gallery_image_id':
namespace.storage_profile = StorageProfile.CommunityGalleryImage
elif image_type == 'urn':
if namespace.use_unmanaged_disk:
# STORAGE PROFILE #1
namespace.storage_profile = StorageProfile.SAPirImage
else:
# STORAGE PROFILE #4
namespace.storage_profile = StorageProfile.ManagedPirImage
else:
raise CLIError('Unrecognized image type: {}'.format(image_type))
elif not namespace.image and not getattr(namespace, 'attach_os_disk', None):
namespace.image = 'MicrosoftWindowsServer:WindowsServer:2022-datacenter-azure-edition:latest'
_parse_image_argument(cmd, namespace)
namespace.storage_profile = StorageProfile.ManagedPirImage
if namespace.enable_secure_boot is None:
namespace.enable_secure_boot = True
if namespace.enable_vtpm is None:
namespace.enable_vtpm = True
if namespace.security_type is None:
namespace.security_type = 'TrustedLaunch'
else:
# did not specify image XOR attach-os-disk
raise CLIError('incorrect usage: --image IMAGE | --attach-os-disk DISK')
auth_params = ['admin_password', 'admin_username', 'authentication_type',
'generate_ssh_keys', 'ssh_dest_key_path', 'ssh_key_value']
# perform parameter validation for the specific storage profile
# start with the required/forbidden parameters for VM
if namespace.storage_profile == StorageProfile.ManagedPirImage:
required = ['image']
forbidden = ['os_type', 'attach_os_disk', 'storage_account',
'storage_container_name', 'use_unmanaged_disk']
if for_scale_set:
forbidden.append('os_disk_name')
elif namespace.storage_profile == StorageProfile.ManagedCustomImage:
required = ['image']
forbidden = ['os_type', 'attach_os_disk', 'storage_account',
'storage_container_name', 'use_unmanaged_disk']
if for_scale_set:
forbidden.append('os_disk_name')
elif namespace.storage_profile == StorageProfile.SharedGalleryImage:
required = ['image']
forbidden = ['attach_os_disk', 'storage_account', 'storage_container_name', 'use_unmanaged_disk']
elif namespace.storage_profile == StorageProfile.CommunityGalleryImage:
required = ['image']
forbidden = ['attach_os_disk', 'storage_account', 'storage_container_name', 'use_unmanaged_disk']
elif namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk:
required = ['os_type', 'attach_os_disk']
forbidden = ['os_disk_name', 'os_caching', 'storage_account', 'ephemeral_os_disk',
'storage_container_name', 'use_unmanaged_disk', 'storage_sku'] + auth_params
elif namespace.storage_profile == StorageProfile.SAPirImage:
required = ['image', 'use_unmanaged_disk']
forbidden = ['os_type', 'attach_os_disk', 'data_disk_sizes_gb', 'ephemeral_os_disk']
elif namespace.storage_profile == StorageProfile.SACustomImage:
required = ['image', 'os_type', 'use_unmanaged_disk']
forbidden = ['attach_os_disk', 'data_disk_sizes_gb', 'ephemeral_os_disk']
elif namespace.storage_profile == StorageProfile.SASpecializedOSDisk:
required = ['os_type', 'attach_os_disk', 'use_unmanaged_disk']
forbidden = ['os_disk_name', 'os_caching', 'image', 'storage_account', 'ephemeral_os_disk',
'storage_container_name', 'data_disk_sizes_gb', 'storage_sku'] + auth_params
else:
raise CLIError('Unrecognized storage profile: {}'.format(namespace.storage_profile))
logger.debug("storage profile '%s'", namespace.storage_profile)
if for_scale_set:
# VMSS lacks some parameters, so scrub these out
props_to_remove = ['attach_os_disk', 'storage_account']
for prop in props_to_remove:
if prop in required:
required.remove(prop)
if prop in forbidden:
forbidden.remove(prop)
# set default storage SKU if not provided and using an image based OS
if not namespace.storage_sku and namespace.storage_profile in [StorageProfile.SAPirImage, StorageProfile.SACustomImage]: # pylint: disable=line-too-long
namespace.storage_sku = ['Standard_LRS'] if for_scale_set else ['Premium_LRS']
if namespace.ultra_ssd_enabled is None and namespace.storage_sku:
for sku in namespace.storage_sku:
if 'ultrassd_lrs' in sku.lower():
namespace.ultra_ssd_enabled = True
# Now verify the presence of required and absence of forbidden parameters
validate_parameter_set(
namespace, required, forbidden,
description='storage profile: {}:'.format(_get_storage_profile_description(namespace.storage_profile)))
image_data_disks = []
if namespace.storage_profile == StorageProfile.ManagedCustomImage:
# extract additional information from a managed custom image
res = parse_resource_id(namespace.image)
namespace.aux_subscriptions = [res['subscription']]
if res['type'].lower() == 'images':
from .aaz.latest.image import Show as ImageShow
command_args = {
'image_name': res['name'],
'resource_group': res['resource_group'],
'subscription': res['subscription']
}
image_info = ImageShow(cli_ctx=cmd.cli_ctx)(command_args=command_args)
namespace.os_type = image_info.get('storageProfile', {}).get('osDisk', {}).get('osType')
image_data_disks = image_info.get('storageProfile', {}).get('dataDisks', [])
image_data_disks = [{'lun': disk.get('lun')} for disk in image_data_disks]
elif res['type'].lower() == 'galleries':
from .aaz.latest.sig.image_definition import Show as SigImageDefinitionShow
command_args = {
'gallery_image_definition': res['child_name_1'],
'gallery_name': res['name'],
'resource_group': res['resource_group'],
'subscription': res['subscription']
}
image_info = SigImageDefinitionShow(cli_ctx=cmd.cli_ctx)(command_args=command_args)
namespace.os_type = image_info.get('osType')
gallery_image_version = res.get('child_name_2', '')
if gallery_image_version.lower() in ['latest', '']:
from .aaz.latest.sig.image_version import List as _SigImageVersionList
image_version_infos = _SigImageVersionList(cli_ctx=cmd.cli_ctx)(command_args={
"resource_group": res['resource_group'],
"gallery_name": res['name'],
"gallery_image_definition": res['child_name_1'],
"subscription": res['subscription'],
})
image_version_infos = [x for x in image_version_infos
if not x.get("publishingProfile", {}).get("excludeFromLatest", None)]
if not image_version_infos:
raise CLIError('There is no latest image version exists for "{}"'.format(namespace.image))
image_version_info = sorted(image_version_infos,
key=lambda x: x["publishingProfile"]["publishedDate"])[-1]
image_data_disks = image_version_info.get("storageProfile", {}).get("dataDiskImages", []) or []
image_data_disks = [{'lun': disk["lun"]} for disk in image_data_disks]
else:
from .aaz.latest.sig.image_version import Show as _SigImageVersionShow
image_version_info = _SigImageVersionShow(cli_ctx=cmd.cli_ctx)(command_args={
"resource_group": res['resource_group'],
"gallery_name": res['name'],
"gallery_image_definition": res['child_name_1'],
"gallery_image_version_name": res['child_name_2'],
"subscription": res['subscription']
})
image_data_disks = image_version_info.get("storageProfile", {}).get("dataDiskImages", []) or []
image_data_disks = [{'lun': disk["lun"]} for disk in image_data_disks]
else:
raise CLIError('usage error: unrecognized image information "{}"'.format(namespace.image))
# pylint: disable=no-member
elif namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk:
# accept disk name or ID
namespace.attach_os_disk = _get_resource_id(
cmd.cli_ctx, namespace.attach_os_disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute')
if getattr(namespace, 'attach_data_disks', None):
if not namespace.use_unmanaged_disk:
namespace.attach_data_disks = [_get_resource_id(cmd.cli_ctx, d, namespace.resource_group_name, 'disks',
'Microsoft.Compute') for d in namespace.attach_data_disks]
if namespace.storage_profile == StorageProfile.SharedGalleryImage:
if namespace.location is None:
raise RequiredArgumentMissingError(
'Please input the location of the shared gallery image through the parameter --location.')
from ._vm_utils import parse_shared_gallery_image_id
image_info = parse_shared_gallery_image_id(namespace.image)
from .aaz.latest.sig.image_definition import ShowShared as SigImageDefinitionShowShared
command_args = {
'gallery_image_definition': image_info[1],
'gallery_unique_name': image_info[0],
'location': namespace.location,
}
shared_gallery_image_info = SigImageDefinitionShowShared(cli_ctx=cmd.cli_ctx)(command_args=command_args)
if namespace.os_type and namespace.os_type.lower() != shared_gallery_image_info.get('osType', '').lower():
raise ArgumentUsageError("The --os-type is not the correct os type of this shared gallery image, "
"the os type of this image should be {}"
.format(shared_gallery_image_info.get('osType', '')))
namespace.os_type = shared_gallery_image_info['osType']
if namespace.storage_profile == StorageProfile.CommunityGalleryImage:
if namespace.location is None:
raise RequiredArgumentMissingError(
'Please input the location of the community gallery image through the parameter --location.')
from ._vm_utils import parse_community_gallery_image_id
image_info = parse_community_gallery_image_id(namespace.image)
from .aaz.latest.sig.image_definition import ShowCommunity as SigImageDefinitionShowCommunity
command_args = {
'gallery_image_definition': image_info[1],
'public_gallery_name': image_info[0],
'location': namespace.location
}
community_gallery_image_info = SigImageDefinitionShowCommunity(cli_ctx=cmd.cli_ctx)(command_args=command_args)
if namespace.os_type and namespace.os_type.lower() != community_gallery_image_info.get('osType', '').lower():
raise ArgumentUsageError(
"The --os-type is not the correct os type of this community gallery image, "
"the os type of this image should be {}".format(community_gallery_image_info.get('osType', '')))
namespace.os_type = community_gallery_image_info['osType']
if getattr(namespace, 'security_type', None) == 'ConfidentialVM' and \
not getattr(namespace, 'os_disk_security_encryption_type', None):
raise RequiredArgumentMissingError('usage error: "--os-disk-security-encryption-type" is required '
'when "--security-type" is specified as "ConfidentialVM"')
if getattr(namespace, 'os_disk_secure_vm_disk_encryption_set', None) and \
getattr(namespace, 'os_disk_security_encryption_type', None) != 'DiskWithVMGuestState':
raise ArgumentUsageError(
'usage error: The "--os-disk-secure-vm-disk-encryption-set" can only be passed in '
'when "--os-disk-security-encryption-type" is "DiskWithVMGuestState"')
os_disk_security_encryption_type = getattr(namespace, 'os_disk_security_encryption_type', None)
if os_disk_security_encryption_type and os_disk_security_encryption_type.lower() == 'nonpersistedtpm':
if ((getattr(namespace, 'security_type', None) != 'ConfidentialVM') or
not getattr(namespace, 'enable_vtpm', None)):
raise ArgumentUsageError(
'usage error: The "--os-disk-security-encryption-type NonPersistedTPM" can only be passed in '
'when "--security-type" is "ConfidentialVM" and "--enable-vtpm" is True')
if not namespace.os_type:
namespace.os_type = 'windows' if 'windows' in namespace.os_offer.lower() else 'linux'
if getattr(namespace, 'source_snapshots_or_disks', None) and \
getattr(namespace, 'source_snapshots_or_disks_size_gb', None):
if len(namespace.source_snapshots_or_disks) != len(namespace.source_snapshots_or_disks_size_gb):
raise ArgumentUsageError(
'Length of --source-snapshots-or-disks, --source-snapshots-or-disks-size-gb must be same.')
elif getattr(namespace, 'source_snapshots_or_disks', None) or \
getattr(namespace, 'source_snapshots_or_disks_size_gb', None):
raise ArgumentUsageError('usage error: --source-snapshots-or-disks and '
'--source-snapshots-or-disks-size-gb must be used together')
if getattr(namespace, 'source_disk_restore_point', None) and \
getattr(namespace, 'source_disk_restore_point_size_gb', None):
if len(namespace.source_disk_restore_point) != len(namespace.source_disk_restore_point_size_gb):
raise ArgumentUsageError(
'Length of --source-disk-restore-point, --source-disk-restore-point-size-gb must be same.')
elif getattr(namespace, 'source_disk_restore_point', None) or \
getattr(namespace, 'source_disk_restore_point_size_gb', None):
raise ArgumentUsageError('usage error: --source-disk-restore-point and '
'--source-disk-restore-point-size-gb must be used together')
from ._vm_utils import normalize_disk_info
# attach_data_disks are not exposed yet for VMSS, so use 'getattr' to avoid crash
vm_size = (getattr(namespace, 'size', None) or getattr(namespace, 'vm_sku', None))
# pylint: disable=line-too-long
namespace.disk_info = normalize_disk_info(size=vm_size,
image_data_disks=image_data_disks,
data_disk_sizes_gb=namespace.data_disk_sizes_gb,
attach_data_disks=getattr(namespace, 'attach_data_disks', []),
storage_sku=namespace.storage_sku,
os_disk_caching=namespace.os_caching,
data_disk_cachings=namespace.data_caching,
ephemeral_os_disk=getattr(namespace, 'ephemeral_os_disk', None),
ephemeral_os_disk_placement=getattr(namespace, 'ephemeral_os_disk_placement', None),
data_disk_delete_option=getattr(
namespace, 'data_disk_delete_option', None),
source_snapshots_or_disks=getattr(namespace, 'source_snapshots_or_disks', None),
source_snapshots_or_disks_size_gb=getattr(namespace, 'source_snapshots_or_disks_size_gb', None),
source_disk_restore_point=getattr(namespace, 'source_disk_restore_point', None),
source_disk_restore_point_size_gb=getattr(namespace, 'source_disk_restore_point_size_gb', None)
)
def _validate_vm_create_storage_account(cmd, namespace):
from azure.mgmt.core.tools import parse_resource_id
if namespace.storage_account:
storage_id = parse_resource_id(namespace.storage_account)
rg = storage_id.get('resource_group', namespace.resource_group_name)
if check_existence(cmd.cli_ctx, storage_id['name'], rg, 'Microsoft.Storage',
'storageAccounts', static_version='2024-01-01'):
# 1 - existing storage account specified
namespace.storage_account_type = 'existing'
logger.debug("using specified existing storage account '%s'", storage_id['name'])
else:
# 2 - params for new storage account specified
namespace.storage_account_type = 'new'
logger.debug("specified storage account '%s' not found and will be created", storage_id['name'])
else:
from azure.cli.core.profiles import ResourceType
from azure.cli.core.commands.client_factory import get_mgmt_service_client
storage_client = get_mgmt_service_client(cmd.cli_ctx, ResourceType.MGMT_STORAGE).storage_accounts
# find storage account in target resource group that matches the VM's location
sku_tier = 'Standard'
for sku in namespace.storage_sku:
if 'Premium' in sku:
sku_tier = 'Premium'
break
account = next(
(a for a in storage_client.list_by_resource_group(namespace.resource_group_name)
if a.sku.tier == sku_tier and a.location == namespace.location), None)
if account:
# 3 - nothing specified - find viable storage account in target resource group
namespace.storage_account = account.name
namespace.storage_account_type = 'existing'
logger.debug("suitable existing storage account '%s' will be used", account.name)
else:
# 4 - nothing specified - create a new storage account
namespace.storage_account_type = 'new'
logger.debug('no suitable storage account found. One will be created.')
def _validate_vm_create_availability_set(cmd, namespace):
from azure.mgmt.core.tools import parse_resource_id, resource_id
from azure.cli.core.commands.client_factory import get_subscription_id
if namespace.availability_set:
as_id = parse_resource_id(namespace.availability_set)
name = as_id['name']
rg = as_id.get('resource_group', namespace.resource_group_name)
if not check_existence(cmd.cli_ctx, name, rg, 'Microsoft.Compute',
'availabilitySets', static_version='2024-07-01'):
raise CLIError("Availability set '{}' does not exist.".format(name))
namespace.availability_set = resource_id(
subscription=get_subscription_id(cmd.cli_ctx),
resource_group=rg,
namespace='Microsoft.Compute',
type='availabilitySets',
name=name)
logger.debug("adding to specified availability set '%s'", namespace.availability_set)
def _validate_vm_create_vmss(cmd, namespace):
from azure.mgmt.core.tools import parse_resource_id, resource_id
from azure.cli.core.commands.client_factory import get_subscription_id
if namespace.vmss:
as_id = parse_resource_id(namespace.vmss)
name = as_id['name']
rg = as_id.get('resource_group', namespace.resource_group_name)
if not check_existence(cmd.cli_ctx, name, rg, 'Microsoft.Compute',
'virtualMachineScaleSets', static_version='2025-04-01'):
raise CLIError("virtual machine scale set '{}' does not exist.".format(name))
namespace.vmss = resource_id(
subscription=get_subscription_id(cmd.cli_ctx),
resource_group=rg,
namespace='Microsoft.Compute',
type='virtualMachineScaleSets',
name=name)
logger.debug("adding to specified virtual machine scale set '%s'", namespace.vmss)
def _validate_vm_create_dedicated_host(cmd, namespace):
"""
"host": {
"$ref": "#/definitions/SubResource",
"description": "Specifies information about the dedicated host that the virtual machine resides in.
<br><br>Minimum api-version: 2018-10-01."
},
"hostGroup": {
"$ref": "#/definitions/SubResource",
"description": "Specifies information about the dedicated host group that the virtual machine resides in.
<br><br>Minimum api-version: 2020-06-01. <br><br>NOTE: User cannot specify both host and hostGroup properties."
}
:param cmd:
:param namespace:
:return:
"""
from azure.mgmt.core.tools import resource_id, is_valid_resource_id
from azure.cli.core.commands.client_factory import get_subscription_id
if namespace.dedicated_host and namespace.dedicated_host_group:
raise CLIError('usage error: User cannot specify both --host and --host-group properties.')
if namespace.dedicated_host and not is_valid_resource_id(namespace.dedicated_host):
raise CLIError('usage error: --host is not a valid resource ID.')
if namespace.dedicated_host_group:
if not is_valid_resource_id(namespace.dedicated_host_group):
namespace.dedicated_host_group = resource_id(
subscription=get_subscription_id(cmd.cli_ctx), resource_group=namespace.resource_group_name,
namespace='Microsoft.Compute', type='hostGroups', name=namespace.dedicated_host_group
)
def _validate_vm_vmss_create_vnet(cmd, namespace, for_scale_set=False):
from azure.mgmt.core.tools import is_valid_resource_id
vnet = namespace.vnet_name
subnet = namespace.subnet
rg = namespace.resource_group_name
location = namespace.location
nics = getattr(namespace, 'nics', None)
if vnet and '/' in vnet:
raise CLIError("incorrect usage: --subnet ID | --subnet NAME --vnet-name NAME")
if not vnet and not subnet and not nics:
logger.debug('no subnet specified. Attempting to find an existing Vnet and subnet...')
# if nothing specified, try to find an existing vnet and subnet in the target resource group
VnetList = import_aaz_by_profile(cmd.cli_ctx.cloud.profile, "network.vnet").List
vnet_list = VnetList(cli_ctx=cmd.cli_ctx)(command_args={
"resource_group": rg
})
# find VNET in target resource group that matches the VM's location with a matching subnet
for vnet_match in (v for v in vnet_list if bool(v['location'] == location and v['subnets'])):
# 1 - find a suitable existing vnet/subnet
result = None
if not for_scale_set:
result = next((s for s in vnet_match['subnets'] if s['name'].lower() != 'gatewaysubnet'), None)
else:
def _check_subnet(s):
if s['name'].lower() == 'gatewaysubnet':
return False
subnet_mask = s['addressPrefix'].split('/')[-1]
return _subnet_capacity_check(subnet_mask, namespace.instance_count,
not namespace.disable_overprovision)
result = next((s for s in vnet_match['subnets'] if _check_subnet(s)), None)
if not result:
continue
namespace.subnet = result['name']
namespace.vnet_name = vnet_match['name']
namespace.vnet_type = 'existing'
logger.debug("existing vnet '%s' and subnet '%s' found", namespace.vnet_name, namespace.subnet)
return
if subnet:
subnet_is_id = is_valid_resource_id(subnet)
if (subnet_is_id and vnet) or (not subnet_is_id and not vnet):
raise CLIError("incorrect usage: --subnet ID | --subnet NAME --vnet-name NAME")
subnet_exists = \
check_existence(cmd.cli_ctx, subnet, rg, 'Microsoft.Network', 'subnets', vnet, 'virtualNetworks',
static_version="2024-07-01")
if subnet_is_id and not subnet_exists:
raise CLIError("Subnet '{}' does not exist.".format(subnet))
if subnet_exists:
# 2 - user specified existing vnet/subnet
namespace.vnet_type = 'existing'
logger.debug("using specified vnet '%s' and subnet '%s'", namespace.vnet_name, namespace.subnet)
return
# 3 - create a new vnet/subnet
namespace.vnet_type = 'new'
logger.debug('no suitable subnet found. One will be created.')
def _subnet_capacity_check(subnet_mask, vmss_instance_count, over_provision):
mask = int(subnet_mask)
# '2' are the reserved broadcasting addresses
# '*1.5' so we have enough leeway for over-provision
factor = 1.5 if over_provision else 1
return ((1 << (32 - mask)) - 2) > int(vmss_instance_count * factor)
def _validate_vm_vmss_accelerated_networking(cli_ctx, namespace):
if namespace.accelerated_networking is None:
size = getattr(namespace, 'size', None) or getattr(namespace, 'vm_sku', None)
size = size.lower()
# Use the following code to refresh the list
# skus = list_sku_info(cli_ctx, namespace.location)
# aval_sizes = [x.name.lower() for x in skus if x.resource_type == 'virtualMachines' and
# any(c.name == 'AcceleratedNetworkingEnabled' and c.value == 'True' for c in x.capabilities)]
aval_sizes = ['standard_b12ms', 'standard_b16ms', 'standard_b20ms', 'standard_ds2_v2', 'standard_ds3_v2',
'standard_ds4_v2', 'standard_ds5_v2', 'standard_ds11-1_v2', 'standard_ds11_v2',
'standard_ds12-1_v2', 'standard_ds12-2_v2', 'standard_ds12_v2', 'standard_ds13-2_v2',
'standard_ds13-4_v2', 'standard_ds13_v2', 'standard_ds14-4_v2', 'standard_ds14-8_v2',
'standard_ds14_v2', 'standard_ds15_v2', 'standard_ds2_v2_promo', 'standard_ds3_v2_promo',
'standard_ds4_v2_promo', 'standard_ds5_v2_promo', 'standard_ds11_v2_promo',
'standard_ds12_v2_promo', 'standard_ds13_v2_promo', 'standard_ds14_v2_promo', 'standard_f2s',
'standard_f4s', 'standard_f8s', 'standard_f16s', 'standard_d4s_v3', 'standard_d8s_v3',
'standard_d16s_v3', 'standard_d32s_v3', 'standard_d2_v2', 'standard_d3_v2', 'standard_d4_v2',
'standard_d5_v2', 'standard_d11_v2', 'standard_d12_v2', 'standard_d13_v2', 'standard_d14_v2',
'standard_d15_v2', 'standard_d2_v2_promo', 'standard_d3_v2_promo', 'standard_d4_v2_promo',
'standard_d5_v2_promo', 'standard_d11_v2_promo', 'standard_d12_v2_promo', 'standard_d13_v2_promo',
'standard_d14_v2_promo', 'standard_f2', 'standard_f4', 'standard_f8', 'standard_f16',
'standard_d4_v3', 'standard_d8_v3', 'standard_d16_v3', 'standard_d32_v3', 'standard_d48_v3',
'standard_d64_v3', 'standard_d48s_v3', 'standard_d64s_v3', 'standard_e4_v3', 'standard_e8_v3',
'standard_e16_v3', 'standard_e20_v3', 'standard_e32_v3', 'standard_e48_v3', 'standard_e64i_v3',
'standard_e64_v3', 'standard_e4-2s_v3', 'standard_e4s_v3', 'standard_e8-2s_v3',
'standard_e8-4s_v3', 'standard_e8s_v3', 'standard_e16-4s_v3', 'standard_e16-8s_v3',
'standard_e16s_v3', 'standard_e20s_v3', 'standard_e32-8s_v3', 'standard_e32-16s_v3',
'standard_e32s_v3', 'standard_e48s_v3', 'standard_e64-16s_v3', 'standard_e64-32s_v3',
'standard_e64is_v3', 'standard_e64s_v3', 'standard_l8s_v2', 'standard_l16s_v2',
'standard_l32s_v2', 'standard_l48s_v2', 'standard_l64s_v2', 'standard_l80s_v2', 'standard_e4_v4',
'standard_e8_v4', 'standard_e16_v4', 'standard_e20_v4', 'standard_e32_v4', 'standard_e48_v4',
'standard_e64_v4', 'standard_e4d_v4', 'standard_e8d_v4', 'standard_e16d_v4', 'standard_e20d_v4',
'standard_e32d_v4', 'standard_e48d_v4', 'standard_e64d_v4', 'standard_e4-2s_v4',
'standard_e4s_v4', 'standard_e8-2s_v4', 'standard_e8-4s_v4', 'standard_e8s_v4',
'standard_e16-4s_v4', 'standard_e16-8s_v4', 'standard_e16s_v4', 'standard_e20s_v4',
'standard_e32-8s_v4', 'standard_e32-16s_v4', 'standard_e32s_v4', 'standard_e48s_v4',
'standard_e64-16s_v4', 'standard_e64-32s_v4', 'standard_e64s_v4', 'standard_e4-2ds_v4',
'standard_e4ds_v4', 'standard_e8-2ds_v4', 'standard_e8-4ds_v4', 'standard_e8ds_v4',
'standard_e16-4ds_v4', 'standard_e16-8ds_v4', 'standard_e16ds_v4', 'standard_e20ds_v4',
'standard_e32-8ds_v4', 'standard_e32-16ds_v4', 'standard_e32ds_v4', 'standard_e48ds_v4',
'standard_e64-16ds_v4', 'standard_e64-32ds_v4', 'standard_e64ds_v4', 'standard_d4d_v4',
'standard_d8d_v4', 'standard_d16d_v4', 'standard_d32d_v4', 'standard_d48d_v4', 'standard_d64d_v4',
'standard_d4_v4', 'standard_d8_v4', 'standard_d16_v4', 'standard_d32_v4', 'standard_d48_v4',
'standard_d64_v4', 'standard_d4ds_v4', 'standard_d8ds_v4', 'standard_d16ds_v4',
'standard_d32ds_v4', 'standard_d48ds_v4', 'standard_d64ds_v4', 'standard_d4s_v4',
'standard_d8s_v4', 'standard_d16s_v4', 'standard_d32s_v4', 'standard_d48s_v4', 'standard_d64s_v4',
'standard_f4s_v2', 'standard_f8s_v2', 'standard_f16s_v2', 'standard_f32s_v2', 'standard_f48s_v2',
'standard_f64s_v2', 'standard_f72s_v2', 'standard_m208ms_v2', 'standard_m208s_v2',
'standard_m416-208s_v2', 'standard_m416s_v2', 'standard_m416-208ms_v2', 'standard_m416ms_v2',
'standard_m64', 'standard_m64m', 'standard_m128', 'standard_m128m', 'standard_m8-2ms',
'standard_m8-4ms', 'standard_m8ms', 'standard_m16-4ms', 'standard_m16-8ms', 'standard_m16ms',
'standard_m32-8ms', 'standard_m32-16ms', 'standard_m32ls', 'standard_m32ms', 'standard_m32ts',
'standard_m64-16ms', 'standard_m64-32ms', 'standard_m64ls', 'standard_m64ms', 'standard_m64s',
'standard_m128-32ms', 'standard_m128-64ms', 'standard_m128ms', 'standard_m128s',
'standard_d4a_v4', 'standard_d8a_v4', 'standard_d16a_v4', 'standard_d32a_v4', 'standard_d48a_v4',
'standard_d64a_v4', 'standard_d96a_v4', 'standard_d4as_v4', 'standard_d8as_v4',
'standard_d16as_v4', 'standard_d32as_v4', 'standard_d48as_v4', 'standard_d64as_v4',
'standard_d96as_v4', 'standard_e4a_v4', 'standard_e8a_v4', 'standard_e16a_v4', 'standard_e20a_v4',
'standard_e32a_v4', 'standard_e48a_v4', 'standard_e64a_v4', 'standard_e96a_v4',
'standard_e4as_v4', 'standard_e8as_v4', 'standard_e16as_v4', 'standard_e20as_v4',
'standard_e32as_v4', 'standard_e48as_v4', 'standard_e64as_v4', 'standard_e96as_v4']
if size not in aval_sizes:
return
new_4core_sizes = ['Standard_D3_v2', 'Standard_D3_v2_Promo', 'Standard_D3_v2_ABC', 'Standard_DS3_v2',
'Standard_DS3_v2_Promo', 'Standard_D12_v2', 'Standard_D12_v2_Promo', 'Standard_D12_v2_ABC',
'Standard_DS12_v2', 'Standard_DS12_v2_Promo', 'Standard_F8s_v2', 'Standard_F4',
'Standard_F4_ABC', 'Standard_F4s', 'Standard_E8_v3', 'Standard_E8s_v3', 'Standard_D8_v3',
'Standard_D8s_v3']
new_4core_sizes = [x.lower() for x in new_4core_sizes]
if size not in new_4core_sizes:
from .aaz.latest.vm import ListSizes
sizes = ListSizes(cli_ctx=cli_ctx)(command_args={
'location': namespace.location
})
size_info = next((s for s in sizes if s.get('name', '').lower() == size), None)
if size_info is None or size_info.get('numberOfCores') < 8:
return
# VMs need to be a supported image in the marketplace
# Ubuntu 16.04 | 18.04, SLES 12 SP3, RHEL 7.4, CentOS 7.4, Flatcar, Debian "Stretch" with backports kernel
# Oracle Linux 7.4, Windows Server 2016, Windows Server 2012R2
publisher, offer, sku = namespace.os_publisher, namespace.os_offer, namespace.os_sku
if not publisher:
return
publisher, offer, sku = publisher.lower(), offer.lower(), sku.lower()
if publisher == 'coreos' or offer == 'coreos':
from azure.cli.core.parser import InvalidArgumentValueError
raise InvalidArgumentValueError("As CoreOS is deprecated and there is no image in the marketplace any more,"
" please use Flatcar Container Linux instead.")
distros = [('canonical', 'UbuntuServer', '^16.04|^18.04'),
('suse', 'sles', '^12-sp3'), ('redhat', 'rhel', '^7.4'),
('openlogic', 'centos', '^7.4'), ('kinvolk', 'flatcar-container-linux-free', None),
('kinvolk', 'flatcar-container-linux', None), ('credativ', 'debian', '-backports'),
('oracle', 'oracle-linux', '^7.4'), ('MicrosoftWindowsServer', 'WindowsServer', '^2016'),
('MicrosoftWindowsServer', 'WindowsServer', '^2012-R2')]
import re
for p, o, s in distros:
if p.lower() == publisher and (o is None or o.lower() == offer) and (s is None or re.match(s, sku, re.I)):
namespace.accelerated_networking = True
def _validate_vmss_create_subnet(namespace):
if namespace.vnet_type == 'new':
if namespace.subnet_address_prefix is None:
cidr = namespace.vnet_address_prefix.split('/', 1)[0]
i = 0
for i in range(24, 16, -1):
if _subnet_capacity_check(i, namespace.instance_count, not namespace.disable_overprovision):
break
if i < 16:
err = "instance count '{}' is out of range of 2^16 subnet size'"
raise CLIError(err.format(namespace.instance_count))
namespace.subnet_address_prefix = '{}/{}'.format(cidr, i)