-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathcustom.py
More file actions
5982 lines (5120 loc) · 297 KB
/
Copy pathcustom.py
File metadata and controls
5982 lines (5120 loc) · 297 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.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
#
# Generation mode: Incremental
# --------------------------------------------------------------------------
# pylint: disable=no-self-use, too-many-lines, no-else-return
# pylint: disable=protected-access
import json
import os
import requests
# the urlopen is imported for automation purpose
from urllib.request import urlopen # noqa, pylint: disable=import-error,unused-import,ungrouped-imports
from knack.log import get_logger
from knack.util import CLIError
from azure.cli.core.azclierror import (
CLIInternalError,
ResourceNotFoundError,
ValidationError,
RequiredArgumentMissingError,
ArgumentUsageError
)
from azure.cli.command_modules.vm._validators import _get_resource_group_from_vault_name
from azure.cli.core.commands.validators import validate_file_or_dict
from azure.cli.core.commands import LongRunningOperation, DeploymentOutputLongRunningOperation
from azure.cli.core.commands.client_factory import get_mgmt_service_client
from azure.cli.core.profiles import ResourceType
from azure.cli.core.util import sdk_no_wait
from ._vm_utils import read_content_if_is_file, import_aaz_by_profile
from ._vm_diagnostics_templates import get_default_diag_config
from ._actions import (load_images_from_aliases_doc, load_extension_images_thru_services,
load_images_thru_services, _get_latest_image_version)
from ._client_factory import (_compute_client_factory, cf_vm_image_term)
from .aaz.latest.vm.disk import AttachDetachDataDisk
from .aaz.latest.vm import Update as UpdateVM
from .generated.custom import * # noqa: F403, pylint: disable=unused-wildcard-import,wildcard-import
try:
from .manual.custom import * # noqa: F403, pylint: disable=unused-wildcard-import,wildcard-import
except ImportError:
pass
logger = get_logger(__name__)
# Use the same name by portal, so people can update from both cli and portal
# (VM doesn't allow multiple handlers for the same extension)
_ACCESS_EXT_HANDLER_NAME = 'enablevmaccess'
_LINUX_ACCESS_EXT = 'VMAccessForLinux'
_WINDOWS_ACCESS_EXT = 'VMAccessAgent'
_LINUX_DIAG_EXT = 'LinuxDiagnostic'
_WINDOWS_DIAG_EXT = 'IaaSDiagnostics'
_LINUX_OMS_AGENT_EXT = 'OmsAgentForLinux'
_WINDOWS_OMS_AGENT_EXT = 'MicrosoftMonitoringAgent'
extension_mappings = {
_LINUX_ACCESS_EXT: {
'version': '1.5',
'publisher': 'Microsoft.OSTCExtensions'
},
_WINDOWS_ACCESS_EXT: {
'version': '2.4',
'publisher': 'Microsoft.Compute'
},
_LINUX_DIAG_EXT: {
'version': '3.0',
'publisher': 'Microsoft.Azure.Diagnostics'
},
_WINDOWS_DIAG_EXT: {
'version': '1.5',
'publisher': 'Microsoft.Azure.Diagnostics'
},
_LINUX_OMS_AGENT_EXT: {
'version': '1.0',
'publisher': 'Microsoft.EnterpriseCloud.Monitoring'
},
_WINDOWS_OMS_AGENT_EXT: {
'version': '1.0',
'publisher': 'Microsoft.EnterpriseCloud.Monitoring'
}
}
remove_basic_option_msg = "It's recommended to create with `%s`. " \
"Please be aware that Basic option will be removed in the future."
def _construct_identity_info(identity_scope, identity_role, implicit_identity, external_identities):
info = {}
if identity_scope:
info['scope'] = identity_scope
info['role'] = str(identity_role) # could be DefaultStr, so convert to string
info['userAssignedIdentities'] = external_identities or {}
info['systemAssignedIdentity'] = implicit_identity or ''
return info
# for injecting test seams to produce predicatable role assignment id for playback
def _gen_guid():
import uuid
return uuid.uuid4()
def _get_access_extension_upgrade_info(extensions, name):
version = extension_mappings[name]['version']
publisher = extension_mappings[name]['publisher']
auto_upgrade = None
if extensions:
extension = next((e for e in extensions if e.name == name), None)
from packaging.version import parse # pylint: disable=no-name-in-module,import-error
if extension and parse(extension.type_handler_version) < parse(version):
auto_upgrade = True
elif extension and parse(extension.type_handler_version) > parse(version):
version = extension.type_handler_version
return publisher, version, auto_upgrade
def _get_extension_instance_name(instance_view, publisher, extension_type_name,
suggested_name=None):
extension_instance_name = suggested_name or extension_type_name
full_type_name = '.'.join([publisher, extension_type_name])
if instance_view.extensions:
ext = next((x for x in instance_view.extensions
if x.type and (x.type.lower() == full_type_name.lower())), None)
if ext:
extension_instance_name = ext.name
return extension_instance_name
# separated for aaz based implementation
def _get_extension_instance_name_aaz(instance_view, publisher, extension_type_name,
suggested_name=None):
extension_instance_name = suggested_name or extension_type_name
full_type_name = '.'.join([publisher, extension_type_name])
if extensions := instance_view.get('extensions', []):
ext = next((x for x in extensions if x.get('type', '').lower() == full_type_name.lower()), None)
if ext:
extension_instance_name = ext['name']
return extension_instance_name
def _get_storage_management_client(cli_ctx):
return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_STORAGE)
def _get_disk_lun(data_disks):
# start from 0, search for unused int for lun
if not data_disks:
return 0
existing_luns = sorted([d.lun for d in data_disks])
for i, current in enumerate(existing_luns):
if current != i:
return i
return len(existing_luns)
def _get_private_config(cli_ctx, resource_group_name, storage_account):
storage_mgmt_client = _get_storage_management_client(cli_ctx)
# pylint: disable=no-member
keys = storage_mgmt_client.storage_accounts.list_keys(resource_group_name, storage_account).keys
private_config = {
'storageAccountName': storage_account,
'storageAccountKey': keys[0].value
}
return private_config
def _get_resource_group_location(cli_ctx, resource_group_name):
client = get_mgmt_service_client(cli_ctx, ResourceType.MGMT_RESOURCE_RESOURCES)
# pylint: disable=no-member
return client.resource_groups.get(resource_group_name).location
def _get_sku_object(cmd, sku):
if cmd.supported_api_version(min_api='2017-03-30'):
DiskSku = cmd.get_models('DiskSku')
return DiskSku(name=sku)
return sku
def get_hyper_v_generation_from_vmss(cli_ctx, image_ref, location): # pylint: disable=too-many-return-statements
from ._vm_utils import (is_valid_image_version_id, parse_gallery_image_id, is_valid_vm_image_id, parse_vm_image_id,
parse_shared_gallery_image_id, parse_community_gallery_image_id)
if image_ref is None:
return None
if image_ref.id:
from ._client_factory import _compute_client_factory
if is_valid_image_version_id(image_ref.id):
image_info = parse_gallery_image_id(image_ref.id)
client = _compute_client_factory(cli_ctx, subscription_id=image_info[0]).gallery_images
gallery_image_info = client.get(
resource_group_name=image_info[1], gallery_name=image_info[2], gallery_image_name=image_info[3])
return gallery_image_info.hyper_v_generation if hasattr(gallery_image_info, 'hyper_v_generation') else None
if is_valid_vm_image_id(image_ref.id):
sub, rg, image_name = parse_vm_image_id(image_ref.id)
client = _compute_client_factory(cli_ctx, subscription_id=sub).images
image_info = client.get(rg, image_name)
return image_info.hyper_v_generation if hasattr(image_info, 'hyper_v_generation') else None
if image_ref.shared_gallery_image_id is not None:
from ._client_factory import cf_shared_gallery_image
image_info = parse_shared_gallery_image_id(image_ref.shared_gallery_image_id)
gallery_image_info = cf_shared_gallery_image(cli_ctx).get(
location=location, gallery_unique_name=image_info[0], gallery_image_name=image_info[1])
return gallery_image_info.hyper_v_generation if hasattr(gallery_image_info, 'hyper_v_generation') else None
if image_ref.community_gallery_image_id is not None:
from ._client_factory import cf_community_gallery_image
image_info = parse_community_gallery_image_id(image_ref.community_gallery_image_id)
gallery_image_info = cf_community_gallery_image(cli_ctx).get(
location=location, public_gallery_name=image_info[0], gallery_image_name=image_info[1])
return gallery_image_info.hyper_v_generation if hasattr(gallery_image_info, 'hyper_v_generation') else None
if image_ref.offer and image_ref.publisher and image_ref.sku and image_ref.version:
from ._client_factory import cf_vm_image
version = image_ref.version
if version.lower() == 'latest':
from ._actions import _get_latest_image_version
version = _get_latest_image_version(cli_ctx, location, image_ref.publisher, image_ref.offer,
image_ref.sku)
vm_image_info = cf_vm_image(cli_ctx, '').get(
location, image_ref.publisher, image_ref.offer, image_ref.sku, version)
return vm_image_info.hyper_v_generation if hasattr(vm_image_info, 'hyper_v_generation') else None
return None
def _is_linux_os(vm):
os_type = None
if vm and vm.storage_profile and vm.storage_profile.os_disk and vm.storage_profile.os_disk.os_type:
os_type = vm.storage_profile.os_disk.os_type
if os_type:
return os_type.lower() == 'linux'
# the os_type could be None for VM scaleset, let us check out os configurations
if vm.os_profile.linux_configuration:
return bool(vm.os_profile.linux_configuration)
return False
# separated for aaz implementation
def _is_linux_os_aaz(vm):
if os_type := vm.get('storageProfile', {}).get('osDisk', {}).get('osType', None):
return os_type.lower() == 'linux'
# the os_type could be None for VM scaleset, let us check out os configurations
if linux_config := vm.get('osProfile', {}).get('linuxConfiguration', ''):
return bool(linux_config)
return False
def _merge_secrets(secrets):
"""
Merge a list of secrets. Each secret should be a dict fitting the following JSON structure:
[{ "sourceVault": { "id": "value" },
"vaultCertificates": [{ "certificateUrl": "value",
"certificateStore": "cert store name (only on windows)"}] }]
The array of secrets is merged on sourceVault.id.
:param secrets:
:return:
"""
merged = {}
vc_name = 'vaultCertificates'
for outer in secrets:
for secret in outer:
if secret['sourceVault']['id'] not in merged:
merged[secret['sourceVault']['id']] = []
merged[secret['sourceVault']['id']] = \
secret[vc_name] + merged[secret['sourceVault']['id']]
# transform the reduced map to vm format
formatted = [{'sourceVault': {'id': source_id},
'vaultCertificates': value}
for source_id, value in list(merged.items())]
return formatted
def _normalize_extension_version(cli_ctx, publisher, vm_extension_name, version, location):
def _trim_away_build_number(version):
# workaround a known issue: the version must only contain "major.minor", even though
# "extension image list" gives more detail
return '.'.join(version.split('.')[0:2])
if not version:
result = load_extension_images_thru_services(cli_ctx, publisher, vm_extension_name, None, location,
show_latest=True, partial_match=False)
if not result:
raise CLIError('Failed to find the latest version for the extension "{}"'.format(vm_extension_name))
# with 'show_latest' enabled, we will only get one result.
version = result[0]['version']
version = _trim_away_build_number(version)
return version
def _parse_rg_name(strid):
'''From an ID, extract the contained (resource group, name) tuple.'''
from azure.mgmt.core.tools import parse_resource_id
parts = parse_resource_id(strid)
return (parts['resource_group'], parts['name'])
def _set_sku(cmd, instance, sku):
if cmd.supported_api_version(min_api='2017-03-30'):
instance.sku = cmd.get_models('DiskSku')(name=sku)
else:
instance.account_type = sku
def _show_missing_access_warning(resource_group, name, command):
warn = ("No access was given yet to the '{1}', because '--scope' was not provided. "
"You should setup by creating a role assignment, e.g. "
"'az role assignment create --assignee <principal-id> --role contributor -g {0}' "
"would let it access the current resource group. To get the pricipal id, run "
"'az {2} show -g {0} -n {1} --query \"identity.principalId\" -otsv'".format(resource_group, name, command))
logger.warning(warn)
def _parse_aux_subscriptions(resource_id):
from azure.mgmt.core.tools import is_valid_resource_id, parse_resource_id
if is_valid_resource_id(resource_id):
res = parse_resource_id(resource_id)
return [res['subscription']]
return None
# Hide extension information from output as the info is not correct and unhelpful; also
# commands using it mean to hide the extension concept from users.
class ExtensionUpdateLongRunningOperation(LongRunningOperation): # pylint: disable=too-few-public-methods
pass
# region Disks (Managed)
def create_managed_disk(cmd, resource_group_name, disk_name, location=None, # pylint: disable=too-many-locals, too-many-branches, too-many-statements, line-too-long
size_gb=None, sku='Premium_LRS', os_type=None,
source=None, for_upload=None, upload_size_bytes=None, # pylint: disable=unused-argument
# below are generated internally from 'source'
source_blob_uri=None, source_disk=None, source_snapshot=None, source_restore_point=None,
source_storage_account_id=None, no_wait=False, tags=None, zone=None,
disk_iops_read_write=None, disk_mbps_read_write=None, hyper_v_generation=None,
encryption_type=None, disk_encryption_set=None, max_shares=None,
disk_iops_read_only=None, disk_mbps_read_only=None,
image_reference=None, image_reference_lun=None,
gallery_image_reference=None, gallery_image_reference_lun=None,
network_access_policy=None, disk_access=None, logical_sector_size=None,
tier=None, enable_bursting=None, edge_zone=None, security_type=None, support_hibernation=None,
public_network_access=None, accelerated_network=None, architecture=None,
data_access_auth_mode=None, gallery_image_reference_type=None, security_data_uri=None,
upload_type=None, secure_vm_disk_encryption_set=None, performance_plus=None,
optimized_for_frequent_attach=None, security_metadata_uri=None):
from azure.mgmt.core.tools import resource_id, is_valid_resource_id
from azure.cli.core.commands.client_factory import get_subscription_id
location = location or _get_resource_group_location(cmd.cli_ctx, resource_group_name)
if security_data_uri:
option = 'ImportSecure'
elif source_blob_uri:
option = 'Import'
elif source_disk or source_snapshot:
option = 'Copy'
elif source_restore_point:
option = 'Restore'
elif upload_type == 'Upload':
option = 'Upload'
elif upload_type == 'UploadWithSecurityData':
option = 'UploadPreparedSecure'
elif image_reference or gallery_image_reference:
option = 'FromImage'
else:
option = 'Empty'
if source_storage_account_id is None and source_blob_uri is not None:
subscription_id = get_subscription_id(cmd.cli_ctx)
storage_account_name = source_blob_uri.split('.')[0].split('/')[-1]
source_storage_account_id = resource_id(
subscription=subscription_id, resource_group=resource_group_name,
namespace='Microsoft.Storage', type='storageAccounts', name=storage_account_name)
if upload_size_bytes is not None and not upload_type:
raise RequiredArgumentMissingError(
'usage error: --upload-size-bytes should be used together with --upload-type')
from ._constants import COMPATIBLE_SECURITY_TYPE_VALUE, UPGRADE_SECURITY_HINT
if image_reference is not None:
if not is_valid_resource_id(image_reference):
# URN or name
terms = image_reference.split(':')
if len(terms) == 4: # URN
disk_publisher, disk_offer, disk_sku, disk_version = terms[0], terms[1], terms[2], terms[3]
if disk_version.lower() == 'latest':
disk_version = _get_latest_image_version(cmd.cli_ctx, location, disk_publisher, disk_offer,
disk_sku)
else: # error
raise CLIError('usage error: --image-reference should be ID or URN (publisher:offer:sku:version).')
else:
from azure.mgmt.core.tools import parse_resource_id
terms = parse_resource_id(image_reference)
disk_publisher, disk_offer, disk_sku, disk_version = \
terms['child_name_1'], terms['child_name_3'], terms['child_name_4'], terms['child_name_5']
client = _compute_client_factory(cmd.cli_ctx)
response = client.virtual_machine_images.get(location=location, publisher_name=disk_publisher,
offer=disk_offer, skus=disk_sku, version=disk_version)
if hasattr(response, 'hyper_v_generation'):
if response.hyper_v_generation == 'V1':
logger.warning(UPGRADE_SECURITY_HINT)
elif response.hyper_v_generation == 'V2':
# set default value of hyper_v_generation
if hyper_v_generation == 'V1':
hyper_v_generation = 'V2'
# set default value of security_type
if not security_type:
security_type = 'TrustedLaunch'
if security_type != 'TrustedLaunch':
logger.warning(UPGRADE_SECURITY_HINT)
# image_reference is an ID now
image_reference = {'id': response.id}
if image_reference_lun is not None:
image_reference['lun'] = image_reference_lun
if gallery_image_reference is not None:
if not security_type:
security_type = 'Standard'
if security_type != 'TrustedLaunch':
logger.warning(UPGRADE_SECURITY_HINT)
key = gallery_image_reference_type if gallery_image_reference_type else 'id'
gallery_image_reference = {key: gallery_image_reference}
if gallery_image_reference_lun is not None:
gallery_image_reference['lun'] = gallery_image_reference_lun
creation_data = {
"create_option": option,
"source_uri": source_blob_uri,
"image_reference": image_reference,
"gallery_image_reference": gallery_image_reference,
"source_resource_id": source_disk or source_snapshot or source_restore_point,
"storage_account_id": source_storage_account_id,
"upload_size_bytes": upload_size_bytes,
"logical_sector_size": logical_sector_size,
"security_data_uri": security_data_uri,
"performance_plus": performance_plus,
"security_metadata_uri": security_metadata_uri,
}
if size_gb is None and option == "Empty":
raise RequiredArgumentMissingError(
'usage error: --size-gb is required to create an empty disk')
if upload_size_bytes is None and upload_type:
raise RequiredArgumentMissingError(
'usage error: --upload-size-bytes is required to create a disk for upload')
if disk_encryption_set is not None and not is_valid_resource_id(disk_encryption_set):
disk_encryption_set = resource_id(
subscription=get_subscription_id(cmd.cli_ctx), resource_group=resource_group_name,
namespace='Microsoft.Compute', type='diskEncryptionSets', name=disk_encryption_set)
if disk_access is not None and not is_valid_resource_id(disk_access):
disk_access = resource_id(
subscription=get_subscription_id(cmd.cli_ctx), resource_group=resource_group_name,
namespace='Microsoft.Compute', type='diskAccesses', name=disk_access)
if secure_vm_disk_encryption_set is not None and not is_valid_resource_id(secure_vm_disk_encryption_set):
secure_vm_disk_encryption_set = resource_id(
subscription=get_subscription_id(cmd.cli_ctx), resource_group=resource_group_name,
namespace='Microsoft.Compute', type='diskEncryptionSets', name=secure_vm_disk_encryption_set)
encryption = None
if disk_encryption_set or encryption_type:
encryption = {
"type": encryption_type,
"disk_encryption_set_id": disk_encryption_set
}
sku = {"name": sku}
args = {
"location": location,
"creation_data": creation_data,
"tags": tags or {},
"sku": sku,
"disk_size_gb": size_gb,
"os_type": os_type,
"encryption": encryption
}
if hyper_v_generation:
args["hyper_v_generation"] = hyper_v_generation
if zone:
args["zones"] = zone
if disk_iops_read_write is not None:
args["disk_iops_read_write"] = disk_iops_read_write
if disk_mbps_read_write is not None:
args["disk_m_bps_read_write"] = disk_mbps_read_write
if max_shares is not None:
args["max_shares"] = max_shares
if disk_iops_read_only is not None:
args["disk_iops_read_only"] = disk_iops_read_only
if disk_mbps_read_only is not None:
args["disk_m_bps_read_only"] = disk_mbps_read_only
if network_access_policy is not None:
args["network_access_policy"] = network_access_policy
if disk_access is not None:
args["disk_access_id"] = disk_access
if tier is not None:
args["tier"] = tier
if enable_bursting is not None:
args["bursting_enabled"] = enable_bursting
if edge_zone is not None:
args["extended_location"] = edge_zone
# 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 and security_type != COMPATIBLE_SECURITY_TYPE_VALUE:
args["security_profile"] = {'securityType': security_type}
if secure_vm_disk_encryption_set:
args["security_profile"]["secure_vm_disk_encryption_set_id"] = secure_vm_disk_encryption_set
if support_hibernation is not None:
args["supports_hibernation"] = support_hibernation
if public_network_access is not None:
args["public_network_access"] = public_network_access
if accelerated_network is not None or architecture is not None:
if args.get("supported_capabilities", None) is None:
supported_capabilities = {
"accelerated_network": accelerated_network,
"architecture": architecture
}
args["supported_capabilities"] = supported_capabilities
else:
args["supported_capabilities"]["accelerated_network"] = accelerated_network
args["supported_capabilities"]["architecture"] = architecture
if data_access_auth_mode is not None:
args["data_access_auth_mode"] = data_access_auth_mode
if optimized_for_frequent_attach is not None:
args["optimized_for_frequent_attach"] = optimized_for_frequent_attach
args["no_wait"] = no_wait
args["disk_name"] = disk_name
args["resource_group"] = resource_group_name
from .aaz.latest.disk import Create
return Create(cli_ctx=cmd.cli_ctx)(command_args=args)
# region Images (Managed)
def create_image(cmd, resource_group_name, name, source, os_type=None, data_disk_sources=None, location=None, # pylint: disable=too-many-locals,unused-argument
# below are generated internally from 'source' and 'data_disk_sources'
source_virtual_machine=None, storage_sku=None, hyper_v_generation=None,
os_blob_uri=None, data_blob_uris=None,
os_snapshot=None, data_snapshots=None,
os_disk=None, os_disk_caching=None, data_disks=None, data_disk_caching=None,
tags=None, zone_resilient=None, edge_zone=None):
if source_virtual_machine:
location = location or _get_resource_group_location(cmd.cli_ctx, resource_group_name)
image_storage_profile = None if zone_resilient is None else {"zone_resilient": zone_resilient}
args = {
"location": location,
"source_virtual_machine": {"id": source_virtual_machine},
"storage_profile": image_storage_profile,
"tags": tags or {}
}
else:
os_disk = {
"os_type": os_type,
"os_state": "Generalized",
"caching": os_disk_caching,
"snapshot": {"id": os_snapshot} if os_snapshot else None,
"managed_disk": {"id": os_disk} if os_disk else None,
"blob_uri": os_blob_uri,
"storage_account_type": storage_sku
}
all_data_disks = []
lun = 0
if data_blob_uris:
for d in data_blob_uris:
all_data_disks.append({
"lun": lun,
"blob_uri": d,
"caching": data_disk_caching
})
lun += 1
if data_snapshots:
for d in data_snapshots:
all_data_disks.append({
"lun": lun,
"snapshot": {"id": d},
"caching": data_disk_caching
})
lun += 1
if data_disks:
for d in data_disks:
all_data_disks.append({
"lun": lun,
"managed_disk": {"id": d},
"caching": data_disk_caching
})
lun += 1
image_storage_profile = {
"os_disk": os_disk,
"data_disks": all_data_disks
}
if zone_resilient is not None:
image_storage_profile["zone_resilient"] = zone_resilient
location = location or _get_resource_group_location(cmd.cli_ctx, resource_group_name)
# pylint disable=no-member
args = {
"location": location,
"storage_profile": image_storage_profile,
"tags": tags or {}
}
if hyper_v_generation:
args["hyper_v_generation"] = hyper_v_generation
if edge_zone:
args["extended_location"] = edge_zone
args["image_name"] = name
args["resource_group"] = resource_group_name
from .aaz.latest.image import Create
return Create(cli_ctx=cmd.cli_ctx)(command_args=args)
# region Snapshots
# pylint: disable=unused-argument,too-many-locals
def create_snapshot(cmd, resource_group_name, snapshot_name, location=None, size_gb=None, sku='Standard_LRS',
source=None, for_upload=None, copy_start=None, incremental=None,
# below are generated internally from 'source'
source_blob_uri=None, source_disk=None, source_snapshot=None, source_storage_account_id=None,
hyper_v_generation=None, tags=None, no_wait=False, disk_encryption_set=None,
encryption_type=None, network_access_policy=None, disk_access=None, edge_zone=None,
public_network_access=None, accelerated_network=None, architecture=None,
elastic_san_resource_id=None, bandwidth_copy_speed=None, instant_access_duration_minutes=None):
from azure.mgmt.core.tools import resource_id, is_valid_resource_id
from azure.cli.core.commands.client_factory import get_subscription_id
location = location or _get_resource_group_location(cmd.cli_ctx, resource_group_name)
if source_blob_uri:
option = 'Import'
elif source_disk or source_snapshot:
option = 'CopyStart' if copy_start else 'Copy'
elif for_upload:
option = 'Upload'
elif elastic_san_resource_id:
option = 'CopyFromSanSnapshot'
else:
option = 'Empty'
creation_data = {
'create_option': option,
'source_uri': source_blob_uri,
'image_reference': None,
'source_resource_id': source_disk or source_snapshot,
'storage_account_id': source_storage_account_id,
'elastic_san_resource_id': elastic_san_resource_id,
'provisioned_bandwidth_copy_speed': bandwidth_copy_speed,
'instant_access_duration_minutes': instant_access_duration_minutes
}
if size_gb is None and option == 'Empty':
raise CLIError('Please supply size for the snapshots')
if disk_encryption_set is not None and not is_valid_resource_id(disk_encryption_set):
disk_encryption_set = resource_id(
subscription=get_subscription_id(cmd.cli_ctx), resource_group=resource_group_name,
namespace='Microsoft.Compute', type='diskEncryptionSets', name=disk_encryption_set)
if disk_access is not None and not is_valid_resource_id(disk_access):
disk_access = resource_id(
subscription=get_subscription_id(cmd.cli_ctx), resource_group=resource_group_name,
namespace='Microsoft.Compute', type='diskAccesses', name=disk_access)
if disk_encryption_set is not None and encryption_type is None:
raise CLIError('usage error: Please specify --encryption-type.')
if encryption_type is not None:
encryption = {
'type': encryption_type,
'disk_encryption_set_id': disk_encryption_set
}
else:
encryption = None
args = {
'location': location,
'creation_data': creation_data,
'tags': tags or {},
'sku': {'name': sku},
'disk_size_gb': size_gb,
'incremental': incremental,
'encryption': encryption,
}
if hyper_v_generation:
args['hyper_v_generation'] = hyper_v_generation
if network_access_policy is not None:
args['network_access_policy'] = network_access_policy
if disk_access is not None:
args['disk_access_id'] = disk_access
if edge_zone:
args['extended_location'] = edge_zone
if public_network_access is not None:
args['public_network_access'] = public_network_access
if accelerated_network is not None or architecture is not None:
if args.get('supported_capabilities', None) is None:
supported_capabilities = {
'accelerated_network': accelerated_network,
'architecture': architecture
}
args['supported_capabilities'] = supported_capabilities
else:
args['supported_capabilities']['accelerated_network'] = accelerated_network
args['supported_capabilities']['architecture'] = architecture
args['snapshot_name'] = snapshot_name
args['resource_group'] = resource_group_name
args['no_wait'] = no_wait
from .aaz.latest.snapshot import Create
return Create(cli_ctx=cmd.cli_ctx)(command_args=args)
# region VirtualMachines Identity
def show_vm_identity(cmd, resource_group_name, vm_name):
client = _compute_client_factory(cmd.cli_ctx)
return client.virtual_machines.get(resource_group_name, vm_name).identity
def show_vmss_identity(cmd, resource_group_name, vm_name):
client = _compute_client_factory(cmd.cli_ctx)
return client.virtual_machine_scale_sets.get(resource_group_name, vm_name).identity
def assign_vm_identity(cmd, resource_group_name, vm_name, assign_identity=None, identity_role=None,
identity_role_id=None, identity_scope=None):
VirtualMachineIdentity, ResourceIdentityType, VirtualMachineUpdate = cmd.get_models('VirtualMachineIdentity',
'ResourceIdentityType',
'VirtualMachineUpdate')
UserAssignedIdentitiesValue = cmd.get_models('UserAssignedIdentitiesValue')
from azure.cli.core.commands.arm import assign_identity as assign_identity_helper
client = _compute_client_factory(cmd.cli_ctx)
_, _, external_identities, enable_local_identity = _build_identities_info(assign_identity)
def getter():
return client.virtual_machines.get(resource_group_name, vm_name)
def setter(vm, external_identities=external_identities):
if vm.identity and vm.identity.type == ResourceIdentityType.system_assigned_user_assigned:
identity_types = ResourceIdentityType.system_assigned_user_assigned
elif vm.identity and vm.identity.type == ResourceIdentityType.system_assigned and external_identities:
identity_types = ResourceIdentityType.system_assigned_user_assigned
elif vm.identity and vm.identity.type == ResourceIdentityType.user_assigned and enable_local_identity:
identity_types = ResourceIdentityType.system_assigned_user_assigned
elif external_identities and enable_local_identity:
identity_types = ResourceIdentityType.system_assigned_user_assigned
elif external_identities:
identity_types = ResourceIdentityType.user_assigned
else:
identity_types = ResourceIdentityType.system_assigned
vm.identity = VirtualMachineIdentity(type=identity_types)
if external_identities:
vm.identity.user_assigned_identities = {}
if not cmd.supported_api_version(min_api='2018-06-01', resource_type=ResourceType.MGMT_COMPUTE):
raise CLIInternalError("Usage error: user assigned identity is not available under current profile.",
"You can set the cloud's profile to latest with 'az cloud set --profile latest"
" --name <cloud name>'")
for identity in external_identities:
vm.identity.user_assigned_identities[identity] = UserAssignedIdentitiesValue()
vm_patch = VirtualMachineUpdate()
vm_patch.identity = vm.identity
return patch_vm(cmd, resource_group_name, vm_name, vm_patch)
assign_identity_helper(cmd.cli_ctx, getter, setter, identity_role=identity_role_id, identity_scope=identity_scope)
vm = client.virtual_machines.get(resource_group_name, vm_name)
return _construct_identity_info(identity_scope, identity_role, vm.identity.principal_id,
vm.identity.user_assigned_identities)
# endregion
# region VirtualMachines
def capture_vm(cmd, resource_group_name, vm_name, vhd_name_prefix,
storage_container='vhds', overwrite=True):
VirtualMachineCaptureParameters = cmd.get_models('VirtualMachineCaptureParameters')
client = _compute_client_factory(cmd.cli_ctx)
parameter = VirtualMachineCaptureParameters(vhd_prefix=vhd_name_prefix,
destination_container_name=storage_container,
overwrite_vhds=overwrite)
poller = client.virtual_machines.begin_capture(resource_group_name, vm_name, parameter)
result = LongRunningOperation(cmd.cli_ctx)(poller)
output = getattr(result, 'output', None) or result.resources[0]
print(json.dumps(output, indent=2)) # pylint: disable=no-member
# pylint: disable=too-many-locals, unused-argument, too-many-statements, too-many-branches, broad-except
def create_vm(cmd, vm_name, resource_group_name, image=None, size='Standard_DS1_v2', location=None, tags=None,
no_wait=False, authentication_type=None, admin_password=None, computer_name=None,
admin_username=None, ssh_dest_key_path=None, ssh_key_value=None, generate_ssh_keys=False,
availability_set=None, nics=None, nsg=None, nsg_rule=None, accelerated_networking=None,
private_ip_address=None, public_ip_address=None, public_ip_address_allocation='dynamic',
public_ip_address_dns_name=None, public_ip_sku=None, os_disk_name=None, os_type=None,
storage_account=None, os_caching=None, data_caching=None, storage_container_name=None, storage_sku=None,
use_unmanaged_disk=False, attach_os_disk=None, os_disk_size_gb=None, attach_data_disks=None,
data_disk_sizes_gb=None, disk_info=None,
vnet_name=None, vnet_address_prefix='10.0.0.0/16', subnet=None, subnet_address_prefix='10.0.0.0/24',
storage_profile=None, os_publisher=None, os_offer=None, os_sku=None, os_version=None,
storage_account_type=None, vnet_type=None, nsg_type=None, public_ip_address_type=None, nic_type=None,
validate=False, custom_data=None, secrets=None, plan_name=None, plan_product=None, plan_publisher=None,
plan_promotion_code=None, license_type=None, assign_identity=None, identity_scope=None,
identity_role=None, identity_role_id=None, encryption_identity=None,
application_security_groups=None, zone=None, boot_diagnostics_storage=None, ultra_ssd_enabled=None,
ephemeral_os_disk=None, ephemeral_os_disk_placement=None,
proximity_placement_group=None, dedicated_host=None, dedicated_host_group=None, aux_subscriptions=None,
priority=None, max_price=None, eviction_policy=None, enable_agent=None, workspace=None, vmss=None,
os_disk_encryption_set=None, data_disk_encryption_sets=None, specialized=None,
encryption_at_host=None, enable_auto_update=None, patch_mode=None, ssh_key_name=None,
enable_hotpatching=None, platform_fault_domain=None, security_type=None, enable_secure_boot=None,
enable_vtpm=None, count=None, edge_zone=None, nic_delete_option=None, os_disk_delete_option=None,
data_disk_delete_option=None, user_data=None, capacity_reservation_group=None, enable_hibernation=None,
v_cpus_available=None, v_cpus_per_core=None, accept_term=None,
disable_integrity_monitoring=None, # Unused
enable_integrity_monitoring=False,
os_disk_security_encryption_type=None, os_disk_secure_vm_disk_encryption_set=None,
disk_controller_type=None, disable_integrity_monitoring_autoupgrade=False, enable_proxy_agent=None,
proxy_agent_mode=None, source_snapshots_or_disks=None, source_snapshots_or_disks_size_gb=None,
source_disk_restore_point=None, source_disk_restore_point_size_gb=None, ssh_key_type=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, what_if=False):
from azure.cli.core.commands.client_factory import get_subscription_id
from azure.cli.core.util import random_string, hash_string
from azure.cli.core.commands.arm import ArmTemplateBuilder
from azure.cli.command_modules.vm._template_builder import (build_vm_resource,
build_storage_account_resource, build_nic_resource,
build_vnet_resource, build_nsg_resource,
build_public_ip_resource, StorageProfile,
build_msi_role_assignment,
build_vm_linux_log_analytics_workspace_agent,
build_vm_windows_log_analytics_workspace_agent)
from azure.cli.command_modules.vm._vm_utils import ArmTemplateBuilder20190401
from azure.mgmt.core.tools import resource_id, is_valid_resource_id, parse_resource_id
# In the latest profile, the default public IP will be expected to be changed from Basic to Standard,
# and Basic option will be removed.
# In order to avoid breaking change which has a big impact to users,
# we use the hint to guide users to use Standard public IP to create VM in the first stage.
if cmd.cli_ctx.cloud.profile == 'latest':
if public_ip_sku == "Basic":
logger.warning(remove_basic_option_msg, "--public-ip-sku Standard")
subscription_id = get_subscription_id(cmd.cli_ctx)
if os_disk_encryption_set is not None and not is_valid_resource_id(os_disk_encryption_set):
os_disk_encryption_set = resource_id(
subscription=subscription_id, resource_group=resource_group_name,
namespace='Microsoft.Compute', type='diskEncryptionSets', name=os_disk_encryption_set)
if os_disk_secure_vm_disk_encryption_set is not None and\
not is_valid_resource_id(os_disk_secure_vm_disk_encryption_set):
os_disk_secure_vm_disk_encryption_set = resource_id(
subscription=subscription_id, resource_group=resource_group_name,
namespace='Microsoft.Compute', type='diskEncryptionSets', name=os_disk_secure_vm_disk_encryption_set)
if data_disk_encryption_sets is None:
data_disk_encryption_sets = []
for i, des in enumerate(data_disk_encryption_sets):
if des is not None and not is_valid_resource_id(des):
data_disk_encryption_sets[i] = resource_id(
subscription=subscription_id, resource_group=resource_group_name,
namespace='Microsoft.Compute', type='diskEncryptionSets', name=des)
storage_sku = disk_info['os'].get('storageAccountType')
network_id_template = resource_id(
subscription=subscription_id, resource_group=resource_group_name,
namespace='Microsoft.Network')
vm_id = resource_id(
subscription=subscription_id, resource_group=resource_group_name,
namespace='Microsoft.Compute', type='virtualMachines', name=vm_name)
# determine final defaults and calculated values
tags = tags or {}
os_disk_name = os_disk_name or ('osdisk_{}'.format(hash_string(vm_id, length=10)) if use_unmanaged_disk else None)
storage_container_name = storage_container_name or 'vhds'
# Build up the ARM template
if count is None:
master_template = ArmTemplateBuilder()
else:
master_template = ArmTemplateBuilder20190401()
vm_dependencies = []
if storage_account_type == 'new':
storage_account = storage_account or 'vhdstorage{}'.format(
hash_string(vm_id, length=14, force_lower=True))
vm_dependencies.append('Microsoft.Storage/storageAccounts/{}'.format(storage_account))
master_template.add_resource(build_storage_account_resource(cmd, storage_account, location,
tags, storage_sku, edge_zone))
nic_name = None
if nic_type == 'new':
nic_name = '{}VMNic'.format(vm_name)
nic_full_name = 'Microsoft.Network/networkInterfaces/{}'.format(nic_name)
if count:
vm_dependencies.extend([nic_full_name + str(i) for i in range(count)])
else:
vm_dependencies.append(nic_full_name)
nic_dependencies = []
if vnet_type == 'new':
subnet = subnet or '{}Subnet'.format(vm_name)
vnet_exists = False
if vnet_name:
from azure.cli.command_modules.vm._vm_utils import check_existence
vnet_exists = \
check_existence(cmd.cli_ctx, vnet_name, resource_group_name, 'Microsoft.Network', 'virtualNetworks')
if vnet_exists:
SubnetCreate = import_aaz_by_profile(cmd.cli_ctx.cloud.profile, "network.vnet.subnet").Create
try:
poller = SubnetCreate(cli_ctx=cmd.cli_ctx)(command_args={
'name': subnet,
'vnet_name': vnet_name,
'resource_group': resource_group_name,
'address_prefixes': [subnet_address_prefix],
'address_prefix': subnet_address_prefix
})
LongRunningOperation(cmd.cli_ctx)(poller)
except Exception:
raise CLIError('Subnet({}) does not exist, but failed to create a new subnet with address '
'prefix {}. It may be caused by name or address prefix conflict. Please specify '
'an appropriate subnet name with --subnet or a valid address prefix value with '
'--subnet-address-prefix.'.format(subnet, subnet_address_prefix))
if not vnet_exists:
vnet_name = vnet_name or '{}VNET'.format(vm_name)
nic_dependencies.append('Microsoft.Network/virtualNetworks/{}'.format(vnet_name))
master_template.add_resource(build_vnet_resource(cmd, vnet_name, location, tags, vnet_address_prefix,
subnet, subnet_address_prefix, edge_zone=edge_zone))
if nsg_type == 'new':
if nsg_rule is None:
nsg_rule = 'RDP' if os_type.lower() == 'windows' else 'SSH'
nsg = nsg or '{}NSG'.format(vm_name)
nic_dependencies.append('Microsoft.Network/networkSecurityGroups/{}'.format(nsg))
master_template.add_resource(build_nsg_resource(cmd, nsg, location, tags, nsg_rule))
if public_ip_address_type == 'new':
public_ip_address = public_ip_address or '{}PublicIP'.format(vm_name)
public_ip_address_full_name = 'Microsoft.Network/publicIpAddresses/{}'.format(public_ip_address)
if count:
nic_dependencies.extend([public_ip_address_full_name + str(i) for i in range(count)])
else:
nic_dependencies.append(public_ip_address_full_name)
master_template.add_resource(build_public_ip_resource(cmd, public_ip_address, location, tags,
public_ip_address_allocation,
public_ip_address_dns_name,
public_ip_sku, zone, count, edge_zone))
subnet_id = subnet if is_valid_resource_id(subnet) else \
'{}/virtualNetworks/{}/subnets/{}'.format(network_id_template, vnet_name, subnet)
nsg_id = None
if nsg:
nsg_id = nsg if is_valid_resource_id(nsg) else \
'{}/networkSecurityGroups/{}'.format(network_id_template, nsg)
public_ip_address_id = None
if public_ip_address:
public_ip_address_id = public_ip_address if is_valid_resource_id(public_ip_address) \
else '{}/publicIPAddresses/{}'.format(network_id_template, public_ip_address)
nics_id = '{}/networkInterfaces/{}'.format(network_id_template, nic_name)
if count:
nics = [
{
'id': "[concat('{}', copyIndex())]".format(nics_id),