| 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_image |
| 14 |
version_added: "0.0.1" |
| 15 |
short_description: Manage Azure image |
| 16 |
description: |
| 17 |
- Create, delete an image from virtual machine, blob uri, managed disk or snapshot. |
| 18 |
options: |
| 19 |
resource_group: |
| 20 |
description: |
| 21 |
- Name of resource group. |
| 22 |
required: true |
| 23 |
type: str |
| 24 |
name: |
| 25 |
description: |
| 26 |
- Name of the image. |
| 27 |
required: true |
| 28 |
type: str |
| 29 |
source: |
| 30 |
description: |
| 31 |
- OS disk source from the same region. |
| 32 |
- It can be a virtual machine, OS disk blob URI, managed OS disk, or OS snapshot. |
| 33 |
- Each type of source except for blob URI can be given as resource id, name or a dict contains C(resource_group), C(name) and C(type). |
| 34 |
- If source type is blob URI, the source should be the full URI of the blob in string type. |
| 35 |
- If you specify the I(type) in a dict, acceptable value contains C(disks), C(virtual_machines) and C(snapshots). |
| 36 |
type: raw |
| 37 |
data_disk_sources: |
| 38 |
description: |
| 39 |
- List of data disk sources, including unmanaged blob URI, managed disk id or name, or snapshot id or name. |
| 40 |
type: list |
| 41 |
elements: str |
| 42 |
default: [] |
| 43 |
os_disk_encryption_set: |
| 44 |
description: |
| 45 |
- The resource ID of the disk encryption set for the OS disk. |
| 46 |
type: str |
| 47 |
data_disk_encryption_set: |
| 48 |
description: |
| 49 |
- The resource ID of the disk encryption set for the data disks. |
| 50 |
type: str |
| 51 |
location: |
| 52 |
description: |
| 53 |
- Location of the image. Derived from I(resource_group) if not specified. |
| 54 |
type: str |
| 55 |
os_type: |
| 56 |
description: The OS type of image. |
| 57 |
choices: |
| 58 |
- Windows |
| 59 |
- Linux |
| 60 |
- windows |
| 61 |
- linux |
| 62 |
type: str |
| 63 |
hyper_v_generation: |
| 64 |
description: |
| 65 |
- Specifies the HyperVGenerationType of the VirtualMachine created from the image. |
| 66 |
type: str |
| 67 |
choices: |
| 68 |
- V1 |
| 69 |
- V2 |
| 70 |
state: |
| 71 |
description: |
| 72 |
- Assert the state of the image. Use C(present) to create or update a image and C(absent) to delete an image. |
| 73 |
default: present |
| 74 |
type: str |
| 75 |
choices: |
| 76 |
- absent |
| 77 |
- present |
| 78 |
|
| 79 |
extends_documentation_fragment: |
| 80 |
- azure.azcollection.azure |
| 81 |
- azure.azcollection.azure_tags |
| 82 |
|
| 83 |
author: |
| 84 |
- Yuwei Zhou (@yuwzho) |
| 85 |
|
| 86 |
''' |
| 87 |
|
| 88 |
EXAMPLES = ''' |
| 89 |
- name: Create an image from a virtual machine |
| 90 |
azure_rm_image: |
| 91 |
resource_group: myResourceGroup |
| 92 |
name: myImage |
| 93 |
source: myVirtualMachine |
| 94 |
|
| 95 |
- name: Create an image from os disk |
| 96 |
azure_rm_image: |
| 97 |
resource_group: myResourceGroup |
| 98 |
name: myImage |
| 99 |
source: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroup/myResourceGroup/providers/Microsoft.Compute/disks/disk001 |
| 100 |
data_disk_sources: |
| 101 |
- datadisk001 |
| 102 |
- datadisk002 |
| 103 |
os_type: Linux |
| 104 |
|
| 105 |
- name: Create an image from os disk via dict |
| 106 |
azure_rm_image: |
| 107 |
resource_group: myResourceGroup |
| 108 |
name: myImage |
| 109 |
source: |
| 110 |
type: disks |
| 111 |
resource_group: myResourceGroup |
| 112 |
name: disk001 |
| 113 |
data_disk_sources: |
| 114 |
- datadisk001 |
| 115 |
- datadisk002 |
| 116 |
os_type: Linux |
| 117 |
|
| 118 |
- name: Delete an image |
| 119 |
azure_rm_image: |
| 120 |
state: absent |
| 121 |
resource_group: myResourceGroup |
| 122 |
name: myImage |
| 123 |
source: testvm001 |
| 124 |
''' |
| 125 |
|
| 126 |
RETURN = ''' |
| 127 |
id: |
| 128 |
description: |
| 129 |
- Image resource path. |
| 130 |
type: str |
| 131 |
returned: success |
| 132 |
sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroup/myResourceGroup/providers/Microsoft.Compute/images/myImage" |
| 133 |
''' |
| 134 |
|
| 135 |
from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase, format_resource_id |
| 136 |
|
| 137 |
try: |
| 138 |
from azure.mgmt.core.tools import parse_resource_id |
| 139 |
from azure.core.exceptions import ResourceNotFoundError |
| 140 |
except ImportError: |
| 141 |
|
| 142 |
pass |
| 143 |
|
| 144 |
|
| 145 |
class AzureRMImage(AzureRMModuleBase): |
| 146 |
|
| 147 |
def __init__(self): |
| 148 |
|
| 149 |
self.module_arg_spec = dict( |
| 150 |
resource_group=dict(type='str', required=True), |
| 151 |
name=dict(type='str', required=True), |
| 152 |
state=dict(type='str', default='present', choices=['present', 'absent']), |
| 153 |
location=dict(type='str'), |
| 154 |
source=dict(type='raw'), |
| 155 |
data_disk_sources=dict(type='list', elements='str', default=[]), |
| 156 |
os_disk_encryption_set=dict(type='str'), |
| 157 |
data_disk_encryption_set=dict(type='str'), |
| 158 |
os_type=dict(type='str', choices=['Windows', 'Linux', 'windows', 'linux']), |
| 159 |
hyper_v_generation=dict(type='str', choices=['V1', 'V2']) |
| 160 |
) |
| 161 |
|
| 162 |
self.results = dict( |
| 163 |
changed=False, |
| 164 |
id=None |
| 165 |
) |
| 166 |
|
| 167 |
required_if = [ |
| 168 |
('state', 'present', ['source']) |
| 169 |
] |
| 170 |
|
| 171 |
self.resource_group = None |
| 172 |
self.name = None |
| 173 |
self.state = None |
| 174 |
self.location = None |
| 175 |
self.source = None |
| 176 |
self.data_disk_sources = None |
| 177 |
self.os_disk_encryption_set = None |
| 178 |
self.data_disk_encryption_set = None |
| 179 |
self.os_type = None |
| 180 |
self.hyper_v_generation = None |
| 181 |
|
| 182 |
super(AzureRMImage, self).__init__(self.module_arg_spec, supports_check_mode=True, required_if=required_if) |
| 183 |
|
| 184 |
def exec_module(self, **kwargs): |
| 185 |
|
| 186 |
for key in list(self.module_arg_spec.keys()) + ['tags']: |
| 187 |
setattr(self, key, kwargs[key]) |
| 188 |
|
| 189 |
results = None |
| 190 |
changed = False |
| 191 |
image = None |
| 192 |
|
| 193 |
if not self.location: |
| 194 |
|
| 195 |
resource_group = self.get_resource_group(self.resource_group) |
| 196 |
self.location = resource_group.location |
| 197 |
|
| 198 |
self.log('Fetching image {0}'.format(self.name)) |
| 199 |
image = self.get_image() |
| 200 |
if image: |
| 201 |
self.check_provisioning_state(image, self.state) |
| 202 |
results = image.id |
| 203 |
|
| 204 |
update_tags, tags = self.update_tags(image.tags) |
| 205 |
if update_tags: |
| 206 |
changed = True |
| 207 |
self.tags = tags |
| 208 |
if self.hyper_v_generation and self.hyper_v_generation != image.hyper_v_generation: |
| 209 |
self.log("Compare configure Check whether hyper_v_generation needs to be updated") |
| 210 |
self.fail("The hyper_v_generation parameter cannot be updated to {0}".format(self.hyper_v_generation)) |
| 211 |
else: |
| 212 |
self.hyper_v_generation = image.hyper_v_generation |
| 213 |
if self.state == 'absent': |
| 214 |
changed = True |
| 215 |
|
| 216 |
elif self.state == 'present': |
| 217 |
changed = True |
| 218 |
|
| 219 |
self.results['changed'] = changed |
| 220 |
self.results['id'] = results |
| 221 |
|
| 222 |
if changed: |
| 223 |
if self.state == 'present': |
| 224 |
image_instance = None |
| 225 |
|
| 226 |
vm = self.get_source_vm() |
| 227 |
if vm: |
| 228 |
if self.data_disk_sources: |
| 229 |
self.fail('data_disk_sources is not allowed when capturing image from vm') |
| 230 |
image_instance = self.image_models.Image(location=self.location, |
| 231 |
source_virtual_machine=self.image_models.SubResource(id=vm.id), |
| 232 |
hyper_v_generation=self.hyper_v_generation, |
| 233 |
tags=self.tags) |
| 234 |
else: |
| 235 |
if not self.os_type: |
| 236 |
self.fail('os_type is required to create the image') |
| 237 |
os_disk = self.create_os_disk() |
| 238 |
data_disks = self.create_data_disks() |
| 239 |
storage_profile = self.image_models.ImageStorageProfile(os_disk=os_disk, data_disks=data_disks) |
| 240 |
image_instance = self.image_models.Image( |
| 241 |
location=self.location, |
| 242 |
storage_profile=storage_profile, |
| 243 |
hyper_v_generation=self.hyper_v_generation, |
| 244 |
tags=self.tags |
| 245 |
) |
| 246 |
|
| 247 |
|
| 248 |
if not self.check_mode and image_instance: |
| 249 |
new_image = self.create_image(image_instance) |
| 250 |
self.results['id'] = new_image.id |
| 251 |
|
| 252 |
elif self.state == 'absent': |
| 253 |
if not self.check_mode: |
| 254 |
|
| 255 |
self.delete_image() |
| 256 |
|
| 257 |
self.results['id'] = None |
| 258 |
|
| 259 |
return self.results |
| 260 |
|
| 261 |
def resolve_storage_source(self, source): |
| 262 |
blob_uri = None |
| 263 |
disk = None |
| 264 |
snapshot = None |
| 265 |
|
| 266 |
if isinstance(source, str) and source.lower().endswith('.vhd'): |
| 267 |
blob_uri = source |
| 268 |
return (blob_uri, disk, snapshot) |
| 269 |
|
| 270 |
tokenize = dict() |
| 271 |
if isinstance(source, dict): |
| 272 |
tokenize = source |
| 273 |
elif isinstance(source, str): |
| 274 |
tokenize = parse_resource_id(source) |
| 275 |
else: |
| 276 |
self.fail("source parameter should be in type string or dictionary") |
| 277 |
if tokenize.get('type') == 'disks': |
| 278 |
disk = format_resource_id(tokenize['name'], |
| 279 |
tokenize.get('subscription') or self.subscription_id, |
| 280 |
'Microsoft.Compute', |
| 281 |
'disks', |
| 282 |
tokenize.get('resource_group') or self.resource_group) |
| 283 |
return (blob_uri, disk, snapshot) |
| 284 |
|
| 285 |
if tokenize.get('type') == 'snapshots': |
| 286 |
snapshot = format_resource_id(tokenize['name'], |
| 287 |
tokenize.get('subscription') or self.subscription_id, |
| 288 |
'Microsoft.Compute', |
| 289 |
'snapshots', |
| 290 |
tokenize.get('resource_group') or self.resource_group) |
| 291 |
return (blob_uri, disk, snapshot) |
| 292 |
|
| 293 |
|
| 294 |
if 'type' in tokenize: |
| 295 |
return (blob_uri, disk, snapshot) |
| 296 |
|
| 297 |
|
| 298 |
snapshot_instance = self.get_snapshot(tokenize.get('resource_group') or self.resource_group, |
| 299 |
tokenize['name']) |
| 300 |
if snapshot_instance: |
| 301 |
snapshot = snapshot_instance.id |
| 302 |
return (blob_uri, disk, snapshot) |
| 303 |
|
| 304 |
disk_instance = self.get_disk(tokenize.get('resource_group') or self.resource_group, |
| 305 |
tokenize['name']) |
| 306 |
if disk_instance: |
| 307 |
disk = disk_instance.id |
| 308 |
return (blob_uri, disk, snapshot) |
| 309 |
|
| 310 |
def create_os_disk(self): |
| 311 |
blob_uri, disk, snapshot = self.resolve_storage_source(self.source) |
| 312 |
snapshot_resource = self.image_models.SubResource(id=snapshot) if snapshot else None |
| 313 |
managed_disk = self.image_models.SubResource(id=disk) if disk else None |
| 314 |
if self.os_disk_encryption_set: |
| 315 |
os_disk_encryption_set = self.image_models.DiskEncryptionSetParameters(id=self.os_disk_encryption_set) |
| 316 |
return self.image_models.ImageOSDisk(os_type=self.os_type, |
| 317 |
os_state=self.image_models.OperatingSystemStateTypes.generalized, |
| 318 |
snapshot=snapshot_resource, |
| 319 |
managed_disk=managed_disk, |
| 320 |
disk_encryption_set=os_disk_encryption_set, |
| 321 |
blob_uri=blob_uri) |
| 322 |
else: |
| 323 |
return self.image_models.ImageOSDisk(os_type=self.os_type, |
| 324 |
os_state=self.image_models.OperatingSystemStateTypes.generalized, |
| 325 |
snapshot=snapshot_resource, |
| 326 |
managed_disk=managed_disk, |
| 327 |
blob_uri=blob_uri) |
| 328 |
|
| 329 |
def create_data_disk(self, lun, source): |
| 330 |
blob_uri, disk, snapshot = self.resolve_storage_source(source) |
| 331 |
if blob_uri or disk or snapshot: |
| 332 |
snapshot_resource = self.image_models.SubResource(id=snapshot) if snapshot else None |
| 333 |
managed_disk = self.image_models.SubResource(id=disk) if disk else None |
| 334 |
if self.data_disk_encryption_set: |
| 335 |
data_disk_encryption_set = self.image_models.DiskEncryptionSetParameters(id=self.data_disk_encryption_set) |
| 336 |
return self.image_models.ImageDataDisk(lun=lun, |
| 337 |
blob_uri=blob_uri, |
| 338 |
snapshot=snapshot_resource, |
| 339 |
managed_disk=managed_disk, |
| 340 |
disk_encryption_set=data_disk_encryption_set) |
| 341 |
else: |
| 342 |
return self.image_models.ImageDataDisk(lun=lun, |
| 343 |
blob_uri=blob_uri, |
| 344 |
snapshot=snapshot_resource, |
| 345 |
managed_disk=managed_disk) |
| 346 |
|
| 347 |
def create_data_disks(self): |
| 348 |
return list(filter(None, [self.create_data_disk(lun, source) for lun, source in enumerate(self.data_disk_sources)])) |
| 349 |
|
| 350 |
def get_source_vm(self): |
| 351 |
|
| 352 |
resource = dict() |
| 353 |
if isinstance(self.source, dict): |
| 354 |
if self.source.get('type') != 'virtual_machines': |
| 355 |
return None |
| 356 |
resource = dict(type='virtualMachines', |
| 357 |
name=self.source['name'], |
| 358 |
resource_group=self.source.get('resource_group') or self.resource_group) |
| 359 |
elif isinstance(self.source, str): |
| 360 |
vm_resource_id = format_resource_id(self.source, |
| 361 |
self.subscription_id, |
| 362 |
'Microsoft.Compute', |
| 363 |
'virtualMachines', |
| 364 |
self.resource_group) |
| 365 |
resource = parse_resource_id(vm_resource_id) |
| 366 |
else: |
| 367 |
self.fail("Unsupported type of source parameter, please give string or dictionary") |
| 368 |
return self.get_vm(resource['resource_group'], resource['name']) if resource['type'] == 'virtualMachines' else None |
| 369 |
|
| 370 |
def get_snapshot(self, resource_group, snapshot_name): |
| 371 |
return self._get_resource(self.disk_client.snapshots.get, resource_group, snapshot_name) |
| 372 |
|
| 373 |
def get_disk(self, resource_group, disk_name): |
| 374 |
return self._get_resource(self.disk_client.disks.get, resource_group, disk_name) |
| 375 |
|
| 376 |
def get_vm(self, resource_group, vm_name): |
| 377 |
return self._get_resource(self.image_client.virtual_machines.get, resource_group, vm_name, 'instanceview') |
| 378 |
|
| 379 |
def get_image(self): |
| 380 |
return self._get_resource(self.image_client.images.get, self.resource_group, self.name) |
| 381 |
|
| 382 |
def _get_resource(self, get_method, resource_group, name, expand=None): |
| 383 |
try: |
| 384 |
if expand: |
| 385 |
return get_method(resource_group, name, expand=expand) |
| 386 |
else: |
| 387 |
return get_method(resource_group, name) |
| 388 |
except ResourceNotFoundError as cloud_err: |
| 389 |
|
| 390 |
if cloud_err.status_code == 404: |
| 391 |
self.log('{0}'.format(str(cloud_err))) |
| 392 |
return None |
| 393 |
self.fail('Error: failed to get resource {0} - {1}'.format(name, str(cloud_err))) |
| 394 |
|
| 395 |
def create_image(self, image): |
| 396 |
try: |
| 397 |
poller = self.image_client.images.begin_create_or_update(self.resource_group, self.name, image) |
| 398 |
new_image = self.get_poller_result(poller) |
| 399 |
except Exception as exc: |
| 400 |
self.fail("Error creating image {0} - {1}".format(self.name, str(exc))) |
| 401 |
self.check_provisioning_state(new_image) |
| 402 |
return new_image |
| 403 |
|
| 404 |
def delete_image(self): |
| 405 |
self.log('Deleting image {0}'.format(self.name)) |
| 406 |
try: |
| 407 |
poller = self.image_client.images.begin_delete(self.resource_group, self.name) |
| 408 |
result = self.get_poller_result(poller) |
| 409 |
except Exception as exc: |
| 410 |
self.fail("Error deleting image {0} - {1}".format(self.name, str(exc))) |
| 411 |
|
| 412 |
return result |
| 413 |
|
| 414 |
|
| 415 |
def main(): |
| 416 |
AzureRMImage() |
| 417 |
|
| 418 |
|
| 419 |
if __name__ == '__main__': |
| 420 |
main() |