Debian Codegraph @

ansible_collections/azure/azcollection/plugins/modules/azure_rm_manageddisk.py

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2017 Bruno Medina Bolanos Cacho <[email protected]>
4 #
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10
11 DOCUMENTATION = '''
12 ---
13 module: azure_rm_manageddisk
14
15 version_added: "0.1.2"
16
17 short_description: Manage Azure Manage Disks
18
19 description:
20 - Create, update and delete an Azure Managed Disk.
21
22 notes:
23 - This module was called M(azure.azcollection.azure_rm_managed_disk) before Ansible 2.8. The usage did not change.
24
25 options:
26 resource_group:
27 description:
28 - Name of a resource group where the managed disk exists or will be created.
29 required: true
30 type: str
31 name:
32 description:
33 - Name of the managed disk.
34 required: true
35 type: str
36 state:
37 description:
38 - Assert the state of the managed disk. Use C(present) to create or update a managed disk and C(absent) to delete a managed disk.
39 default: present
40 type: str
41 choices:
42 - absent
43 - present
44 location:
45 description:
46 - Valid Azure location. Defaults to location of the resource group.
47 type: str
48 storage_account_type:
49 description:
50 - Type of storage for the managed disk.
51 - If not specified, the disk is created as C(Standard_LRS).
52 - C(Standard_LRS) is for Standard HDD.
53 - C(StandardSSD_LRS) (added in 2.8) is for Standard SSD.
54 - C(StandardSSD_ZRS) is for Standard SSD Zone-redundant.
55 - C(Premium_LRS) is for Premium SSD.
56 - C(Premium_ZRS) is for Premium SSD Zone-redundant.
57 - C(UltraSSD_LRS) (added in 2.8) is for Ultra SSD, which is only available on select instance types.
58 - See U(https://docs.microsoft.com/en-us/azure/virtual-machines/windows/disks-types) for more information about disk types.
59 type: str
60 choices:
61 - Standard_LRS
62 - StandardSSD_LRS
63 - StandardSSD_ZRS
64 - Premium_LRS
65 - PremiumV2_LRS
66 - Premium_ZRS
67 - UltraSSD_LRS
68 create_option:
69 description:
70 - C(import) from a VHD file in I(source_uri) and C(copy) from previous managed disk I(source_uri).
71 type: str
72 choices:
73 - empty
74 - import
75 - copy
76 - upload
77 - fromimage
78 - restore
79 - uploadpreparedsecure
80 storage_account_id:
81 description:
82 - The full path to the storage account the image is to be imported from.
83 - Required when I(create_option=import).
84 type: str
85 source_uri:
86 description:
87 - URI to a valid VHD file to be used or the resource ID of the managed disk to copy.
88 type: str
89 aliases:
90 - source_resource_uri
91 os_type:
92 description:
93 - Type of Operating System.
94 - Used when I(create_option=copy) or I(create_option=import) and the source is an OS disk.
95 - If omitted during creation, no value is set.
96 - If omitted during an update, no change is made.
97 - Once set, this value cannot be cleared.
98 type: str
99 choices:
100 - linux
101 - windows
102 - Linux
103 - Windows
104 disk_size_gb:
105 description:
106 - Size in GB of the managed disk to be created.
107 - If I(create_option=copy) then the value must be greater than or equal to the source's size.
108 type: int
109 managed_by:
110 description:
111 - Name of an existing virtual machine with which the disk is or will be associated, this VM should be in the same resource group.
112 - To detach a disk from a vm, explicitly set to ''.
113 - If this option is unset, the value will not be changed.
114 type: str
115 managed_by_extended:
116 description:
117 - List of name and resource group of the VMs that have the disk attached.
118 - I(max_shares) should be set to a value greater than one for disks to allow attaching them to multiple VMs.
119 type: list
120 elements: dict
121 suboptions:
122 resource_group:
123 description:
124 - The resource group of the attache VM.
125 type: str
126 name:
127 description:
128 - The name of the attache VM.
129 type: str
130 max_shares:
131 description:
132 - The maximum number of VMs that can attach to the disk at the same time.
133 - Value greater than one indicates a disk that can be mounted on multiple VMs at the same time.
134 type: int
135 attach_caching:
136 description:
137 - Disk caching policy controlled by VM. Will be used when attached to the VM defined by C(managed_by).
138 - If this option is different from the current caching policy, the managed disk will be deattached and attached with current caching option again.
139 type: str
140 choices:
141 - ''
142 - read_only
143 - read_write
144 zone:
145 description:
146 - The Azure managed disk's zone.
147 - Allowed values are C(1), C(2), C(3) and C('').
148 type: str
149 choices:
150 - '1'
151 - '2'
152 - '3'
153 - ''
154 lun:
155 description:
156 - The logical unit number for data disk.
157 - This value is used to identify data disks within the VM and therefore must be unique for each data disk attached to a VM.
158 type: int
159 disk_iops_read_write:
160 description:
161 - The number of IOPS allowed for this disk.
162 - Only settable for I(storage_account_type=UltraSSD_LRS) disks.
163 - One operation can transfer between 4k and 256k bytes.
164 type: int
165 disk_m_bps_read_write:
166 description:
167 - The bandwidth allowed for this disk.
168 - Only settable for I(storage_account_type=UltraSSD_LRS) disks.
169 - One operation can transfer between 4k and 256k bytes.
170 type: int
171 disk_iops_read_only:
172 description:
173 - The total throughput (MBps) that will be allowed across all VMs mounting the shared disk as ReadOnly.
174 - One operation can transfer between 4k and 256k bytes.
175 type: int
176 disk_m_bps_read_only:
177 description:
178 - The total throughput (MBps) that will be allowed across all VMs mounting the shared disk as ReadOnly.
179 - MBps means millions of bytes per second - MB here uses the ISO notation, of powers of 10.
180 type: int
181 tier:
182 description:
183 - Performance tier assigned to this disk.
184 - Only settable for I(storage_account_type=Premium_LRS) disks.
185 - Allowed values are C(P1), C(P2), C(P3), C(P4), C(P6), C(P10), C(P15), C(P20), C(P30), C(P40), C(P50), C(P60), C(P70), C(P80)
186 - See U(https://learn.microsoft.com/en-us/azure/virtual-machines/disks-change-performance) for more information about disk performance tiers.
187 - Does not apply to Ultra disks.
188 type: str
189 choices:
190 - P1
191 - P2
192 - P3
193 - P4
194 - P6
195 - P10
196 - P15
197 - P20
198 - P30
199 - P40
200 - P50
201 - P60
202 - P70
203 - P80
204 network_access_policy:
205 description:
206 - Policy for accessing the disk via network.
207 type: str
208 choices:
209 - AllowAll
210 - AllowPrivate
211 - DenyAll
212 public_network_access:
213 description:
214 - Policy for controlling export on the disk.
215 type: str
216 choices:
217 - Enabled
218 - Disabled
219 write_accelerator_enabled:
220 description:
221 - Specifies whether writeAccelerator should be enabled or disabled on the disk.
222 type: bool
223 disk_access_id:
224 description:
225 - ARM ID of the DiskAccess resource for using private endpoints on disks.
226 type: str
227 performance_plus:
228 description:
229 - Set this flag to true to get a boost on the performance target of the disk deployed, see here on the respective performance target.
230 - This flag can only be set on disk creation time and cannot be disabled after enabled.
231 type: bool
232 upload_size_bytes:
233 description:
234 - If I(create_option=upload), this is the size of the contents of the upload including the VHD footer.
235 - This value should be between 20972032 (20 MiB + 512 bytes for the VHD footer) and 35183298347520 bytes (32 TiB + 512 bytes for the VHD footer).
236 type: int
237 gallery_image_reference:
238 description:
239 - Required if creating from a Gallery Image.
240 - The id/sharedGalleryImageId/communityGalleryImageId of the ImageDiskReference
241 will be the ARM id of the shared galley image version from which to create a disk.
242 type: dict
243 suboptions:
244 id:
245 description:
246 - A relative uri containing either a Platform Image Repository, user image, or Azure Compute Gallery image reference.
247 type: str
248 shared_gallery_image_id:
249 description:
250 - A relative uri containing a direct shared Azure Compute Gallery image reference.
251 type: str
252 community_gallery_image_id:
253 description:
254 - A relative uri containing a community Azure Compute Gallery image reference.
255 type: str
256 image_reference:
257 description:
258 - Disk source information for PIR or user images or Gallery Image.
259 type: dict
260 suboptions:
261 id:
262 description:
263 - A relative uri containing either a Platform Image Repository, user image, or Azure Compute Gallery image reference.
264 type: str
265 shared_gallery_image_id:
266 description:
267 - A relative uri containing a direct shared Azure Compute Gallery image reference.
268 type: str
269 community_gallery_image_id:
270 description:
271 - A relative uri containing a community Azure Compute Gallery image reference.
272 type: str
273 logical_sector_size:
274 description:
275 - Logical sector size in bytes for Ultra disks.
276 - Supported values are 512 ad 4096. 4096 is the default.
277 type: int
278 source_resource_id:
279 description:
280 - If I(create_option=copy), this is the ARM id of the source snapshot or disk.
281 type: str
282 security_profile:
283 description:
284 - Contains the security related information for the resource.
285 type: dict
286 suboptions:
287 security_type:
288 description:
289 - Specifies the SecurityType of the VM. Applicable for OS disks only.
290 type: str
291 choices:
292 - TrustedLaunch
293 - ConfidentialVM_VMGuestStateOnlyEncryptedWithPlatformKey
294 - ConfidentialVM_DiskEncryptedWithPlatformKey
295 - ConfidentialVM_DiskEncryptedWithCustomerKey
296 secure_vm_disk_encryption_set_id:
297 description:
298 - ResourceId of the disk encryption set associated to Confidential VM supported disk encrypted with customer managed key.
299 type: str
300 extends_documentation_fragment:
301 - azure.azcollection.azure
302 - azure.azcollection.azure_tags
303 author:
304 - Bruno Medina (@brusMX)
305 '''
306
307 EXAMPLES = '''
308 - name: Create managed disk
309 azure_rm_manageddisk:
310 name: mymanageddisk
311 location: eastus
312 resource_group: myResourceGroup
313 disk_size_gb: 4
314
315 - name: Create managed operating system disk from page blob
316 azure_rm_manageddisk:
317 name: mymanageddisk
318 location: eastus2
319 resource_group: myResourceGroup
320 create_option: import
321 source_uri: https://storageaccountname.blob.core.windows.net/containername/blob-name.vhd
322 storage_account_id: /subscriptions/<uuid>/resourceGroups/myResourceGroup/providers/Microsoft.Storage/storageAccounts/storageaccountname
323 os_type: windows
324 storage_account_type: Premium_LRS
325
326 - name: Create managed disk with I(create_option=upload)
327 azure_rm_manageddisk:
328 resource_group: myResourceGroup
329 name: mymanageddisk
330 storage_account_type: "Standard_LRS"
331 upload_size_bytes: 20972032
332 network_access_policy: DenyAll
333 public_network_access: Disabled
334 create_option: upload
335
336 - name: Create managed disk with I(create_option=fromimage)
337 azure_rm_manageddisk:
338 resource_group: "{{ resource_group }}"
339 name: "md{{ rpfx }}"
340 storage_account_type: "Standard_LRS"
341 disk_size_gb: 1024
342 network_access_policy: DenyAll
343 public_network_access: Disabled
344 create_option: fromimage
345 os_type: windows
346 security_profile:
347 security_type: TrustedLaunch
348 gallery_image_reference:
349 id: "/subscriptions/xxxx/resourceGroups/testRG/providers/Microsoft.Compute/galleries/Gallery01/images/windowsVMimage/versions/0.0.1"
350
351 - name: Create managed disk with I(create_option=restore)
352 azure_rm_manageddisk:
353 resource_group: "{{ resource_group }}"
354 name: "md{{ rpfx }}"
355 storage_account_type: "Standard_LRS"
356 disk_size_gb: 1024
357 network_access_policy: DenyAll
358 public_network_access: Disabled
359 performance_plus: true
360 source_resource_id: "/subscriptions/xxxx/resourceGroups/testRG/providers/Microsoft.Compute/
361 restorePointCollections/point01/restorePoints/restorepoint01/diskRestorePoints/testVM_OsDisk_1"
362 create_option: restore
363
364 - name: Create managed disk with I(create_option=uploadpreparedsecure)
365 azure_rm_manageddisk:
366 resource_group: "{{ resource_group }}"
367 name: "md{{ rpfx }}"
368 storage_account_type: "Standard_LRS"
369 upload_size_bytes: 20972032
370 network_access_policy: DenyAll
371 public_network_access: Disabled
372 create_option: uploadpreparedsecure
373 security_profile:
374 security_type: TrustedLaunch
375
376 - name: Mount the managed disk to VM
377 azure_rm_manageddisk:
378 name: mymanageddisk
379 location: eastus
380 resource_group: myResourceGroup
381 disk_size_gb: 4
382 managed_by: testvm001
383 attach_caching: read_only
384
385 - name: Mount the managed disk to multiple VMs
386 azure_rm_manageddisk:
387 resource_group: myResourceGroup
388 name: freddisk04
389 max_shares: 4
390 disk_size_gb: 1024
391 storage_account_type: Premium_LRS
392 managed_by_extended:
393 - resource_group: myResourceGroup01
394 name: testVM01
395 - resource_group: myResourceGroup02
396 name: testVM02
397 zone: 1
398
399 - name: Unmount the managed disk to VM
400 azure_rm_manageddisk:
401 name: mymanageddisk
402 location: eastus
403 resource_group: myResourceGroup
404 managed_by: ''
405 disk_size_gb: 4
406
407 - name: Delete managed disk
408 azure_rm_manageddisk:
409 name: mymanageddisk
410 location: eastus
411 resource_group: myResourceGroup
412 state: absent
413 '''
414
415 RETURN = '''
416 state:
417 description:
418 - Current state of the managed disk.
419 returned: always
420 type: complex
421 contains:
422 id:
423 description:
424 - Resource id.
425 type: str
426 name:
427 description:
428 - Name of the managed disk.
429 type: str
430 location:
431 description:
432 - Valid Azure location.
433 type: str
434 storage_account_type:
435 description:
436 - Type of storage for the managed disk.
437 - See U(https://docs.microsoft.com/en-us/azure/virtual-machines/windows/disks-types) for more information about this type.
438 type: str
439 sample: Standard_LRS
440 create_option:
441 description:
442 - Create option of the disk.
443 type: str
444 sample: copy
445 storage_account_id:
446 description:
447 - The full path to the storage account the image is to be imported from
448 type: str
449 sample: /subscriptions/<uuid>/resourceGroups/<resource group name>/providers/Microsoft.Storage/storageAccounts/<storage account name>
450 source_uri:
451 description:
452 - URI to a valid VHD file to be used or the resource ID of the managed disk to copy.
453 type: str
454 os_type:
455 description:
456 - Type of Operating System.
457 type: str
458 sample: linux
459 disk_size_gb:
460 description:
461 - Size in GB of the managed disk to be created.
462 type: str
463 managed_by:
464 description:
465 - Name of an existing virtual machine with which the disk is or will be associated, this VM should be in the same resource group.
466 type: str
467 max_shares:
468 description:
469 - The maximum number of VMs that can attach to the disk at the same time.
470 - Value greater than one indicates a disk that can be mounted on multiple VMs at the same time.
471 type: int
472 sample: 3
473 managed_by_extended:
474 description:
475 - List ID of an existing virtual machine with which the disk is or will be associated.
476 type: list
477 sample: ["/subscriptions/xxx-xxx/resourceGroups/myRG/providers/Microsoft.Compute/virtualMachines/testVM"]
478 tags:
479 description:
480 - Tags to assign to the managed disk.
481 type: dict
482 sample: { "tag": "value" }
483 disk_iops_read_write:
484 description:
485 - The number of IOPS allowed for this disk.
486 - Only settable for I(storage_account_type=UltraSSD_LRS) disks.
487 - One operation can transfer between 4k and 256k bytes.
488 type: int
489 returned: always
490 sample: 200
491 disk_m_bps_read_write:
492 description:
493 - The bandwidth allowed for this disk.
494 - Only settable for I(storage_account_type=UltraSSD_LRS) disks.
495 - One operation can transfer between 4k and 256k bytes.
496 type: int
497 returned: always
498 sample: 30
499 disk_iops_read_only:
500 description:
501 - The total throughput (MBps) that will be allowed across all VMs mounting the shared disk as ReadOnly.
502 - One operation can transfer between 4k and 256k bytes.
503 type: int
504 returned: always
505 sample: 200
506 disk_m_bps_read_only:
507 description:
508 - The total throughput (MBps) that will be allowed across all VMs mounting the shared disk as ReadOnly.
509 - MBps means millions of bytes per second - MB here uses the ISO notation, of powers of 10.
510 type: int
511 returned: always
512 sample: 30
513 tier:
514 description:
515 - Performance tier assigned to the managed disk.
516 type: str
517 sample: "P30"
518 network_access_policy:
519 description:
520 - Policy for accessing the disk via network.
521 type: str
522 returned: always
523 sample: AllowAll
524 public_network_access:
525 description:
526 - Policy for controlling export on the disk.
527 type: str
528 returned: always
529 sample: Enabled
530 disk_access_id:
531 description:
532 - ARM ID of the DiskAccess resource for using private endpoints on disks.
533 type: str
534 returned: always
535 sample: '/subscriptions/*********/resourceGroups/myRG/providers/Microsoft.Compute/diskAccesses/diskacc'
536 performance_plus:
537 description:
538 - The flag of the performance target of the disk deployed.
539 type: bool
540 returned: always
541 sample: False
542 upload_size_bytes:
543 description:
544 - This is the size of the contents of the upload including the VHD footer.
545 type: int
546 returned: always
547 sample: None
548 image_reference:
549 description:
550 - Disk source information for PIR or user images or Gallery Image.
551 type: dict
552 returned: always
553 sample: None
554 gallery_image_reference:
555 description:
556 - The Gallery Image info.
557 type: dict
558 returned: always
559 sample: None
560 logical_sector_size:
561 description:
562 - Logical sector size in bytes for Ultra disks.
563 type: int
564 returned: always
565 sample: None
566 source_resource_id:
567 description:
568 - This is the ARM id of the source snapshot or disk.
569 type: str
570 returned: always
571 sample: None
572 security_profile:
573 description:
574 - The security related information for the resource.
575 type: complex
576 contains:
577 security_type:
578 description:
579 - Specifies the SecurityType of the VM.
580 type: str
581 returned: when-used
582 sample: TrustedLaunch
583 secure_vm_disk_encryption_set_id:
584 description:
585 - ResourceId of the disk encryption set associated to Confidential VM supported disk encrypted with customer managed key.
586 type: str
587 returned: when-used
588 sample: None
589 changed:
590 description:
591 - Whether or not the resource has changed.
592 returned: always
593 type: bool
594 '''
595
596
597 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase
598 try:
599 from concurrent.futures import ThreadPoolExecutor
600 import multiprocessing
601 from azure.mgmt.core.tools import parse_resource_id
602 from azure.core.exceptions import ResourceNotFoundError
603 except ImportError:
604 # This is handled in azure_rm_common
605 pass
606
607
608 managed_by_extended_spec = dict(
609 resource_group=dict(type='str'),
610 name=dict(type='str')
611 )
612
613
614 # duplicated in azure_rm_manageddisk_facts
615 def managed_disk_to_dict(managed_disk):
616 create_data = managed_disk.creation_data
617 return dict(
618 id=managed_disk.id,
619 name=managed_disk.name,
620 location=managed_disk.location,
621 tags=managed_disk.tags,
622 create_option=create_data.create_option.lower(),
623 source_uri=create_data.source_uri,
624 disk_size_gb=managed_disk.disk_size_gb,
625 os_type=managed_disk.os_type.lower() if managed_disk.os_type else None,
626 storage_account_type=managed_disk.sku.name if managed_disk.sku else None,
627 managed_by=managed_disk.managed_by,
628 max_shares=managed_disk.max_shares,
629 managed_by_extended=managed_disk.managed_by_extended,
630 zone=managed_disk.zones[0] if managed_disk.zones and len(managed_disk.zones) > 0 else '',
631 disk_iops_read_write=managed_disk.disk_iops_read_write,
632 disk_m_bps_read_write=managed_disk.disk_m_bps_read_write,
633 disk_iops_read_only=managed_disk.disk_iops_read_only,
634 disk_m_bps_read_only=managed_disk.disk_m_bps_read_only,
635 tier=managed_disk.tier,
636 public_network_access=managed_disk.public_network_access,
637 network_access_policy=managed_disk.network_access_policy,
638 disk_access_id=managed_disk.disk_access_id,
639 source_resource_id=create_data.source_resource_id,
640 storage_account_id=create_data.storage_account_id,
641 upload_size_bytes=create_data.upload_size_bytes,
642 logical_sector_size=create_data.logical_sector_size,
643 performance_plus=create_data.performance_plus,
644 gallery_image_reference=dict(
645 id=create_data.gallery_image_reference.id,
646 shared_gallery_image_id=create_data.gallery_image_reference.shared_gallery_image_id,
647 community_gallery_image_id=create_data.gallery_image_reference.community_gallery_image_id
648 ) if create_data.gallery_image_reference is not None else None,
649 image_reference=dict(
650 id=create_data.image_reference.id,
651 shared_gallery_image_id=create_data.image_reference.shared_gallery_image_id,
652 community_gallery_image_id=create_data.image_reference.community_gallery_image_id
653 ) if create_data.image_reference is not None else None,
654 security_profile=dict(
655 security_type=managed_disk.security_profile.security_type,
656 secure_vm_disk_encryption_set_id=managed_disk.security_profile.secure_vm_disk_encryption_set_id
657 ) if managed_disk.security_profile is not None else None
658 )
659
660
661 class AzureRMManagedDisk(AzureRMModuleBase):
662 """Configuration class for an Azure RM Managed Disk resource"""
663
664 def __init__(self):
665 self.module_arg_spec = dict(
666 resource_group=dict(
667 type='str',
668 required=True
669 ),
670 name=dict(
671 type='str',
672 required=True
673 ),
674 state=dict(
675 type='str',
676 default='present',
677 choices=['present', 'absent']
678 ),
679 location=dict(
680 type='str'
681 ),
682 storage_account_type=dict(
683 type='str',
684 choices=['Standard_LRS', 'StandardSSD_LRS', 'StandardSSD_ZRS', 'Premium_LRS', 'Premium_ZRS', 'UltraSSD_LRS', 'PremiumV2_LRS']
685 ),
686 create_option=dict(
687 type='str',
688 choices=['empty', 'import', 'copy', 'upload', 'fromimage', 'restore', 'uploadpreparedsecure']
689 ),
690 storage_account_id=dict(
691 type='str'
692 ),
693 source_uri=dict(
694 type='str',
695 aliases=['source_resource_uri']
696 ),
697 os_type=dict(
698 type='str',
699 choices=['linux', 'windows', 'Linux', 'Windows']
700 ),
701 disk_size_gb=dict(
702 type='int'
703 ),
704 managed_by=dict(
705 type='str'
706 ),
707 zone=dict(
708 type='str',
709 choices=['', '1', '2', '3']
710 ),
711 attach_caching=dict(
712 type='str',
713 choices=['', 'read_only', 'read_write']
714 ),
715 lun=dict(
716 type='int'
717 ),
718 max_shares=dict(
719 type='int'
720 ),
721 managed_by_extended=dict(
722 type='list',
723 elements='dict',
724 options=managed_by_extended_spec
725 ),
726 disk_iops_read_only=dict(
727 type='int'
728 ),
729 disk_iops_read_write=dict(
730 type='int'
731 ),
732 disk_m_bps_read_only=dict(
733 type='int'
734 ),
735 disk_m_bps_read_write=dict(
736 type='int'
737 ),
738 tier=dict(
739 type='str',
740 choices=['P1', 'P2', 'P3', 'P4', 'P6', 'P10', 'P15', 'P20', 'P30', 'P40', 'P50', 'P60', 'P70', 'P80']
741 ),
742 public_network_access=dict(
743 type='str',
744 choices=['Enabled', 'Disabled']
745 ),
746 write_accelerator_enabled=dict(
747 type='bool',
748 ),
749 network_access_policy=dict(
750 type='str',
751 choices=['AllowAll', 'AllowPrivate', 'DenyAll']
752 ),
753 disk_access_id=dict(
754 type='str'
755 ),
756 performance_plus=dict(type='bool'),
757 upload_size_bytes=dict(type='int'),
758 gallery_image_reference=dict(
759 type='dict',
760 options=dict(
761 id=dict(type='str'),
762 shared_gallery_image_id=dict(type='str'),
763 community_gallery_image_id=dict(type='str')
764 )
765 ),
766 image_reference=dict(
767 type='dict',
768 options=dict(
769 id=dict(type='str'),
770 shared_gallery_image_id=dict(type='str'),
771 community_gallery_image_id=dict(type='str')
772 )
773 ),
774 logical_sector_size=dict(
775 type='int',
776 ),
777 source_resource_id=dict(
778 type='str'
779 ),
780 security_profile=dict(
781 type='dict',
782 options=dict(
783 security_type=dict(
784 type='str',
785 choices=["TrustedLaunch", "ConfidentialVM_VMGuestStateOnlyEncryptedWithPlatformKey",
786 "ConfidentialVM_DiskEncryptedWithPlatformKey", "ConfidentialVM_DiskEncryptedWithCustomerKey"]
787 ),
788 secure_vm_disk_encryption_set_id=dict(type='str')
789 )
790 )
791 )
792 required_if = [
793 ('create_option', 'import', ['source_uri', 'storage_account_id']),
794 ('create_option', 'copy', ['source_resource_id']),
795 ('create_option', 'empty', ['disk_size_gb']),
796 ('create_option', 'upload', ['upload_size_bytes']),
797 ('create_option', 'restore', ['source_resource_id']),
798 ('create_option', 'uploadpreparedsecure', ['upload_size_bytes', 'security_profile']),
799 ('network_access_policy', 'AllowPrivate', ['disk_access_id'])
800 ]
801 self.results = dict(
802 changed=False,
803 state=dict())
804
805 self.resource_group = None
806 self.name = None
807 self.location = None
808 self.storage_account_type = None
809 self.create_option = None
810 self.storage_account_id = None
811 self.source_uri = None
812 self.os_type = None
813 self.disk_size_gb = None
814 self.tags = None
815 self.zone = None
816 self.managed_by = None
817 self.attach_caching = None
818 self.lun = None
819 self.max_shares = None
820 self.managed_by_extended = None
821 self.disk_iops_read_write = None
822 self.disk_m_bps_read_write = None
823 self.disk_iops_read_only = None
824 self.disk_m_bps_read_only = None
825 self.tier = None
826 self.public_network_access = None
827 self.network_access_policy = None
828 self.write_accelerator_enabled = None
829 self.disk_access_id = None
830 self.performance_plus = None
831 self.upload_size_bytes = None
832 self.source_resource_id = None
833 self.image_reference = None
834 self.gallery_image_reference = None
835 self.logical_sector_size = None
836 self.security_profile = None
837
838 mutually_exclusive = [['managed_by_extended', 'managed_by'], ['image_reference', 'gallery_image_reference']]
839
840 super(AzureRMManagedDisk, self).__init__(
841 derived_arg_spec=self.module_arg_spec,
842 required_if=required_if,
843 supports_check_mode=True,
844 mutually_exclusive=mutually_exclusive,
845 supports_tags=True)
846
847 def exec_module(self, **kwargs):
848 """Main module execution method"""
849 for key in list(self.module_arg_spec.keys()) + ['tags']:
850 setattr(self, key, kwargs[key])
851
852 result = None
853 changed = False
854 update_flag = False
855
856 resource_group = self.get_resource_group(self.resource_group)
857 if not self.location:
858 self.location = resource_group.location
859
860 disk_instance = self.get_managed_disk()
861 if disk_instance is not None:
862 update_flag = True
863 if self.create_option is None:
864 self.create_option = disk_instance.get('create_option')
865 if self.source_uri is None:
866 self.source_uri = disk_instance.get('source_uri')
867 if self.disk_size_gb is None:
868 self.disk_size_gb = disk_instance.get('disk_size_gb')
869 if self.os_type is None:
870 self.os_type = disk_instance.get('os_type')
871 if self.zone is None:
872 self.zone = disk_instance.get('zone')
873 if self.public_network_access is None:
874 self.public_network_access = disk_instance.get('public_network_access')
875 if self.network_access_policy is None:
876 self.network_access_policy = disk_instance.get('network_access_policy')
877 if self.disk_access_id is None:
878 self.disk_access_id = disk_instance.get('disk_access_id')
879 if self.upload_size_bytes is None:
880 self.upload_size_bytes = disk_instance.get('upload_size_bytes')
881 if self.image_reference is None:
882 self.image_reference = disk_instance.get('image_reference')
883 if self.gallery_image_reference is None:
884 self.gallery_image_reference = disk_instance.get('gallery_image_reference')
885
886 result = disk_instance
887
888 # need create or update
889 if self.state == 'present':
890 parameter = self.generate_managed_disk_property()
891 if not disk_instance or self.is_different(disk_instance, parameter):
892 changed = True
893 if not self.check_mode:
894 result = self.create_or_update_managed_disk(parameter, update_flag)
895 else:
896 result = True
897
898 # Mount the disk to multiple VM
899 if self.managed_by_extended:
900 if not self.check_mode:
901 cpu_count = multiprocessing.cpu_count()
902 executor = ThreadPoolExecutor(max_workers=cpu_count)
903 task_result = []
904 for vm_item in self.managed_by_extended:
905 vm_name_id = self.compute_client.virtual_machines.get(vm_item['resource_group'], vm_item['name'])
906 if result['managed_by_extended'] is None or vm_name_id.id not in result['managed_by_extended']:
907 changed = True
908 feature = executor.submit(self.attach, vm_item['resource_group'], vm_item['name'], result)
909 task_result.append({'task': feature, 'vm_name': vm_item['name'], 'resource_group': vm_item['resource_group']})
910 fail_attach_VM = []
911 for task_item in task_result:
912 if task_item['task'].result() is not None:
913 task_item['error_msg'] = task_item['task'].result()
914 task_item.pop('task')
915 fail_attach_VM.append(task_item)
916 if len(fail_attach_VM) > 0:
917 self.fail("Disk mount failure, VM and Error message information: {0}".format(fail_attach_VM))
918
919 result = self.get_managed_disk()
920
921 # unmount from the old virtual machine and mount to the new virtual machine
922 if self.managed_by or self.managed_by == '':
923 vm_name = parse_resource_id(disk_instance.get('managed_by', '')).get('name') if disk_instance else None
924 resource_group = parse_resource_id(disk_instance.get('managed_by', '')).get('resource_group') if disk_instance else None
925 vm_name = vm_name or ''
926 if self.managed_by != vm_name or self.is_attach_caching_option_different(vm_name, result):
927 changed = True
928 if not self.check_mode:
929 if vm_name:
930 self.detach(resource_group, vm_name, result)
931 if self.managed_by:
932 self.attach(self.resource_group, self.managed_by, result)
933 result = self.get_managed_disk()
934
935 if self.state == 'absent' and disk_instance:
936 changed = True
937 if not self.check_mode:
938 self.delete_managed_disk()
939 result = True
940
941 self.results['changed'] = changed
942 self.results['state'] = result
943 return self.results
944
945 def attach(self, resource_group, vm_name, disk):
946 vm = self._get_vm(resource_group, vm_name)
947 # find the lun
948 if self.lun:
949 lun = self.lun
950 else:
951 luns = ([d.lun for d in vm.storage_profile.data_disks]
952 if vm.storage_profile.data_disks else [])
953 lun = 0
954 while True:
955 if lun not in luns:
956 break
957 lun = lun + 1
958 for item in vm.storage_profile.data_disks:
959 if item.name == self.name:
960 lun = item.lun
961
962 # prepare the data disk
963 params = self.compute_models.ManagedDiskParameters(id=disk.get('id'), storage_account_type=disk.get('storage_account_type'))
964 caching_options = self.compute_models.CachingTypes[self.attach_caching] if self.attach_caching and self.attach_caching != '' else None
965 # pylint: disable=missing-kwoa
966 data_disk = self.compute_models.DataDisk(lun=lun,
967 create_option=self.compute_models.DiskCreateOptionTypes.attach,
968 managed_disk=params,
969 write_accelerator_enabled=self.write_accelerator_enabled,
970 caching=caching_options)
971 vm.storage_profile.data_disks.append(data_disk)
972 return self._update_vm(resource_group, vm_name, vm)
973
974 def detach(self, resource_group, vm_name, disk):
975 vm = self._get_vm(resource_group, vm_name)
976 leftovers = [d for d in vm.storage_profile.data_disks if d.name.lower() != disk.get('name').lower()]
977 if len(vm.storage_profile.data_disks) == len(leftovers):
978 self.fail("No disk with the name '{0}' was found".format(disk.get('name')))
979 vm.storage_profile.data_disks = leftovers
980 self._update_vm(resource_group, vm_name, vm)
981
982 def _update_vm(self, resource_group, name, params):
983 try:
984 poller = self.compute_client.virtual_machines.begin_create_or_update(resource_group, name, params)
985 self.get_poller_result(poller)
986 except Exception as exc:
987 if self.managed_by_extended:
988 return exc
989 else:
990 self.fail("Error updating virtual machine {0} - {1}".format(name, str(exc)))
991
992 def _get_vm(self, resource_group, name):
993 try:
994 return self.compute_client.virtual_machines.get(resource_group, name, expand='instanceview')
995 except Exception as exc:
996 self.fail("Error getting virtual machine {0} - {1}".format(name, str(exc)))
997
998 def generate_managed_disk_property(self):
999 # TODO: Add support for EncryptionSettings, DiskIOPSReadWrite, DiskMBpsReadWrite
1000 disk_params = {}
1001 creation_data = {}
1002 disk_params['location'] = self.location
1003 disk_params['tags'] = self.tags
1004 if self.zone:
1005 disk_params['zones'] = [self.zone]
1006 if self.storage_account_type:
1007 storage_account_type = self.disk_models.DiskSku(name=self.storage_account_type)
1008 disk_params['sku'] = storage_account_type
1009 disk_params['disk_size_gb'] = self.disk_size_gb
1010
1011 if self.create_option == 'import':
1012 creation_data['create_option'] = self.disk_models.DiskCreateOption.import_enum
1013 creation_data['source_uri'] = self.source_uri
1014 creation_data['storage_account_id'] = self.storage_account_id
1015 elif self.create_option == 'copy':
1016 creation_data['create_option'] = self.disk_models.DiskCreateOption.copy
1017 creation_data['source_resource_id'] = self.source_resource_id
1018 elif self.create_option == 'upload':
1019 creation_data['create_option'] = self.disk_models.DiskCreateOption.upload
1020 creation_data['upload_size_bytes'] = self.upload_size_bytes
1021 elif self.create_option == 'fromimage':
1022 creation_data['create_option'] = self.disk_models.DiskCreateOption.from_image
1023 if self.image_reference is not None:
1024 image = self.disk_models.ImageDiskReference(id=self.image_reference.get('id'),
1025 shared_gallery_image_id=self.image_reference.get('shared_gallery_image_id'),
1026 community_gallery_image_id=self.image_reference.get('community_gallery_image_id'))
1027 creation_data['image_reference'] = image
1028 elif self.gallery_image_reference is not None:
1029 image = self.disk_models.ImageDiskReference(id=self.gallery_image_reference.get('id'),
1030 shared_gallery_image_id=self.gallery_image_reference.get('shared_gallery_image_id'),
1031 community_gallery_image_id=self.gallery_image_reference.get('community_gallery_image_id'))
1032 creation_data['gallery_image_reference'] = image
1033 else:
1034 self.fail("When create_option=fromimage is configured, image_reference or gallery_image_reference must be configured")
1035 elif self.create_option == 'restore':
1036 creation_data['create_option'] = self.disk_models.DiskCreateOption.Restore
1037 elif self.create_option == 'uploadpreparedsecure':
1038 creation_data['create_option'] = self.disk_models.DiskCreateOption.upload_prepared_secure
1039 creation_data['upload_size_bytes'] = self.upload_size_bytes
1040 else:
1041 creation_data['create_option'] = self.disk_models.DiskCreateOption.empty
1042 creation_data['logical_sector_size'] = self.logical_sector_size
1043 creation_data['performance_plus'] = self.performance_plus
1044 if self.security_profile is not None:
1045 disk_id = self.security_profile.get('secure_vm_disk_encryption_set_id')
1046 disk_params['security_profile'] = self.disk_models.DiskSecurityProfile(security_type=self.security_profile.get('security_type'),
1047 secure_vm_disk_encryption_set_id=disk_id)
1048 if self.os_type:
1049 disk_params['os_type'] = self.disk_models.OperatingSystemTypes(self.os_type.capitalize())
1050 else:
1051 disk_params['os_type'] = None
1052 if self.max_shares:
1053 disk_params['max_shares'] = self.max_shares
1054 if self.disk_m_bps_read_only is not None:
1055 disk_params['disk_m_bps_read_only'] = self.disk_m_bps_read_only
1056 if self.disk_m_bps_read_write is not None:
1057 disk_params['disk_m_bps_read_write'] = self.disk_m_bps_read_write
1058 if self.disk_iops_read_write is not None:
1059 disk_params['disk_iops_read_write'] = self.disk_iops_read_write
1060 if self.disk_iops_read_only is not None:
1061 disk_params['disk_iops_read_only'] = self.disk_iops_read_only
1062 if self.tier is not None:
1063 disk_params['tier'] = self.tier
1064 if self.network_access_policy is not None:
1065 disk_params['network_access_policy'] = self.network_access_policy
1066 if self.public_network_access is not None:
1067 disk_params['public_network_access'] = self.public_network_access
1068 if self.disk_access_id is not None:
1069 disk_params['disk_access_id'] = self.disk_access_id
1070 disk_params['creation_data'] = creation_data
1071 return disk_params
1072
1073 def create_or_update_managed_disk(self, parameter, update_flag):
1074 try:
1075 parameter['tags'] = self.tags
1076 if update_flag:
1077 poller = self.disk_client.disks.begin_update(self.resource_group,
1078 self.name,
1079 parameter)
1080 else:
1081 poller = self.disk_client.disks.begin_create_or_update(self.resource_group,
1082 self.name,
1083 parameter)
1084 aux = self.get_poller_result(poller)
1085 return managed_disk_to_dict(aux)
1086 except Exception as e:
1087 self.fail("Error creating the managed disk: {0}".format(str(e)))
1088
1089 # This method accounts for the difference in structure between the
1090 # Azure retrieved disk and the parameters for the new disk to be created.
1091 def is_different(self, found_disk, new_disk):
1092 resp = False
1093 if new_disk.get('disk_size_gb'):
1094 if not found_disk['disk_size_gb'] == new_disk['disk_size_gb']:
1095 resp = True
1096 if new_disk.get('os_type'):
1097 if found_disk['os_type'] is None or not self.disk_models.OperatingSystemTypes(found_disk['os_type'].capitalize()) == new_disk['os_type']:
1098 resp = True
1099 if new_disk.get('sku'):
1100 if not found_disk['storage_account_type'] == new_disk['sku'].name:
1101 resp = True
1102 # Check how to implement tags
1103 update_tags, self.tags = self.update_tags(found_disk['tags'])
1104 if update_tags:
1105 resp = True
1106 if self.zone is not None:
1107 if not found_disk['zone'] == self.zone:
1108 resp = True
1109 if self.max_shares is not None:
1110 if not found_disk['max_shares'] == self.max_shares:
1111 resp = True
1112 if self.disk_iops_read_write is not None and found_disk['disk_iops_read_write'] != self.disk_iops_read_write:
1113 resp = True
1114 if self.disk_m_bps_read_write is not None and found_disk['disk_m_bps_read_write'] != self.disk_m_bps_read_write:
1115 resp = True
1116 if self.disk_iops_read_only is not None and found_disk['disk_iops_read_only'] != self.disk_iops_read_only:
1117 resp = True
1118 if self.disk_m_bps_read_only is not None and found_disk['disk_m_bps_read_only'] != self.disk_m_bps_read_only:
1119 resp = True
1120 if self.tier is not None:
1121 if not found_disk['tier'] == self.tier:
1122 resp = True
1123 if self.network_access_policy is not None and found_disk['network_access_policy'] != self.network_access_policy:
1124 resp = True
1125 if self.public_network_access is not None and found_disk['public_network_access'] != self.public_network_access:
1126 resp = True
1127 if self.disk_access_id is not None:
1128 if found_disk['disk_access_id'] is not None:
1129 if found_disk['disk_access_id'].lower() != self.disk_access_id.lower():
1130 resp = True
1131 else:
1132 resp = True
1133 return resp
1134
1135 def delete_managed_disk(self):
1136 try:
1137 poller = self.disk_client.disks.begin_delete(self.resource_group,
1138 self.name)
1139 return self.get_poller_result(poller)
1140 except Exception as e:
1141 self.fail("Error deleting the managed disk: {0}".format(str(e)))
1142
1143 def get_managed_disk(self):
1144 try:
1145 resp = self.disk_client.disks.get(
1146 self.resource_group,
1147 self.name)
1148 return managed_disk_to_dict(resp)
1149 except ResourceNotFoundError:
1150 self.log('Did not find managed disk')
1151
1152 def is_attach_caching_option_different(self, vm_name, disk):
1153 resp = False
1154 if vm_name:
1155 vm = self._get_vm(self.resource_group, vm_name)
1156 correspondence = next((d for d in vm.storage_profile.data_disks if d.name.lower() == disk.get('name').lower()), None)
1157 caching_options = self.compute_models.CachingTypes[self.attach_caching] if self.attach_caching and self.attach_caching != '' else None
1158 if correspondence and correspondence.caching != caching_options:
1159 resp = True
1160 if correspondence.caching == 'None' and (self.attach_caching == '' or self.attach_caching is None):
1161 resp = False
1162 return resp
1163
1164
1165 def main():
1166 """Main execution"""
1167 AzureRMManagedDisk()
1168
1169
1170 if __name__ == '__main__':
1171 main()