Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2019 Zim Kalinowski, (@zikalino)
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_galleryimage
14 version_added: "0.1.2"
15 short_description: Manage Azure SIG Image instance
16 description:
17 - Create, update and delete instance of Azure SIG Image.
18 options:
19 resource_group:
20 description:
21 - The name of the resource group.
22 required: true
23 type: str
24 gallery_name:
25 description:
26 - The name of the Shared Image Gallery in which the Image Definition is to be created.
27 required: true
28 type: str
29 name:
30 description:
31 - The name of the gallery Image Definition to be created or updated.
32 - The allowed characters are alphabets and numbers with dots, dashes, and periods allowed in the middle.
33 - The maximum length is 80 characters.
34 required: true
35 type: str
36 location:
37 description:
38 - Resource location.
39 type: str
40 description:
41 description:
42 - The description of this gallery Image Definition resource. This property is updatable.
43 type: str
44 eula:
45 description:
46 - The Eula agreement for the gallery Image Definition.
47 type: str
48 privacy_statement_uri:
49 description:
50 - The privacy statement uri.
51 type: str
52 release_note_uri:
53 description:
54 - The release note uri.
55 type: str
56 os_type:
57 description:
58 - This property allows you to specify the type of the OS that is included in the disk when creating a VM from a managed image.
59 - Required when creating.
60 choices:
61 - windows
62 - linux
63 - Windows
64 - Linux
65 type: str
66 os_state:
67 description:
68 - The allowed values for OS State are C(generalized).
69 - Required when creating.
70 choices:
71 - generalized
72 - specialized
73 type: str
74 hypervgeneration:
75 description:
76 - This property allows you to specify the Hyper V Version of the Virtual Machines.
77 choices:
78 - V1
79 - V2
80 type: str
81 architecture:
82 description:
83 - This property allows you to specify the hardware architecture of the Virtual Machines.
84 - Arm64 is only supported with Hyper V Version 2.
85 choices:
86 - Arm64
87 - x64
88 type: str
89 end_of_life_date:
90 description:
91 - The end of life date of the gallery Image Definition.
92 - This property can be used for decommissioning purposes.
93 - This property is updatable.
94 - Format should be according to ISO-8601, for instance "2019-06-26".
95 type: str
96 identifier:
97 description:
98 - Image identifier.
99 - Required when creating.
100 type: dict
101 suboptions:
102 publisher:
103 description:
104 - The name of the gallery Image Definition publisher.
105 required: true
106 type: str
107 offer:
108 description:
109 - The name of the gallery Image Definition offer.
110 required: true
111 type: str
112 sku:
113 description:
114 - The name of the gallery Image Definition SKU.
115 required: true
116 type: str
117 recommended:
118 description:
119 - Recommended parameter values.
120 type: dict
121 suboptions:
122 v_cpus:
123 description:
124 - Number of virtual CPUs.
125 type: dict
126 suboptions:
127 min:
128 description:
129 - The minimum number of the resource.
130 type: int
131 max:
132 description:
133 - The maximum number of the resource.
134 type: int
135 memory:
136 description:
137 - Memory.
138 type: dict
139 suboptions:
140 min:
141 description:
142 - The minimum number of the resource.
143 type: int
144 max:
145 description:
146 - The maximum number of the resource.
147 type: int
148 disallowed:
149 description:
150 - Disallowed parameter values.
151 type: dict
152 suboptions:
153 disk_types:
154 description:
155 - A list of disallowed disk types.
156 type: list
157 elements: str
158 purchase_plan:
159 description:
160 - Purchase plan.
161 type: dict
162 suboptions:
163 name:
164 description:
165 - The plan ID.
166 type: str
167 publisher:
168 description:
169 - The publisher ID.
170 type: str
171 product:
172 description:
173 - The product ID.
174 type: str
175 features:
176 description:
177 - A list of gallery image features.
178 type: list
179 elements: dict
180 suboptions:
181 name:
182 description:
183 - The name of the gallery image feature.
184 type: str
185 required: True
186 value:
187 description:
188 - The value of the gallery image feature.
189 type: str
190 required: True
191 state:
192 description:
193 - Assert the state of the GalleryImage.
194 - Use C(present) to create or update an GalleryImage and C(absent) to delete it.
195 default: present
196 choices:
197 - absent
198 - present
199 type: str
200 extends_documentation_fragment:
201 - azure.azcollection.azure
202 - azure.azcollection.azure_tags
203 author:
204 - Zim Kalinowski (@zikalino)
205
206 '''
207
208 EXAMPLES = '''
209 - name: Create or update gallery image
210 azure_rm_galleryimage:
211 resource_group: myResourceGroup
212 gallery_name: myGallery1283
213 name: myImage
214 location: West US
215 os_type: linux
216 os_state: generalized
217 identifier:
218 publisher: myPublisherName
219 offer: myOfferName
220 sku: mySkuName
221 '''
222
223 RETURN = '''
224 id:
225 description:
226 - Resource ID.
227 returned: always
228 type: str
229 sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Compute/galleries/myGalle
230 ry1283/images/myImage"
231 '''
232
233 import time
234 import json
235 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ext import AzureRMModuleBaseExt
236 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_rest import GenericRestClient
237
238
239 class Actions:
240 NoAction, Create, Update, Delete = range(4)
241
242
243 class AzureRMGalleryImages(AzureRMModuleBaseExt):
244 def __init__(self):
245 self.module_arg_spec = dict(
246 resource_group=dict(
247 type='str',
248 required=True
249 ),
250 gallery_name=dict(
251 type='str',
252 required=True
253 ),
254 name=dict(
255 type='str',
256 required=True
257 ),
258 location=dict(
259 type='str',
260 ),
261 description=dict(
262 type='str',
263 ),
264 eula=dict(
265 type='str',
266 ),
267 privacy_statement_uri=dict(
268 type='str',
269 ),
270 release_note_uri=dict(
271 type='str',
272 ),
273 os_type=dict(
274 type='str',
275 choices=['windows', 'Windows',
276 'Linux', 'linux']
277 ),
278 os_state=dict(
279 type='str',
280 choices=['generalized',
281 'specialized']
282 ),
283 hypervgeneration=dict(
284 type='str',
285 choices=['V1',
286 'V2']
287 ),
288 architecture=dict(
289 type='str',
290 choices=['Arm64',
291 'x64']
292 ),
293 end_of_life_date=dict(
294 type='str',
295 ),
296 identifier=dict(
297 type='dict',
298 options=dict(
299 publisher=dict(
300 type='str',
301 required=True,
302 ),
303 offer=dict(
304 type='str',
305 required=True
306 ),
307 sku=dict(
308 type='str',
309 required=True
310 )
311 )
312 ),
313 recommended=dict(
314 type='dict',
315 options=dict(
316 v_cpus=dict(
317 type='dict',
318 options=dict(
319 min=dict(
320 type='int'
321 ),
322 max=dict(
323 type='int'
324 )
325 )
326 ),
327 memory=dict(
328 type='dict',
329 options=dict(
330 min=dict(
331 type='int'
332 ),
333 max=dict(
334 type='int'
335 )
336 )
337 )
338 )
339 ),
340 disallowed=dict(
341 type='dict',
342 options=dict(
343 disk_types=dict(
344 type='list',
345 elements='str',
346 )
347 )
348 ),
349 purchase_plan=dict(
350 type='dict',
351 options=dict(
352 name=dict(
353 type='str'
354 ),
355 publisher=dict(
356 type='str'
357 ),
358 product=dict(
359 type='str'
360 )
361 )
362 ),
363 features=dict(
364 type='list',
365 elements='dict',
366 options=dict(
367 name=dict(
368 type='str',
369 required=True
370 ),
371 value=dict(
372 type='str',
373 required=True
374 )
375 )
376 ),
377 state=dict(
378 type='str',
379 default='present',
380 choices=['present', 'absent']
381 )
382 )
383
384 self.resource_group = None
385 self.gallery_name = None
386 self.name = None
387 self.gallery_image = None
388
389 self.results = dict(changed=False)
390 self.mgmt_client = None
391 self.state = None
392 self.url = None
393 self.status_code = [200, 201, 202]
394 self.to_do = Actions.NoAction
395
396 self.body = {}
397 self.body['properties'] = {}
398 self.query_parameters = {}
399 self.query_parameters['api-version'] = '2022-03-03'
400 self.header_parameters = {}
401 self.header_parameters['Content-Type'] = 'application/json; charset=utf-8'
402
403 super(AzureRMGalleryImages, self).__init__(derived_arg_spec=self.module_arg_spec,
404 supports_check_mode=True,
405 supports_tags=True)
406
407 def exec_module(self, **kwargs):
408 for key in list(self.module_arg_spec.keys()) + ['tags']:
409 if hasattr(self, key):
410 setattr(self, key, kwargs[key])
411 elif kwargs[key] is not None:
412 if key == 'description':
413 self.body['properties']['description'] = kwargs[key]
414 elif key == 'eula':
415 self.body['properties']['eula'] = kwargs[key]
416 elif key == 'privacy_statement_uri':
417 self.body['properties']['privacyStatementUri'] = kwargs[key]
418 elif key == 'release_note_uri':
419 self.body['properties']['releaseNoteUri'] = kwargs[key]
420 elif key == 'os_type':
421 self.body['properties']['osType'] = kwargs[key]
422 elif key == 'os_state':
423 self.body['properties']['osState'] = kwargs[key]
424 elif key == 'hypervgeneration':
425 self.body['properties']['hyperVGeneration'] = kwargs[key]
426 elif key == 'architecture':
427 self.body['properties']['architecture'] = kwargs[key]
428 elif key == 'end_of_life_date':
429 self.body['properties']['endOfLifeDate'] = kwargs[key]
430 elif key == 'identifier':
431 self.body['properties']['identifier'] = kwargs[key]
432 elif key == 'recommended':
433 self.body['properties']['recommended'] = {}
434 for item in kwargs[key].keys():
435 if item == 'v_cpus':
436 self.body['properties']['recommended']['vCPUs'] = kwargs[key].get('v_cpus')
437 elif item == 'memory':
438 self.body['properties']['recommended']['memory'] = kwargs[key].get('memory')
439 elif key == 'disallowed':
440 self.body['properties']['disallowed'] = {}
441 self.body['properties']['disallowed']['diskTypes'] = kwargs[key].get('disk_types')
442 elif key == 'purchase_plan':
443 self.body['properties']['purchasePlan'] = kwargs[key]
444 elif key == 'features':
445 self.body['properties']['features'] = kwargs[key]
446 else:
447 self.body[key] = kwargs[key]
448
449 old_response = None
450 response = None
451
452 self.mgmt_client = self.get_mgmt_svc_client(GenericRestClient,
453 base_url=self._cloud_environment.endpoints.resource_manager)
454
455 resource_group = self.get_resource_group(self.resource_group)
456
457 if 'location' not in self.body:
458 self.body['location'] = resource_group.location
459
460 self.url = ('/subscriptions' +
461 '/{{ subscription_id }}' +
462 '/resourceGroups' +
463 '/{{ resource_group }}' +
464 '/providers' +
465 '/Microsoft.Compute' +
466 '/galleries' +
467 '/{{ gallery_name }}' +
468 '/images' +
469 '/{{ image_name }}')
470 self.url = self.url.replace('{{ subscription_id }}', self.subscription_id)
471 self.url = self.url.replace('{{ resource_group }}', self.resource_group)
472 self.url = self.url.replace('{{ gallery_name }}', self.gallery_name)
473 self.url = self.url.replace('{{ image_name }}', self.name)
474
475 old_response = self.get_resource()
476
477 if not old_response:
478 self.log("GalleryImage instance doesn't exist")
479
480 if self.state == 'absent':
481 self.log("Old instance didn't exist")
482 else:
483 self.to_do = Actions.Create
484 else:
485 self.log('GalleryImage instance already exists')
486
487 if self.state == 'absent':
488 self.to_do = Actions.Delete
489 else:
490 if self.body['properties'].get('description') is not None and \
491 self.body['properties']['description'] != old_response['properties'].get('description'):
492 self.to_do = Actions.Update
493 elif self.body['properties'].get('eula') is not None and self.body['properties']['eula'] != old_response['properties'].get('eula'):
494 self.to_do = Actions.Update
495 elif (self.body['properties'].get('privacyStatementUri') is not None and
496 self.body['properties']['privacyStatementUri'] != old_response['properties'].get('privacyStatementUri')):
497 self.to_do = Actions.Update
498 elif (self.body['properties'].get('releaseNoteUri') is not None and
499 self.body['properties']['releaseNoteUri'] != old_response['properties'].get('releaseNoteUri')):
500 self.to_do = Actions.Update
501 elif (self.body['properties'].get('osType') is not None and
502 self.body['properties']['osType'].lower() != old_response['properties'].get('osType', '').lower()):
503 self.to_do = Actions.Update
504 elif (self.body['properties'].get('osState') is not None and
505 self.body['properties']['osState'].lower() != old_response['properties'].get('osState', '').lower()):
506 self.to_do = Actions.Update
507 elif (self.body['properties'].get('hyperVGeneration') is not None and
508 self.body['properties']['hyperVGeneration'] != old_response['properties'].get('hyperVGeneration')):
509 self.to_do = Actions.Update
510 elif (self.body['properties'].get('architecture') is not None and
511 self.body['properties']['architecture'] != old_response['properties'].get('architecture')):
512 self.to_do = Actions.Update
513 elif (self.body['properties'].get('endOfLifeDate') is not None and
514 self.body['properties']['endOfLifeDate'] != old_response['properties'].get('endOfLifeDate')):
515 self.to_do = Actions.Update
516 elif (self.body['properties'].get('identifier') is not None and
517 self.body['properties']['identifier'].get('offer') != old_response['properties']['identifier'].get('offer') or
518 self.body['properties']['identifier'].get('sku') != old_response['properties']['identifier'].get('sku')):
519 self.to_do = Actions.Update
520 elif self.body['properties'].get('recommended') is not None:
521 if self.body['properties']['recommended'].get('vCPUS') is not None:
522 for item in self.body['properties']['recommended']['vCPUS'].keys():
523 if self.body['properties']['recommended']['vCPUS'].get(item) != old_response['properties']['recommended']['vCPUS'].get(item):
524 self.to_do = Actions.Update
525 elif (self.body['properties']['recommended'].get('memory') is not None and
526 not all(self.body['properties']['recommended']['memory'].get(item) == old_response['properties']['recommended']['memory'].get(item)
527 for item in self.body['properties']['recommended']['memory'].keys())):
528 self.to_do = Actions.Update
529 elif (self.body['properties'].get('disallowed') is not None and
530 self.body['properties']['disallowed'].get('diskTypes') != old_response['properties']['disallowed'].get('diskTypes')):
531 self.to_do = Actions.Update
532 elif self.body['properties'].get('purchasePlan') is not None:
533 for item in self.body['properties']['purchasePlan'].keys():
534 if self.body['properties']['purchasePlan'][item] != old_response['properties']['purchasePlan'].get(item):
535 self.to_do = Actions.Update
536 elif self.body['properties'].get('features') is not None:
537 if old_response['properties'].get('features') is None:
538 self.to_do = Actions.Update
539 else:
540 if not all(item in old_response['properties']['features'] for item in self.body['properties']['features']):
541 self.to_do = Actions.Update
542 update_tags, self.body['tags'] = self.update_tags(old_response.get('tags'))
543 if update_tags:
544 self.to_do = Actions.Update
545
546 if (self.to_do == Actions.Create) or (self.to_do == Actions.Update):
547 self.log('Need to Create / Update the GalleryImage instance')
548
549 if self.check_mode:
550 self.results['changed'] = True
551 return self.results
552
553 response = self.create_update_resource()
554
555 # if not old_response:
556 self.results['changed'] = True
557 # else:
558 # self.results['changed'] = old_response.__ne__(response)
559 self.log('Creation / Update done')
560 elif self.to_do == Actions.Delete:
561 self.log('GalleryImage instance deleted')
562 self.results['changed'] = True
563
564 if self.check_mode:
565 return self.results
566
567 self.delete_resource()
568
569 # make sure instance is actually deleted, for some Azure resources, instance is hanging around
570 # for some time after deletion -- this should be really fixed in Azure
571 while self.get_resource():
572 time.sleep(20)
573 else:
574 self.log('GalleryImage instance unchanged')
575 self.results['changed'] = False
576 response = old_response
577
578 if response:
579 self.results["id"] = response["id"]
580
581 return self.results
582
583 def create_update_resource(self):
584 # self.log('Creating / Updating the GalleryImage instance {0}'.format(self.))
585
586 try:
587 response = self.mgmt_client.query(self.url,
588 'PUT',
589 self.query_parameters,
590 self.header_parameters,
591 self.body,
592 self.status_code,
593 600,
594 30)
595 except Exception as exc:
596 self.log('Error attempting to create the GalleryImage instance.')
597 self.fail('Error creating the GalleryImage instance: {0}'.format(str(exc)))
598
599 if hasattr(response, 'body'):
600 response = json.loads(response.body())
601 elif hasattr(response, 'context'):
602 response = response.context['deserialized_data']
603 else:
604 self.fail("Create or Updating fail, no match message return, return info as {0}".format(response))
605
606 return response
607
608 def delete_resource(self):
609 # self.log('Deleting the GalleryImage instance {0}'.format(self.))
610 try:
611 response = self.mgmt_client.query(self.url,
612 'DELETE',
613 self.query_parameters,
614 self.header_parameters,
615 None,
616 self.status_code,
617 600,
618 30)
619 except Exception as e:
620 self.log('Error attempting to delete the GalleryImage instance.')
621 self.fail('Error deleting the GalleryImage instance: {0}'.format(str(e)))
622
623 return True
624
625 def get_resource(self):
626 # self.log('Checking if the GalleryImage instance {0} is present'.format(self.))
627 found = False
628 try:
629 response = self.mgmt_client.query(self.url,
630 'GET',
631 self.query_parameters,
632 self.header_parameters,
633 None,
634 self.status_code,
635 600,
636 30)
637 response = json.loads(response.body())
638 found = True
639 self.log("Response : {0}".format(response))
640 # self.log("AzureFirewall instance : {0} found".format(response.name))
641 except Exception as e:
642 self.log('Did not find the AzureFirewall instance.')
643 if found is True:
644 return response
645
646 return False
647
648
649 def main():
650 AzureRMGalleryImages()
651
652
653 if __name__ == '__main__':
654 main()