| 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_snapshot |
| 14 |
version_added: "0.1.2" |
| 15 |
short_description: Manage Azure Snapshot instance |
| 16 |
description: |
| 17 |
- Create, update and delete instance of Azure Snapshot. |
| 18 |
options: |
| 19 |
resource_group: |
| 20 |
description: |
| 21 |
- The name of the resource group. |
| 22 |
required: true |
| 23 |
type: str |
| 24 |
name: |
| 25 |
description: |
| 26 |
- Resource name. |
| 27 |
required: true |
| 28 |
type: str |
| 29 |
location: |
| 30 |
description: |
| 31 |
- Resource location. |
| 32 |
type: str |
| 33 |
incremental: |
| 34 |
description: |
| 35 |
- Whether a snapshot is incremental. |
| 36 |
- Incremental snapshots on the same disk occupy less space than full snapshots and can be diffed. |
| 37 |
type: bool |
| 38 |
default: False |
| 39 |
sku: |
| 40 |
description: |
| 41 |
- The snapshots SKU. |
| 42 |
type: dict |
| 43 |
suboptions: |
| 44 |
name: |
| 45 |
description: |
| 46 |
- The sku name. |
| 47 |
type: str |
| 48 |
choices: |
| 49 |
- Standard_LRS |
| 50 |
- Premium_LRS |
| 51 |
- Standard_ZRS |
| 52 |
tier: |
| 53 |
description: |
| 54 |
- The sku tier. |
| 55 |
type: str |
| 56 |
os_type: |
| 57 |
description: |
| 58 |
- The Operating System type. |
| 59 |
type: str |
| 60 |
choices: |
| 61 |
- Linux |
| 62 |
- Windows |
| 63 |
- linux |
| 64 |
- windows |
| 65 |
creation_data: |
| 66 |
description: |
| 67 |
- Disk source information. |
| 68 |
- CreationData information cannot be changed after the disk has been created. |
| 69 |
type: dict |
| 70 |
suboptions: |
| 71 |
create_option: |
| 72 |
description: |
| 73 |
- This enumerates the possible sources of a disk's creation. |
| 74 |
type: str |
| 75 |
choices: |
| 76 |
- Import |
| 77 |
- Copy |
| 78 |
source_uri: |
| 79 |
description: |
| 80 |
- If I(create_option=Import), this is the URI of a blob to be imported into a managed disk. |
| 81 |
type: str |
| 82 |
source_id: |
| 83 |
description: |
| 84 |
- If I(create_option=Copy), this is the resource ID of a managed disk to be copied from. |
| 85 |
type: str |
| 86 |
state: |
| 87 |
description: |
| 88 |
- Assert the state of the Snapshot. |
| 89 |
- Use C(present) to create or update an Snapshot and C(absent) to delete it. |
| 90 |
default: present |
| 91 |
type: str |
| 92 |
choices: |
| 93 |
- absent |
| 94 |
- present |
| 95 |
extends_documentation_fragment: |
| 96 |
- azure.azcollection.azure |
| 97 |
- azure.azcollection.azure_tags |
| 98 |
author: |
| 99 |
- Zim Kalinowski (@zikalino) |
| 100 |
|
| 101 |
''' |
| 102 |
|
| 103 |
EXAMPLES = ''' |
| 104 |
- name: Create a snapshot by importing an unmanaged blob from the same subscription. |
| 105 |
azure_rm_snapshot: |
| 106 |
resource_group: myResourceGroup |
| 107 |
name: mySnapshot |
| 108 |
location: eastus |
| 109 |
creation_data: |
| 110 |
create_option: Import |
| 111 |
source_uri: 'https://mystorageaccount.blob.core.windows.net/osimages/osimage.vhd' |
| 112 |
|
| 113 |
- name: Create a snapshot by copying an existing managed disk. |
| 114 |
azure_rm_snapshot: |
| 115 |
resource_group: myResourceGroup |
| 116 |
name: mySnapshot |
| 117 |
location: eastus |
| 118 |
creation_data: |
| 119 |
create_option: Copy |
| 120 |
source_id: '/subscriptions/sub123/resourceGroups/group123/providers/Microsoft.Compute/disks/disk123' |
| 121 |
''' |
| 122 |
|
| 123 |
RETURN = ''' |
| 124 |
id: |
| 125 |
description: |
| 126 |
- Resource ID. |
| 127 |
returned: always |
| 128 |
type: str |
| 129 |
sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Compute/snapshots/mySnapshot |
| 130 |
''' |
| 131 |
|
| 132 |
import time |
| 133 |
import json |
| 134 |
from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ext import AzureRMModuleBaseExt |
| 135 |
from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_rest import GenericRestClient |
| 136 |
|
| 137 |
|
| 138 |
class Actions: |
| 139 |
NoAction, Create, Update, Delete = range(4) |
| 140 |
|
| 141 |
|
| 142 |
class AzureRMSnapshots(AzureRMModuleBaseExt): |
| 143 |
def __init__(self): |
| 144 |
self.module_arg_spec = dict( |
| 145 |
resource_group=dict( |
| 146 |
type='str', |
| 147 |
required=True |
| 148 |
), |
| 149 |
name=dict( |
| 150 |
type='str', |
| 151 |
required=True |
| 152 |
), |
| 153 |
location=dict( |
| 154 |
type='str' |
| 155 |
), |
| 156 |
sku=dict( |
| 157 |
type='dict', |
| 158 |
options=dict( |
| 159 |
name=dict( |
| 160 |
type='str', |
| 161 |
choices=['Standard_LRS', |
| 162 |
'Premium_LRS', |
| 163 |
'Standard_ZRS'] |
| 164 |
), |
| 165 |
tier=dict( |
| 166 |
type='str' |
| 167 |
) |
| 168 |
) |
| 169 |
), |
| 170 |
os_type=dict( |
| 171 |
type='str', |
| 172 |
choices=['Windows', 'linux', |
| 173 |
'Linux', 'windows'] |
| 174 |
), |
| 175 |
incremental=dict(type='bool', default=False), |
| 176 |
creation_data=dict( |
| 177 |
type='dict', |
| 178 |
options=dict( |
| 179 |
create_option=dict( |
| 180 |
type='str', |
| 181 |
choices=['Import', 'Copy'], |
| 182 |
), |
| 183 |
source_uri=dict( |
| 184 |
type='str' |
| 185 |
), |
| 186 |
source_id=dict( |
| 187 |
type='str' |
| 188 |
) |
| 189 |
) |
| 190 |
), |
| 191 |
state=dict( |
| 192 |
type='str', |
| 193 |
default='present', |
| 194 |
choices=['present', 'absent'] |
| 195 |
) |
| 196 |
) |
| 197 |
|
| 198 |
self.resource_group = None |
| 199 |
self.name = None |
| 200 |
self.id = None |
| 201 |
self.name = None |
| 202 |
self.type = None |
| 203 |
self.managed_by = None |
| 204 |
|
| 205 |
self.results = dict(changed=False) |
| 206 |
self.mgmt_client = None |
| 207 |
self.state = None |
| 208 |
self.url = None |
| 209 |
self.status_code = [200, 201, 202] |
| 210 |
self.to_do = Actions.NoAction |
| 211 |
|
| 212 |
self.body = {} |
| 213 |
self.body['properties'] = dict() |
| 214 |
self.query_parameters = {} |
| 215 |
self.query_parameters['api-version'] = '2022-03-02' |
| 216 |
self.header_parameters = {} |
| 217 |
self.header_parameters['Content-Type'] = 'application/json; charset=utf-8' |
| 218 |
|
| 219 |
super(AzureRMSnapshots, self).__init__(derived_arg_spec=self.module_arg_spec, |
| 220 |
supports_check_mode=True, |
| 221 |
supports_tags=True) |
| 222 |
|
| 223 |
def exec_module(self, **kwargs): |
| 224 |
for key in list(self.module_arg_spec.keys()) + ['tags']: |
| 225 |
if hasattr(self, key): |
| 226 |
setattr(self, key, kwargs[key]) |
| 227 |
elif kwargs[key] is not None: |
| 228 |
if key == 'incremental': |
| 229 |
self.body['properties']['incremental'] = kwargs[key] |
| 230 |
elif key == 'os_type': |
| 231 |
self.body['properties']['osType'] = kwargs[key] |
| 232 |
elif key == 'creation_data': |
| 233 |
self.body['properties']['creationData'] = dict() |
| 234 |
if kwargs[key].get('create_option') is not None: |
| 235 |
self.body['properties']['creationData']['createOption'] = kwargs[key].get('create_option') |
| 236 |
self.body['properties']['creationData']['sourceUri'] = kwargs[key].get('source_uri') |
| 237 |
self.body['properties']['creationData']['sourceResourceId'] = kwargs[key].get('source_id') |
| 238 |
if kwargs[key].get('source_uri') is not None: |
| 239 |
self.query_parameters['api-version'] = '2019-03-01' |
| 240 |
else: |
| 241 |
self.body[key] = kwargs[key] |
| 242 |
|
| 243 |
old_response = None |
| 244 |
response = None |
| 245 |
|
| 246 |
self.mgmt_client = self.get_mgmt_svc_client(GenericRestClient, |
| 247 |
base_url=self._cloud_environment.endpoints.resource_manager) |
| 248 |
|
| 249 |
resource_group = self.get_resource_group(self.resource_group) |
| 250 |
|
| 251 |
if 'location' not in self.body: |
| 252 |
self.body['location'] = resource_group.location |
| 253 |
|
| 254 |
self.url = ('/subscriptions' + |
| 255 |
'/{{ subscription_id }}' + |
| 256 |
'/resourceGroups' + |
| 257 |
'/{{ resource_group }}' + |
| 258 |
'/providers' + |
| 259 |
'/Microsoft.Compute' + |
| 260 |
'/snapshots' + |
| 261 |
'/{{ snapshot_name }}') |
| 262 |
self.url = self.url.replace('{{ subscription_id }}', self.subscription_id) |
| 263 |
self.url = self.url.replace('{{ resource_group }}', self.resource_group) |
| 264 |
self.url = self.url.replace('{{ snapshot_name }}', self.name) |
| 265 |
|
| 266 |
old_response = self.get_resource() |
| 267 |
|
| 268 |
if not old_response: |
| 269 |
self.log("Snapshot instance doesn't exist") |
| 270 |
|
| 271 |
if self.state == 'absent': |
| 272 |
self.log("Old instance didn't exist") |
| 273 |
else: |
| 274 |
self.to_do = Actions.Create |
| 275 |
else: |
| 276 |
self.log('Snapshot instance already exists') |
| 277 |
|
| 278 |
if self.state == 'absent': |
| 279 |
self.to_do = Actions.Delete |
| 280 |
else: |
| 281 |
if self.body.get('sku') is not None and \ |
| 282 |
not all(self.body['sku'][item] == old_response['sku'].get(item) for item in self.body['sku'].keys()): |
| 283 |
self.to_do = Actions.Update |
| 284 |
if self.body['properties'].get('incremental') is not None and \ |
| 285 |
self.body['properties']['incremental'] != old_response['properties']['incremental']: |
| 286 |
self.to_do = Actions.Update |
| 287 |
if self.body['properties'].get('osType') is not None and \ |
| 288 |
self.body['properties']['osType'] != old_response['properties'].get('osType'): |
| 289 |
self.to_do = Actions.Update |
| 290 |
if self.body['properties'].get('creationData') is not None and \ |
| 291 |
not all(self.body['properties']['creationData'][item] == old_response['properties']['creationData'].get(item) |
| 292 |
for item in self.body['properties']['creationData'].keys()): |
| 293 |
self.to_do = Actions.Update |
| 294 |
|
| 295 |
update_tags, self.body['tags'] = self.update_tags(old_response.get('tags')) |
| 296 |
if update_tags: |
| 297 |
self.to_do = Actions.Update |
| 298 |
|
| 299 |
if (self.to_do == Actions.Create) or (self.to_do == Actions.Update): |
| 300 |
self.log('Need to Create / Update the Snapshot instance') |
| 301 |
|
| 302 |
if self.check_mode: |
| 303 |
self.results['changed'] = True |
| 304 |
return self.results |
| 305 |
response = self.create_update_resource() |
| 306 |
self.results['changed'] = True |
| 307 |
self.log('Creation / Update done') |
| 308 |
elif self.to_do == Actions.Delete: |
| 309 |
self.log('Snapshot instance deleted') |
| 310 |
self.results['changed'] = True |
| 311 |
|
| 312 |
if self.check_mode: |
| 313 |
return self.results |
| 314 |
|
| 315 |
self.delete_resource() |
| 316 |
|
| 317 |
|
| 318 |
|
| 319 |
while self.get_resource(): |
| 320 |
time.sleep(20) |
| 321 |
else: |
| 322 |
self.log('Snapshot instance unchanged') |
| 323 |
self.results['changed'] = False |
| 324 |
response = old_response |
| 325 |
|
| 326 |
if response: |
| 327 |
self.results["id"] = response["id"] |
| 328 |
|
| 329 |
return self.results |
| 330 |
|
| 331 |
def create_update_resource(self): |
| 332 |
|
| 333 |
response = None |
| 334 |
try: |
| 335 |
response = self.mgmt_client.query(url=self.url, |
| 336 |
method='PUT', |
| 337 |
query_parameters=self.query_parameters, |
| 338 |
header_parameters=self.header_parameters, |
| 339 |
body=self.body, |
| 340 |
expected_status_codes=self.status_code, |
| 341 |
polling_timeout=600, |
| 342 |
polling_interval=30) |
| 343 |
except Exception as exc: |
| 344 |
self.log('Error attempting to create the Snapshot instance.') |
| 345 |
self.fail('Error creating the Snapshot instance: {0}'.format(str(exc))) |
| 346 |
|
| 347 |
if hasattr(response, 'body'): |
| 348 |
response = json.loads(response.body()) |
| 349 |
elif hasattr(response, 'context'): |
| 350 |
response = response.context['deserialized_data'] |
| 351 |
else: |
| 352 |
self.fail("Create or Updating fail, no match message return, return info as {0}".format(response)) |
| 353 |
|
| 354 |
return response |
| 355 |
|
| 356 |
def delete_resource(self): |
| 357 |
|
| 358 |
try: |
| 359 |
response = self.mgmt_client.query(url=self.url, |
| 360 |
method='DELETE', |
| 361 |
query_parameters=self.query_parameters, |
| 362 |
header_parameters=self.header_parameters, |
| 363 |
body=None, |
| 364 |
expected_status_codes=self.status_code, |
| 365 |
polling_timeout=600, |
| 366 |
polling_interval=30) |
| 367 |
except Exception as e: |
| 368 |
self.log('Error attempting to delete the Snapshot instance.') |
| 369 |
self.fail('Error deleting the Snapshot instance: {0}'.format(str(e))) |
| 370 |
|
| 371 |
return True |
| 372 |
|
| 373 |
def get_resource(self): |
| 374 |
|
| 375 |
found = False |
| 376 |
try: |
| 377 |
response = self.mgmt_client.query(url=self.url, |
| 378 |
method='GET', |
| 379 |
query_parameters=self.query_parameters, |
| 380 |
header_parameters=self.header_parameters, |
| 381 |
body=None, |
| 382 |
expected_status_codes=self.status_code, |
| 383 |
polling_timeout=600, |
| 384 |
polling_interval=30) |
| 385 |
response = json.loads(response.body()) |
| 386 |
found = True |
| 387 |
self.log("Response : {0}".format(response)) |
| 388 |
|
| 389 |
except Exception as e: |
| 390 |
self.log('Did not find the Snapshot instance.') |
| 391 |
if found is True: |
| 392 |
return response |
| 393 |
|
| 394 |
return False |
| 395 |
|
| 396 |
|
| 397 |
def main(): |
| 398 |
AzureRMSnapshots() |
| 399 |
|
| 400 |
|
| 401 |
if __name__ == '__main__': |
| 402 |
main() |