| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
from __future__ import absolute_import, division, print_function |
| 8 |
__metaclass__ = type |
| 9 |
|
| 10 |
|
| 11 |
DOCUMENTATION = ''' |
| 12 |
--- |
| 13 |
module: azure_rm_multiplemanageddisks |
| 14 |
|
| 15 |
version_added: "1.14.0" |
| 16 |
|
| 17 |
short_description: Manage Multiple Azure Manage Disks |
| 18 |
|
| 19 |
description: |
| 20 |
- Create, update and delete one or more Azure Managed Disk. |
| 21 |
- This module can be used also to attach/detach disks to/from one or more virtual machines. |
| 22 |
|
| 23 |
options: |
| 24 |
state: |
| 25 |
description: |
| 26 |
- Assert the state of the managed disks. |
| 27 |
- Use C(present) to create or update managed disks and/or attach/detach managed disks to a list of |
| 28 |
VMs depending on the value specified in I(managed_by_extended). |
| 29 |
- Use C(absent) to detach/delete managed disks depending on the value specified in I(managed_by_extended). |
| 30 |
default: present |
| 31 |
type: str |
| 32 |
choices: |
| 33 |
- absent |
| 34 |
- present |
| 35 |
managed_disks: |
| 36 |
description: |
| 37 |
- List of managed disks to create, update, or delete. |
| 38 |
type: list |
| 39 |
elements: dict |
| 40 |
suboptions: |
| 41 |
resource_group: |
| 42 |
description: |
| 43 |
- Name of a resource group where the managed disk exists or will be created. |
| 44 |
required: true |
| 45 |
type: str |
| 46 |
name: |
| 47 |
description: |
| 48 |
- Name of the managed disk. |
| 49 |
required: true |
| 50 |
type: str |
| 51 |
location: |
| 52 |
description: |
| 53 |
- Valid Azure location. Defaults to location of the resource group. |
| 54 |
type: str |
| 55 |
storage_account_type: |
| 56 |
description: |
| 57 |
- Type of storage for the managed disk. |
| 58 |
- If not specified, the disk is created as C(Standard_LRS). |
| 59 |
- C(Standard_LRS) is for Standard HDD. |
| 60 |
- C(StandardSSD_LRS) (added in 2.8) is for Standard SSD. |
| 61 |
- C(StandardSSD_ZRS) is for Standard SSD Zone-redundant. |
| 62 |
- C(Premium_LRS) is for Premium SSD. |
| 63 |
- C(Premium_ZRS) is for Premium SSD Zone-redundant. |
| 64 |
- C(UltraSSD_LRS) (added in 2.8) is for Ultra SSD, which is only available on select instance types. |
| 65 |
- See U(https://docs.microsoft.com/en-us/azure/virtual-machines/windows/disks-types) for more information about disk types. |
| 66 |
choices: |
| 67 |
- Standard_LRS |
| 68 |
- StandardSSD_LRS |
| 69 |
- StandardSSD_ZRS |
| 70 |
- Premium_LRS |
| 71 |
- Premium_ZRS |
| 72 |
- UltraSSD_LRS |
| 73 |
type: str |
| 74 |
create_option: |
| 75 |
description: |
| 76 |
- C(import) from a VHD file in I(source_uri) and C(copy) from previous managed disk I(source_uri). |
| 77 |
type: str |
| 78 |
choices: |
| 79 |
- empty |
| 80 |
- import |
| 81 |
- copy |
| 82 |
storage_account_id: |
| 83 |
description: |
| 84 |
- The full path to the storage account the image is to be imported from. |
| 85 |
- Required when I(create_option=import). |
| 86 |
type: str |
| 87 |
source_uri: |
| 88 |
description: |
| 89 |
- URI to a valid VHD file to be used or the resource ID of the managed disk to copy. |
| 90 |
- Required when I(create_option=import) or I(create_option=copy). |
| 91 |
aliases: |
| 92 |
- source_resource_uri |
| 93 |
type: str |
| 94 |
os_type: |
| 95 |
description: |
| 96 |
- Type of Operating System. |
| 97 |
- Used when I(create_option=copy) or I(create_option=import) and the source is an OS disk. |
| 98 |
- If omitted during creation, no value is set. |
| 99 |
- If omitted during an update, no change is made. |
| 100 |
- Once set, this value cannot be cleared. |
| 101 |
choices: |
| 102 |
- linux |
| 103 |
- windows |
| 104 |
- Linux |
| 105 |
- Windows |
| 106 |
type: str |
| 107 |
disk_size_gb: |
| 108 |
description: |
| 109 |
- Size in GB of the managed disk to be created. |
| 110 |
- Required when I(create_option=empty). |
| 111 |
- If I(create_option=copy) then the value must be greater than or equal to the source's size. |
| 112 |
type: int |
| 113 |
max_shares: |
| 114 |
description: |
| 115 |
- The maximum number of VMs that can attach to the disk at the same time. |
| 116 |
- Value greater than one indicates a disk that can be mounted on multiple VMs at the same time. |
| 117 |
type: int |
| 118 |
attach_caching: |
| 119 |
description: |
| 120 |
- Disk caching policy controlled by VM. Will be used when attached to the VM defined by C(managed_by). |
| 121 |
- If this option is different from the current caching policy, the managed disk will be deattached |
| 122 |
and attached with current caching option again. |
| 123 |
choices: |
| 124 |
- '' |
| 125 |
- read_only |
| 126 |
- read_write |
| 127 |
type: str |
| 128 |
zone: |
| 129 |
description: |
| 130 |
- The Azure managed disk's zone. |
| 131 |
- Allowed values are C(1), C(2), C(3) and C(''). |
| 132 |
choices: |
| 133 |
- '1' |
| 134 |
- '2' |
| 135 |
- '3' |
| 136 |
- '' |
| 137 |
type: str |
| 138 |
lun: |
| 139 |
description: |
| 140 |
- The logical unit number for data disk. |
| 141 |
- This value is used to identify data disks within the VM and therefore must be unique for each data disk attached to a VM. |
| 142 |
type: int |
| 143 |
managed_by_extended: |
| 144 |
description: |
| 145 |
- List of name and resource group of the VMs to managed disks. |
| 146 |
- When I(state=present), the disks will be attached to the list of VMs specified. |
| 147 |
- When I(state=present), use I([]) to detach disks from all the VMs. |
| 148 |
- When I(state=absent) and this parameter is defined, the disks will be detached from the list of VMs. |
| 149 |
- When I(state=absent) and this parameter is not defined, the disks will be deleted. |
| 150 |
type: list |
| 151 |
elements: dict |
| 152 |
suboptions: |
| 153 |
resource_group: |
| 154 |
description: |
| 155 |
- The resource group of the attache VM. |
| 156 |
type: str |
| 157 |
name: |
| 158 |
description: |
| 159 |
- The name of the attache VM. |
| 160 |
type: str |
| 161 |
|
| 162 |
extends_documentation_fragment: |
| 163 |
- azure.azcollection.azure |
| 164 |
- azure.azcollection.azure_tags |
| 165 |
author: |
| 166 |
- Aubin Bikouo (@abikouo) |
| 167 |
''' |
| 168 |
|
| 169 |
EXAMPLES = ''' |
| 170 |
- name: Create managed operating system disks from page blob and attach them to a list of VMs |
| 171 |
azure_rm_multiplemanageddisks: |
| 172 |
managed_disks: |
| 173 |
- name: mymanageddisk1 |
| 174 |
location: eastus2 |
| 175 |
resource_group: myResourceGroup |
| 176 |
create_option: import |
| 177 |
source_uri: https://storageaccountname.blob.core.windows.net/containername/blob-name.vhd |
| 178 |
storage_account_id: /subscriptions/<uuid>/resourceGroups/myResourceGroup/providers/Microsoft.Storage/storageAccounts/storageaccountname |
| 179 |
os_type: windows |
| 180 |
storage_account_type: Premium_LRS |
| 181 |
- name: mymanageddisk2 |
| 182 |
location: eastus2 |
| 183 |
resource_group: myResourceGroup |
| 184 |
create_option: import |
| 185 |
source_uri: https://storageaccountname.blob.core.windows.net/containername/blob-name.vhd |
| 186 |
storage_account_id: /subscriptions/<uuid>/resourceGroups/myResourceGroup/providers/Microsoft.Storage/storageAccounts/storageaccountname |
| 187 |
os_type: windows |
| 188 |
storage_account_type: Premium_LRS |
| 189 |
managed_by_extended: |
| 190 |
- resource_group: myResourceGroupTest |
| 191 |
name: TestVM |
| 192 |
|
| 193 |
- name: Detach disks from the VMs specified in the list |
| 194 |
azure_rm_multiplemanageddisks: |
| 195 |
state: absent |
| 196 |
managed_disks: |
| 197 |
- name: mymanageddisk1 |
| 198 |
location: eastus2 |
| 199 |
resource_group: myResourceGroup |
| 200 |
create_option: import |
| 201 |
source_uri: https://storageaccountname.blob.core.windows.net/containername/blob-name.vhd |
| 202 |
storage_account_id: /subscriptions/<uuid>/resourceGroups/myResourceGroup/providers/Microsoft.Storage/storageAccounts/storageaccountname |
| 203 |
os_type: windows |
| 204 |
storage_account_type: Premium_LRS |
| 205 |
- name: mymanageddisk2 |
| 206 |
location: eastus2 |
| 207 |
resource_group: myResourceGroup |
| 208 |
create_option: import |
| 209 |
source_uri: https://storageaccountname.blob.core.windows.net/containername/blob-name.vhd |
| 210 |
storage_account_id: /subscriptions/<uuid>/resourceGroups/myResourceGroup/providers/Microsoft.Storage/storageAccounts/storageaccountname |
| 211 |
os_type: windows |
| 212 |
storage_account_type: Premium_LRS |
| 213 |
managed_by_extended: |
| 214 |
- resource_group: myResourceGroupTest |
| 215 |
name: TestVM1 |
| 216 |
- resource_group: myResourceGroupTest |
| 217 |
name: TestVM2 |
| 218 |
|
| 219 |
- name: Detach managed disks from all VMs without deletion |
| 220 |
azure_rm_multiplemanageddisks: |
| 221 |
state: present |
| 222 |
managed_disks: |
| 223 |
- name: mymanageddisk1 |
| 224 |
location: eastus2 |
| 225 |
resource_group: myResourceGroup |
| 226 |
- name: mymanageddisk2 |
| 227 |
location: eastus2 |
| 228 |
resource_group: myResourceGroup |
| 229 |
managed_by_extended: [] |
| 230 |
|
| 231 |
- name: Detach managed disks from all VMs and delete them |
| 232 |
azure_rm_multiplemanageddisks: |
| 233 |
state: absent |
| 234 |
managed_disks: |
| 235 |
- name: mymanageddisk1 |
| 236 |
location: eastus2 |
| 237 |
resource_group: myResourceGroup |
| 238 |
- name: mymanageddisk2 |
| 239 |
location: eastus2 |
| 240 |
resource_group: myResourceGroup |
| 241 |
''' |
| 242 |
|
| 243 |
RETURN = ''' |
| 244 |
state: |
| 245 |
description: |
| 246 |
- Current state of the managed disks. |
| 247 |
returned: always |
| 248 |
type: complex |
| 249 |
contains: |
| 250 |
id: |
| 251 |
description: |
| 252 |
- Resource id. |
| 253 |
type: str |
| 254 |
name: |
| 255 |
description: |
| 256 |
- Name of the managed disk. |
| 257 |
type: str |
| 258 |
location: |
| 259 |
description: |
| 260 |
- Valid Azure location. |
| 261 |
type: str |
| 262 |
storage_account_type: |
| 263 |
description: |
| 264 |
- Type of storage for the managed disk. |
| 265 |
- See U(https://docs.microsoft.com/en-us/azure/virtual-machines/windows/disks-types) for more information about this type. |
| 266 |
type: str |
| 267 |
sample: Standard_LRS |
| 268 |
create_option: |
| 269 |
description: |
| 270 |
- Create option of the disk. |
| 271 |
type: str |
| 272 |
sample: copy |
| 273 |
storage_account_id: |
| 274 |
description: |
| 275 |
- The full path to the storage account the image is to be imported from |
| 276 |
type: str |
| 277 |
sample: /subscriptions/<uuid>/resourceGroups/<resource group name>/providers/Microsoft.Storage/storageAccounts/<storage account name> |
| 278 |
source_uri: |
| 279 |
description: |
| 280 |
- URI to a valid VHD file to be used or the resource ID of the managed disk to copy. |
| 281 |
type: str |
| 282 |
os_type: |
| 283 |
description: |
| 284 |
- Type of Operating System. |
| 285 |
type: str |
| 286 |
sample: linux |
| 287 |
disk_size_gb: |
| 288 |
description: |
| 289 |
- Size in GB of the managed disk to be created. |
| 290 |
type: str |
| 291 |
managed_by: |
| 292 |
description: |
| 293 |
- Name of an existing virtual machine with which the disk is or will be associated, this VM should be in the same resource group. |
| 294 |
type: str |
| 295 |
max_shares: |
| 296 |
description: |
| 297 |
- The maximum number of VMs that can attach to the disk at the same time. |
| 298 |
- Value greater than one indicates a disk that can be mounted on multiple VMs at the same time. |
| 299 |
type: int |
| 300 |
sample: 3 |
| 301 |
managed_by_extended: |
| 302 |
description: |
| 303 |
- List ID of an existing virtual machine with which the disk is or will be associated. |
| 304 |
type: list |
| 305 |
sample: ["/subscriptions/xxx-xxx/resourceGroups/myRG/providers/Microsoft.Compute/virtualMachines/testVM"] |
| 306 |
tags: |
| 307 |
description: |
| 308 |
- Tags to assign to the managed disk. |
| 309 |
type: dict |
| 310 |
sample: { "tag": "value" } |
| 311 |
''' |
| 312 |
|
| 313 |
|
| 314 |
from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase |
| 315 |
try: |
| 316 |
from azure.core.exceptions import ResourceNotFoundError, AzureError |
| 317 |
from azure.mgmt.core.tools import parse_resource_id |
| 318 |
import time |
| 319 |
except ImportError: |
| 320 |
|
| 321 |
pass |
| 322 |
|
| 323 |
|
| 324 |
|
| 325 |
def managed_disk_to_dict(managed_disk): |
| 326 |
create_data = managed_disk.creation_data |
| 327 |
return dict( |
| 328 |
id=managed_disk.id, |
| 329 |
name=managed_disk.name, |
| 330 |
location=managed_disk.location, |
| 331 |
tags=managed_disk.tags, |
| 332 |
create_option=create_data.create_option.lower(), |
| 333 |
source_uri=create_data.source_uri or create_data.source_resource_id, |
| 334 |
disk_size_gb=managed_disk.disk_size_gb, |
| 335 |
os_type=managed_disk.os_type.lower() if managed_disk.os_type else None, |
| 336 |
storage_account_type=managed_disk.sku.name if managed_disk.sku else None, |
| 337 |
managed_by=managed_disk.managed_by, |
| 338 |
max_shares=managed_disk.max_shares, |
| 339 |
managed_by_extended=managed_disk.managed_by_extended, |
| 340 |
zone=managed_disk.zones[0] if managed_disk.zones and len(managed_disk.zones) > 0 else '' |
| 341 |
) |
| 342 |
|
| 343 |
|
| 344 |
class AzureRMMultipleManagedDisk(AzureRMModuleBase): |
| 345 |
"""Configuration class for an Azure RM Managed Disk resource""" |
| 346 |
|
| 347 |
def __init__(self): |
| 348 |
|
| 349 |
managed_by_extended_spec = dict( |
| 350 |
resource_group=dict(type='str'), |
| 351 |
name=dict(type='str') |
| 352 |
) |
| 353 |
managed_disks_spec = dict( |
| 354 |
resource_group=dict( |
| 355 |
type='str', |
| 356 |
required=True |
| 357 |
), |
| 358 |
name=dict( |
| 359 |
type='str', |
| 360 |
required=True |
| 361 |
), |
| 362 |
location=dict( |
| 363 |
type='str' |
| 364 |
), |
| 365 |
storage_account_type=dict( |
| 366 |
type='str', |
| 367 |
choices=['Standard_LRS', 'StandardSSD_LRS', 'StandardSSD_ZRS', 'Premium_LRS', 'Premium_ZRS', 'UltraSSD_LRS'] |
| 368 |
), |
| 369 |
create_option=dict( |
| 370 |
type='str', |
| 371 |
choices=['empty', 'import', 'copy'] |
| 372 |
), |
| 373 |
storage_account_id=dict( |
| 374 |
type='str' |
| 375 |
), |
| 376 |
source_uri=dict( |
| 377 |
type='str', |
| 378 |
aliases=['source_resource_uri'] |
| 379 |
), |
| 380 |
os_type=dict( |
| 381 |
type='str', |
| 382 |
choices=['linux', 'windows', 'Linux', 'Windows'] |
| 383 |
), |
| 384 |
disk_size_gb=dict( |
| 385 |
type='int' |
| 386 |
), |
| 387 |
zone=dict( |
| 388 |
type='str', |
| 389 |
choices=['', '1', '2', '3'] |
| 390 |
), |
| 391 |
attach_caching=dict( |
| 392 |
type='str', |
| 393 |
choices=['', 'read_only', 'read_write'] |
| 394 |
), |
| 395 |
lun=dict( |
| 396 |
type='int' |
| 397 |
), |
| 398 |
max_shares=dict( |
| 399 |
type='int' |
| 400 |
), |
| 401 |
) |
| 402 |
|
| 403 |
self.module_arg_spec = dict( |
| 404 |
state=dict( |
| 405 |
type='str', |
| 406 |
default='present', |
| 407 |
choices=['present', 'absent'] |
| 408 |
), |
| 409 |
managed_disks=dict( |
| 410 |
type='list', |
| 411 |
elements='dict', |
| 412 |
options=managed_disks_spec, |
| 413 |
), |
| 414 |
managed_by_extended=dict( |
| 415 |
type='list', |
| 416 |
elements='dict', |
| 417 |
options=managed_by_extended_spec, |
| 418 |
), |
| 419 |
) |
| 420 |
self.results = dict( |
| 421 |
changed=False, |
| 422 |
state=list()) |
| 423 |
|
| 424 |
super(AzureRMMultipleManagedDisk, self).__init__( |
| 425 |
derived_arg_spec=self.module_arg_spec, |
| 426 |
supports_tags=True) |
| 427 |
|
| 428 |
def validate_disks_parameter(self): |
| 429 |
errors = [] |
| 430 |
create_option_reqs = [ |
| 431 |
('import', ['source_uri', 'storage_account_id']), |
| 432 |
('copy', ['source_uri']), |
| 433 |
('empty', ['disk_size_gb']) |
| 434 |
] |
| 435 |
for disk in self.managed_disks: |
| 436 |
create_option = disk.get("create_option") |
| 437 |
for req in create_option_reqs: |
| 438 |
if create_option == req[0] and any((disk.get(opt) is None for opt in req[1])): |
| 439 |
errors.append("managed disk {0}/{1} has create_option set to {2} but not all required parameters ({3}) are set.".format( |
| 440 |
disk.get("resource_group"), disk.get("name"), req[0], ",".join(req[1]))) |
| 441 |
if errors: |
| 442 |
self.fail(msg="Some required options are missing from managed disks configuration.", errors=errors) |
| 443 |
|
| 444 |
def generate_disk_parameters(self, location, tags, zone=None, |
| 445 |
storage_account_type=None, disk_size_gb=None, create_option=None, |
| 446 |
source_uri=None, storage_account_id=None, os_type=None, max_shares=None, **kwargs): |
| 447 |
disk_params = {} |
| 448 |
creation_data = {} |
| 449 |
disk_params['location'] = location |
| 450 |
disk_params['tags'] = tags |
| 451 |
if zone: |
| 452 |
disk_params['zones'] = [zone] |
| 453 |
if storage_account_type: |
| 454 |
storage = self.multi_disk_models.DiskSku(name=storage_account_type) |
| 455 |
disk_params['sku'] = storage |
| 456 |
disk_params['disk_size_gb'] = disk_size_gb |
| 457 |
creation_data['create_option'] = self.multi_disk_models.DiskCreateOption.empty |
| 458 |
if create_option == 'import': |
| 459 |
creation_data['create_option'] = self.multi_disk_models.DiskCreateOption.import_enum |
| 460 |
creation_data['source_uri'] = source_uri |
| 461 |
creation_data['storage_account_id'] = storage_account_id |
| 462 |
elif create_option == 'copy': |
| 463 |
creation_data['create_option'] = self.multi_disk_models.DiskCreateOption.copy |
| 464 |
creation_data['source_resource_id'] = source_uri |
| 465 |
if os_type: |
| 466 |
disk_params['os_type'] = self.multi_disk_models.OperatingSystemTypes(os_type.capitalize()) |
| 467 |
else: |
| 468 |
disk_params['os_type'] = None |
| 469 |
if max_shares: |
| 470 |
disk_params['max_shares'] = max_shares |
| 471 |
disk_params['creation_data'] = creation_data |
| 472 |
return disk_params |
| 473 |
|
| 474 |
def get_disk_instance(self, managed_disk): |
| 475 |
resource_group = self.get_resource_group(managed_disk.get("resource_group")) |
| 476 |
managed_disk["location"] = managed_disk.get("location") or resource_group.location |
| 477 |
disk_instance = self.get_managed_disk(resource_group=managed_disk.get("resource_group"), name=managed_disk.get("name")) |
| 478 |
if disk_instance is not None: |
| 479 |
for key in ("create_option", 'source_uri', 'disk_size_gb', 'os_type', 'zone'): |
| 480 |
if managed_disk.get(key) is None: |
| 481 |
managed_disk[key] = disk_instance.get(key) |
| 482 |
parameter = self.generate_disk_parameters(tags=self.tags, **managed_disk) |
| 483 |
|
| 484 |
return parameter, disk_instance |
| 485 |
|
| 486 |
def exec_module(self, **kwargs): |
| 487 |
"""Main module execution method""" |
| 488 |
self.tags = kwargs.get("tags") |
| 489 |
|
| 490 |
state = kwargs.get("state") |
| 491 |
self.managed_disks = kwargs.get("managed_disks") |
| 492 |
self.managed_by_extended = kwargs.get("managed_by_extended") |
| 493 |
|
| 494 |
self.validate_disks_parameter() |
| 495 |
|
| 496 |
managed_vm_id = [] |
| 497 |
if self.managed_by_extended: |
| 498 |
managed_vm_id = [self._get_vm(vm['resource_group'], vm['name']) for vm in self.managed_by_extended] |
| 499 |
|
| 500 |
if state == "present": |
| 501 |
return self.create_or_attach_disks(managed_vm_id) |
| 502 |
elif state == "absent": |
| 503 |
return self.detach_or_delete_disks(managed_vm_id) |
| 504 |
|
| 505 |
def compute_disks_result(self, disk_instances): |
| 506 |
result = [] |
| 507 |
for params, disk in disk_instances: |
| 508 |
disk_id = parse_resource_id(disk.get("id")) |
| 509 |
result.append(self.get_managed_disk(resource_group=disk_id.get("resource_group"), name=disk_id.get("resource_name"))) |
| 510 |
return result |
| 511 |
|
| 512 |
def create_or_attach_disks(self, managed_vm_id): |
| 513 |
changed, disk_instances, disks_to_create = False, [], [] |
| 514 |
for disk in self.managed_disks: |
| 515 |
parameter, disk_instance = self.get_disk_instance(disk) |
| 516 |
|
| 517 |
disk_info_to_compare = dict(zone=disk.get("zone"), max_shares=disk.get("max_shares"), found_disk=disk_instance, new_disk=parameter) |
| 518 |
if disk_instance is None or self.is_different(**disk_info_to_compare): |
| 519 |
disks_to_create.append((disk, parameter)) |
| 520 |
else: |
| 521 |
disk_instances.append((disk, disk_instance)) |
| 522 |
|
| 523 |
if len(disks_to_create) > 0: |
| 524 |
changed = True |
| 525 |
result = self.create_or_update_disks(disks_to_create) |
| 526 |
disk_instances += result |
| 527 |
|
| 528 |
if self.managed_by_extended is not None and len(self.managed_by_extended) > 0: |
| 529 |
|
| 530 |
attach_config = [] |
| 531 |
for vm in managed_vm_id: |
| 532 |
time.sleep(5) |
| 533 |
disks = [(d, i) for d, i in disk_instances if not self._is_disk_attached_to_vm(vm.id, i)] |
| 534 |
if len(disks) > 0: |
| 535 |
attach_config.append(self.create_attachment_configuration(vm, disks)) |
| 536 |
|
| 537 |
if len(attach_config) > 0: |
| 538 |
changed = True |
| 539 |
self.update_virtual_machines(attach_config) |
| 540 |
|
| 541 |
elif self.managed_by_extended == []: |
| 542 |
|
| 543 |
changed = self.detach_disks_from_all_vms(disk_instances) or changed |
| 544 |
|
| 545 |
return dict(changed=changed, state=self.compute_disks_result(disk_instances)) |
| 546 |
|
| 547 |
def detach_or_delete_disks(self, managed_vm_id): |
| 548 |
changed, disk_instances = False, [] |
| 549 |
for disk in self.managed_disks: |
| 550 |
params, disk_instance = self.get_disk_instance(disk) |
| 551 |
if disk_instance is not None: |
| 552 |
disk_instances.append((disk, disk_instance)) |
| 553 |
|
| 554 |
result = [] |
| 555 |
if self.managed_by_extended is not None and len(self.managed_by_extended) > 0: |
| 556 |
|
| 557 |
disks_names = [d.get("name").lower() for p, d in disk_instances] |
| 558 |
attach_config = [] |
| 559 |
for vm in managed_vm_id: |
| 560 |
disks = [d for p, d in disk_instances if self._is_disk_attached_to_vm(vm.id, d)] |
| 561 |
if len(disks) > 0: |
| 562 |
attach_config.append(self.create_detachment_configuration(vm, disks_names)) |
| 563 |
|
| 564 |
if len(attach_config) > 0: |
| 565 |
changed = True |
| 566 |
self.update_virtual_machines(attach_config) |
| 567 |
result = self.compute_disks_result(disk_instances) |
| 568 |
|
| 569 |
elif self.managed_by_extended is None: |
| 570 |
|
| 571 |
changed = self.detach_disks_from_all_vms(disk_instances) |
| 572 |
|
| 573 |
|
| 574 |
if len(disk_instances) > 0: |
| 575 |
disks_ids = [disk.get("id") for param, disk in disk_instances] |
| 576 |
changed = True |
| 577 |
self.delete_disks(disks_ids) |
| 578 |
|
| 579 |
return dict(changed=changed, state=result) |
| 580 |
|
| 581 |
def detach_disks_from_all_vms(self, disk_instances): |
| 582 |
changed = False |
| 583 |
|
| 584 |
unique_vm_id = [] |
| 585 |
for param, disk_instance in disk_instances: |
| 586 |
managed_by_vm = disk_instance.get("managed_by") |
| 587 |
managed_by_extended_vms = disk_instance.get("managed_by_extended") or [] |
| 588 |
if managed_by_vm is not None and managed_by_vm not in unique_vm_id: |
| 589 |
unique_vm_id.append(managed_by_vm) |
| 590 |
for vm_id in managed_by_extended_vms: |
| 591 |
if vm_id not in unique_vm_id: |
| 592 |
unique_vm_id.append(vm_id) |
| 593 |
if unique_vm_id: |
| 594 |
disks_names = [instance.get("name").lower() for d, instance in disk_instances] |
| 595 |
changed = True |
| 596 |
attach_config = [] |
| 597 |
for vm_id in unique_vm_id: |
| 598 |
vm_name_id = parse_resource_id(vm_id) |
| 599 |
vm_instance = self._get_vm(vm_name_id['resource_group'], vm_name_id['resource_name']) |
| 600 |
attach_config.append(self.create_detachment_configuration(vm_instance, disks_names)) |
| 601 |
|
| 602 |
if len(attach_config) > 0: |
| 603 |
changed = True |
| 604 |
self.update_virtual_machines(attach_config) |
| 605 |
return changed |
| 606 |
|
| 607 |
def _is_disk_attached_to_vm(self, vm_id, item): |
| 608 |
managed_by = item['managed_by'] |
| 609 |
managed_by_extended = item['managed_by_extended'] |
| 610 |
if managed_by is not None and vm_id == managed_by: |
| 611 |
return True |
| 612 |
if managed_by_extended is not None and vm_id in managed_by_extended: |
| 613 |
return True |
| 614 |
return False |
| 615 |
|
| 616 |
def create_attachment_configuration(self, vm, disks): |
| 617 |
vm_id = parse_resource_id(vm.id) |
| 618 |
|
| 619 |
|
| 620 |
for managed_disk, disk_instance in disks: |
| 621 |
lun = managed_disk.get("lun") |
| 622 |
if lun is None: |
| 623 |
luns = ([d.lun for d in vm.storage_profile.data_disks] if vm.storage_profile.data_disks else []) |
| 624 |
lun = 0 |
| 625 |
while True: |
| 626 |
if lun not in luns: |
| 627 |
break |
| 628 |
lun = lun + 1 |
| 629 |
for item in vm.storage_profile.data_disks: |
| 630 |
if item.name == managed_disk.get("name"): |
| 631 |
lun = item.lun |
| 632 |
|
| 633 |
|
| 634 |
params = self.multi_disk_models.ManagedDiskParameters(id=disk_instance.get('id'), storage_account_type=disk_instance.get('storage_account_type')) |
| 635 |
attach_caching = managed_disk.get("attach_caching") |
| 636 |
caching_options = self.multi_disk_models.CachingTypes[attach_caching] if attach_caching and attach_caching != '' else None |
| 637 |
|
| 638 |
|
| 639 |
data_disk = self.multi_disk_models.DataDisk(lun=lun, |
| 640 |
create_option=self.compute_models.DiskCreateOptionTypes.attach, |
| 641 |
managed_disk=params, |
| 642 |
caching=caching_options) |
| 643 |
vm.storage_profile.data_disks.append(data_disk) |
| 644 |
return vm_id["resource_group"], vm_id["resource_name"], vm |
| 645 |
|
| 646 |
def create_detachment_configuration(self, vm_instance, disks_names): |
| 647 |
vm_data = parse_resource_id(vm_instance.id) |
| 648 |
leftovers = [d for d in vm_instance.storage_profile.data_disks if d.name.lower() not in disks_names] |
| 649 |
if len(vm_instance.storage_profile.data_disks) == len(leftovers): |
| 650 |
self.fail("None of the following disks '{0}' are attached to the VM '{1}/{2}'.".format( |
| 651 |
disks_names, vm_data["resource_group"], vm_data["resource_name"] |
| 652 |
)) |
| 653 |
vm_instance.storage_profile.data_disks = leftovers |
| 654 |
return vm_data["resource_group"], vm_data["resource_name"], vm_instance |
| 655 |
|
| 656 |
def _get_vm(self, resource_group, name): |
| 657 |
try: |
| 658 |
return self.compute_client.virtual_machines.get(resource_group, name, expand='instanceview') |
| 659 |
except Exception as exc: |
| 660 |
self.fail("Error getting virtual machine {0}/{1} - {2}".format(resource_group, name, str(exc))) |
| 661 |
|
| 662 |
def create_or_update_disks(self, disks_to_create): |
| 663 |
pollers = [] |
| 664 |
for disk_info, disk in disks_to_create: |
| 665 |
resource_group = disk_info.get("resource_group") |
| 666 |
name = disk_info.get("name") |
| 667 |
try: |
| 668 |
poller = self.multi_disk_client.disks.begin_create_or_update(resource_group, name, disk) |
| 669 |
pollers.append(poller) |
| 670 |
except Exception as e: |
| 671 |
self.fail("Error creating the managed disk {0}/{1}: {2}".format(resource_group, name, str(e))) |
| 672 |
disks_instances = self.get_multiple_pollers_results(pollers) |
| 673 |
result = [] |
| 674 |
for i, instance in enumerate(disks_instances): |
| 675 |
result.append((disks_to_create[i][0], managed_disk_to_dict(instance))) |
| 676 |
return result |
| 677 |
|
| 678 |
|
| 679 |
|
| 680 |
def is_different(self, zone, max_shares, found_disk, new_disk): |
| 681 |
resp = False |
| 682 |
if new_disk.get('disk_size_gb'): |
| 683 |
if not found_disk['disk_size_gb'] == new_disk['disk_size_gb']: |
| 684 |
resp = True |
| 685 |
if new_disk.get('os_type'): |
| 686 |
if found_disk['os_type'] is None or not self.multi_disk_models.OperatingSystemTypes(found_disk['os_type'].capitalize()) == new_disk['os_type']: |
| 687 |
resp = True |
| 688 |
if new_disk.get('sku'): |
| 689 |
if not found_disk['storage_account_type'] == new_disk['sku'].name: |
| 690 |
resp = True |
| 691 |
|
| 692 |
if new_disk.get('tags') is not None: |
| 693 |
if not found_disk['tags'] == new_disk['tags']: |
| 694 |
resp = True |
| 695 |
if zone is not None: |
| 696 |
if not found_disk['zone'] == zone: |
| 697 |
resp = True |
| 698 |
if max_shares is not None: |
| 699 |
if not found_disk['max_shares'] == max_shares: |
| 700 |
resp = True |
| 701 |
return resp |
| 702 |
|
| 703 |
def delete_disks(self, ids): |
| 704 |
pollers = [] |
| 705 |
for disk_id in ids: |
| 706 |
try: |
| 707 |
disk = parse_resource_id(disk_id) |
| 708 |
resource_group, name = disk.get("resource_group"), disk.get("resource_name") |
| 709 |
poller = self.multi_disk_client.disks.begin_delete(resource_group, name) |
| 710 |
pollers.append(poller) |
| 711 |
except Exception as e: |
| 712 |
self.fail("Error deleting the managed disk {0}/{1}: {2}".format(resource_group, name, str(e))) |
| 713 |
return self.get_multiple_pollers_results(pollers) |
| 714 |
|
| 715 |
def update_virtual_machines(self, config): |
| 716 |
pollers = [] |
| 717 |
for resource_group, name, params in config: |
| 718 |
try: |
| 719 |
poller = self.compute_client.virtual_machines.begin_create_or_update(resource_group, name, params) |
| 720 |
pollers.append(poller) |
| 721 |
except AzureError as exc: |
| 722 |
self.fail("Error updating virtual machine (attaching/detaching disks) {0}/{1} - {2}".format(resource_group, name, exc.message)) |
| 723 |
return self.get_multiple_pollers_results(pollers) |
| 724 |
|
| 725 |
def get_managed_disk(self, resource_group, name): |
| 726 |
try: |
| 727 |
resp = self.multi_disk_client.disks.get(resource_group, name) |
| 728 |
return managed_disk_to_dict(resp) |
| 729 |
except ResourceNotFoundError: |
| 730 |
self.log("Did not find managed disk {0}/{1}".format(resource_group, name)) |
| 731 |
|
| 732 |
|
| 733 |
def main(): |
| 734 |
"""Main execution""" |
| 735 |
AzureRMMultipleManagedDisk() |
| 736 |
|
| 737 |
|
| 738 |
if __name__ == '__main__': |
| 739 |
main() |