Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2018 Hai Cao, <[email protected]>, Yunge Zhu <[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 DOCUMENTATION = '''
11 ---
12 module: azure_rm_cdnendpoint
13 version_added: "0.1.2"
14 short_description: Manage a Azure CDN endpoint
15 description:
16 - Create, update, start, stop and delete a Azure CDN endpoint.
17
18 options:
19 resource_group:
20 description:
21 - Name of a resource group where the Azure CDN endpoint exists or will be created.
22 required: true
23 type: str
24 name:
25 description:
26 - Name of the Azure CDN endpoint.
27 required: true
28 type: str
29 location:
30 description:
31 - Valid azure location. Defaults to location of the resource group.
32 type: str
33 started:
34 description:
35 - Use with I(state=present) to start the endpoint.
36 type: bool
37 purge:
38 description:
39 - Use with I(state=present) to purge the endpoint.
40 type: bool
41 purge_content_paths:
42 description:
43 - Use with I(state=present) and I(purge=true) to specify content paths to be purged.
44 type: list
45 elements: str
46 default: ['/']
47 profile_name:
48 description:
49 - Name of the CDN profile where the endpoint attached to.
50 required: true
51 type: str
52 origins:
53 description:
54 - Set of source of the content being delivered via CDN.
55 - Required when creating.
56 elements: dict
57 type: list
58 suboptions:
59 name:
60 description:
61 - Origin name.
62 required: true
63 type: str
64 host_name:
65 description:
66 - The address of the origin.
67 - It can be a domain name, IPv4 address, or IPv6 address.
68 required: true
69 type: str
70 http_port:
71 description:
72 - The value of the HTTP port. Must be between C(1) and C(65535).
73 type: int
74 https_port:
75 description:
76 - The value of the HTTPS port. Must be between C(1) and C(65535).
77 type: int
78 origin_host_header:
79 description:
80 - The host header value sent to the origin with each request.
81 type: str
82 origin_path:
83 description:
84 - A directory path on the origin that CDN can use to retrieve content from.
85 - E.g. contoso.cloudapp.net/originpath.
86 type: str
87 content_types_to_compress:
88 description:
89 - List of content types on which compression applies.
90 - This value should be a valid MIME type.
91 type: list
92 elements: str
93 is_compression_enabled:
94 description:
95 - Indicates whether content compression is enabled on CDN.
96 type: bool
97 default: false
98 is_http_allowed:
99 description:
100 - Indicates whether HTTP traffic is allowed on the endpoint.
101 type: bool
102 default: true
103 is_https_allowed:
104 description:
105 - Indicates whether HTTPS traffic is allowed on the endpoint.
106 type: bool
107 default: true
108 query_string_caching_behavior:
109 description:
110 - Defines how CDN caches requests that include query strings.
111 type: str
112 choices:
113 - ignore_query_string
114 - bypass_caching
115 - use_query_string
116 - not_set
117 default: ignore_query_string
118 state:
119 description:
120 - Assert the state of the Azure CDN endpoint. Use C(present) to create or update a Azure CDN endpoint and C(absent) to delete it.
121 default: present
122 type: str
123 choices:
124 - absent
125 - present
126
127 extends_documentation_fragment:
128 - azure.azcollection.azure
129 - azure.azcollection.azure_tags
130
131 author:
132 - Yunge Zhu (@yungezz)
133 '''
134
135 EXAMPLES = '''
136 - name: Create a Azure CDN endpoint
137 azure_rm_cdnendpoint:
138 resource_group: myResourceGroup
139 profile_name: myProfile
140 name: myEndpoint
141 origins:
142 - name: TestOrig
143 host_name: "www.example.com"
144 tags:
145 testing: testing
146 delete: on-exit
147 foo: bar
148 - name: Delete a Azure CDN endpoint
149 azure_rm_cdnendpoint:
150 resource_group: myResourceGroup
151 profile_name: myProfile
152 name: myEndpoint
153 state: absent
154 '''
155 RETURN = '''
156 state:
157 description: Current state of the Azure CDN endpoint.
158 returned: always
159 type: str
160 id:
161 description:
162 - Id of the CDN endpoint.
163 returned: always
164 type: str
165 sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourcegroups/myResourceGroup/providers/Microsoft.Cdn/profiles/myProfile/endpoints/
166 myEndpoint"
167 host_name:
168 description:
169 - Host name of the CDN endpoint.
170 returned: always
171 type: str
172 sample: "myendpoint.azureedge.net"
173 '''
174
175 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase
176 from ansible.module_utils.common.dict_transformations import _snake_to_camel
177
178 try:
179 from azure.mgmt.cdn.models import Endpoint, DeepCreatedOrigin, EndpointUpdateParameters, QueryStringCachingBehavior
180 except ImportError:
181 # This is handled in azure_rm_common
182 pass
183
184
185 def cdnendpoint_to_dict(cdnendpoint):
186 return dict(
187 id=cdnendpoint.id,
188 name=cdnendpoint.name,
189 type=cdnendpoint.type,
190 location=cdnendpoint.location,
191 tags=cdnendpoint.tags,
192 origin_host_header=cdnendpoint.origin_host_header,
193 origin_path=cdnendpoint.origin_path,
194 content_types_to_compress=cdnendpoint.content_types_to_compress,
195 is_compression_enabled=cdnendpoint.is_compression_enabled,
196 is_http_allowed=cdnendpoint.is_http_allowed,
197 is_https_allowed=cdnendpoint.is_https_allowed,
198 query_string_caching_behavior=cdnendpoint.query_string_caching_behavior,
199 optimization_type=cdnendpoint.optimization_type,
200 probe_path=cdnendpoint.probe_path,
201 geo_filters=[geo_filter_to_dict(geo_filter) for geo_filter in cdnendpoint.geo_filters] if cdnendpoint.geo_filters else None,
202 host_name=cdnendpoint.host_name,
203 origins=[deep_created_origin_to_dict(origin) for origin in cdnendpoint.origins] if cdnendpoint.origins else None,
204 resource_state=cdnendpoint.resource_state,
205 provisioning_state=cdnendpoint.provisioning_state
206 )
207
208
209 def deep_created_origin_to_dict(origin):
210 return dict(
211 name=origin.name,
212 host_name=origin.host_name,
213 http_port=origin.http_port,
214 https_port=origin.https_port,
215 )
216
217
218 def geo_filter_to_dict(geo_filter):
219 return dict(
220 relative_path=geo_filter.relative_path,
221 action=geo_filter.action,
222 country_codes=geo_filter.country_codes,
223 )
224
225
226 def default_content_types():
227 return ["text/plain",
228 "text/html",
229 "text/css",
230 "text/javascript",
231 "application/x-javascript",
232 "application/javascript",
233 "application/json",
234 "application/xml"]
235
236
237 origin_spec = dict(
238 name=dict(
239 type='str',
240 required=True
241 ),
242 host_name=dict(
243 type='str',
244 required=True
245 ),
246 http_port=dict(
247 type='int'
248 ),
249 https_port=dict(
250 type='int'
251 )
252 )
253
254
255 class AzureRMCdnendpoint(AzureRMModuleBase):
256
257 def __init__(self):
258 self.module_arg_spec = dict(
259 resource_group=dict(
260 type='str',
261 required=True
262 ),
263 name=dict(
264 type='str',
265 required=True
266 ),
267 location=dict(
268 type='str'
269 ),
270 state=dict(
271 type='str',
272 default='present',
273 choices=['present', 'absent']
274 ),
275 started=dict(
276 type='bool'
277 ),
278 purge=dict(
279 type='bool'
280 ),
281 purge_content_paths=dict(
282 type='list',
283 elements='str',
284 default=['/']
285 ),
286 profile_name=dict(
287 type='str',
288 required=True
289 ),
290 origins=dict(
291 type='list',
292 elements='dict',
293 options=origin_spec
294 ),
295 origin_host_header=dict(
296 type='str',
297 ),
298 origin_path=dict(
299 type='str',
300 ),
301 content_types_to_compress=dict(
302 type='list',
303 elements='str',
304 ),
305 is_compression_enabled=dict(
306 type='bool',
307 default=False
308 ),
309 is_http_allowed=dict(
310 type='bool',
311 default=True
312 ),
313 is_https_allowed=dict(
314 type='bool',
315 default=True
316 ),
317 query_string_caching_behavior=dict(
318 type='str',
319 choices=[
320 'ignore_query_string',
321 'bypass_caching',
322 'use_query_string',
323 'not_set'
324 ],
325 default='ignore_query_string'
326 ),
327 )
328
329 self.resource_group = None
330 self.name = None
331 self.state = None
332 self.started = None
333 self.purge = None
334 self.purge_content_paths = None
335 self.location = None
336 self.profile_name = None
337 self.origins = None
338 self.tags = None
339 self.origin_host_header = None
340 self.origin_path = None
341 self.content_types_to_compress = None
342 self.is_compression_enabled = None
343 self.is_http_allowed = None
344 self.is_https_allowed = None
345 self.query_string_caching_behavior = None
346
347 self.results = dict(changed=False)
348
349 super(AzureRMCdnendpoint, self).__init__(derived_arg_spec=self.module_arg_spec,
350 supports_check_mode=True,
351 supports_tags=True)
352
353 def exec_module(self, **kwargs):
354 """Main module execution method"""
355
356 for key in list(self.module_arg_spec.keys()) + ['tags']:
357 setattr(self, key, kwargs[key])
358
359 to_be_updated = False
360
361 resource_group = self.get_resource_group(self.resource_group)
362 if not self.location:
363 self.location = resource_group.location
364
365 if self.query_string_caching_behavior:
366 self.query_string_caching_behavior = _snake_to_camel(self.query_string_caching_behavior, capitalize_first=True)
367
368 response = self.get_cdnendpoint()
369
370 if self.state == 'present':
371
372 if not response:
373
374 if self.started is None:
375 # If endpoint doesn't exist and no start/stop operation specified, create endpoint.
376 if self.origins is None:
377 self.fail("Origins is not provided when trying to create endpoint")
378 self.log("Need to create the Azure CDN endpoint")
379
380 if not self.check_mode:
381 result = self.create_cdnendpoint()
382 self.results['id'] = result['id']
383 self.results['host_name'] = result['host_name']
384 self.log("Creation done")
385
386 self.results['changed'] = True
387 return self.results
388
389 else:
390 # Fail the module when user try to start/stop a non-existed endpoint
391 self.log("Can't stop/stop a non-existed endpoint")
392 self.fail("This endpoint is not found, stop/start is forbidden")
393
394 else:
395 self.log('Results : {0}'.format(response))
396 self.results['id'] = response['id']
397 self.results['host_name'] = response['host_name']
398
399 update_tags, response['tags'] = self.update_tags(response['tags'])
400
401 if update_tags:
402 to_be_updated = True
403
404 if response['provisioning_state'] == "Succeeded":
405 if self.started is False and response['resource_state'] == 'Running':
406 self.log("Need to stop the Azure CDN endpoint")
407
408 if not self.check_mode:
409 result = self.stop_cdnendpoint()
410 self.log("Endpoint stopped")
411
412 self.results['changed'] = True
413
414 elif self.started and response['resource_state'] == 'Stopped':
415 self.log("Need to start the Azure CDN endpoint")
416
417 if not self.check_mode:
418 result = self.start_cdnendpoint()
419 self.log("Endpoint started")
420
421 self.results['changed'] = True
422
423 elif self.started is not None:
424 self.module.warn("Start/Stop not performed due to current resource state {0}".format(response['resource_state']))
425 self.results['changed'] = False
426
427 if self.purge:
428 self.log("Need to purge endpoint")
429
430 if not self.check_mode:
431 result = self.purge_cdnendpoint()
432 self.log("Endpoint purged")
433
434 self.results['changed'] = True
435
436 to_be_updated = to_be_updated or self.check_update(response)
437
438 if to_be_updated:
439 self.log("Need to update the Azure CDN endpoint")
440 self.results['changed'] = True
441
442 if not self.check_mode:
443 result = self.update_cdnendpoint()
444 self.results['host_name'] = result['host_name']
445 self.log("Update done")
446
447 elif self.started is not None:
448 self.module.warn("Start/Stop not performed due to current provisioning state {0}".format(response['provisioning_state']))
449 self.results['changed'] = False
450
451 elif self.state == 'absent' and response:
452 self.log("Need to delete the Azure CDN endpoint")
453 self.results['changed'] = True
454
455 if not self.check_mode:
456 self.delete_cdnendpoint()
457 self.log("Azure CDN endpoint deleted")
458
459 return self.results
460
461 def create_cdnendpoint(self):
462 '''
463 Creates a Azure CDN endpoint.
464
465 :return: deserialized Azure CDN endpoint instance state dictionary
466 '''
467 self.log("Creating the Azure CDN endpoint instance {0}".format(self.name))
468
469 origins = []
470 for item in self.origins:
471 origins.append(
472 DeepCreatedOrigin(name=item['name'],
473 host_name=item['host_name'],
474 http_port=item['http_port'] if 'http_port' in item else None,
475 https_port=item['https_port'] if 'https_port' in item else None)
476 )
477
478 parameters = Endpoint(
479 origins=origins,
480 location=self.location,
481 tags=self.tags,
482 origin_host_header=self.origin_host_header,
483 origin_path=self.origin_path,
484 content_types_to_compress=default_content_types() if self.is_compression_enabled and not self.content_types_to_compress
485 else self.content_types_to_compress,
486 is_compression_enabled=self.is_compression_enabled if self.is_compression_enabled is not None else False,
487 is_http_allowed=self.is_http_allowed if self.is_http_allowed is not None else True,
488 is_https_allowed=self.is_https_allowed if self.is_https_allowed is not None else True,
489 query_string_caching_behavior=self.query_string_caching_behavior if self.query_string_caching_behavior
490 else QueryStringCachingBehavior.ignore_query_string
491 )
492
493 try:
494 poller = self.cdn_client.endpoints.begin_create(self.resource_group, self.profile_name, self.name, parameters)
495 response = self.get_poller_result(poller)
496 return cdnendpoint_to_dict(response)
497 except Exception as exc:
498 self.log('Error attempting to create Azure CDN endpoint instance.')
499 self.fail("Error creating Azure CDN endpoint instance: {0}".format(exc.message))
500
501 def update_cdnendpoint(self):
502 '''
503 Updates a Azure CDN endpoint.
504
505 :return: deserialized Azure CDN endpoint instance state dictionary
506 '''
507 self.log("Updating the Azure CDN endpoint instance {0}".format(self.name))
508
509 endpoint_update_properties = EndpointUpdateParameters(
510 tags=self.tags,
511 origin_host_header=self.origin_host_header,
512 origin_path=self.origin_path,
513 content_types_to_compress=default_content_types() if self.is_compression_enabled and not self.content_types_to_compress
514 else self.content_types_to_compress,
515 is_compression_enabled=self.is_compression_enabled,
516 is_http_allowed=self.is_http_allowed,
517 is_https_allowed=self.is_https_allowed,
518 query_string_caching_behavior=self.query_string_caching_behavior,
519 )
520
521 try:
522 poller = self.cdn_client.endpoints.begin_update(self.resource_group, self.profile_name, self.name, endpoint_update_properties)
523 response = self.get_poller_result(poller)
524 return cdnendpoint_to_dict(response)
525 except Exception as exc:
526 self.log('Error attempting to update Azure CDN endpoint instance.')
527 self.fail("Error updating Azure CDN endpoint instance: {0}".format(exc.message))
528
529 def delete_cdnendpoint(self):
530 '''
531 Deletes the specified Azure CDN endpoint in the specified subscription and resource group.
532
533 :return: True
534 '''
535 self.log("Deleting the Azure CDN endpoint {0}".format(self.name))
536 try:
537 poller = self.cdn_client.endpoints.begin_delete(self.resource_group, self.profile_name, self.name)
538 self.get_poller_result(poller)
539 return True
540 except Exception as e:
541 self.log('Error attempting to delete the Azure CDN endpoint.')
542 self.fail("Error deleting the Azure CDN endpoint: {0}".format(e.message))
543 return False
544
545 def get_cdnendpoint(self):
546 '''
547 Gets the properties of the specified Azure CDN endpoint.
548
549 :return: deserialized Azure CDN endpoint state dictionary
550 '''
551 self.log(
552 "Checking if the Azure CDN endpoint {0} is present".format(self.name))
553 try:
554 response = self.cdn_client.endpoints.get(self.resource_group, self.profile_name, self.name)
555 self.log("Response : {0}".format(response))
556 self.log("Azure CDN endpoint : {0} found".format(response.name))
557 return cdnendpoint_to_dict(response)
558 except Exception:
559 self.log('Did not find the Azure CDN endpoint.')
560 return False
561
562 def start_cdnendpoint(self):
563 '''
564 Starts an existing Azure CDN endpoint that is on a stopped state.
565
566 :return: deserialized Azure CDN endpoint state dictionary
567 '''
568 self.log(
569 "Starting the Azure CDN endpoint {0}".format(self.name))
570 try:
571 poller = self.cdn_client.endpoints.begin_start(self.resource_group, self.profile_name, self.name)
572 response = self.get_poller_result(poller)
573 self.log("Response : {0}".format(response))
574 self.log("Azure CDN endpoint : {0} started".format(response.name))
575 return self.get_cdnendpoint()
576 except Exception:
577 self.log('Fail to start the Azure CDN endpoint.')
578 return False
579
580 def purge_cdnendpoint(self):
581 '''
582 Purges an existing Azure CDN endpoint.
583
584 :return: deserialized Azure CDN endpoint state dictionary
585 '''
586 self.log(
587 "Purging the Azure CDN endpoint {0}".format(self.name))
588 try:
589 poller = self.cdn_client.endpoints.begin_purge_content(self.resource_group,
590 self.profile_name,
591 self.name,
592 content_file_paths=dict(content_paths=self.purge_content_paths))
593 response = self.get_poller_result(poller)
594 self.log("Response : {0}".format(response))
595 return self.get_cdnendpoint()
596 except Exception as e:
597 self.fail('Fail to purge the Azure CDN endpoint.')
598 return False
599
600 def stop_cdnendpoint(self):
601 '''
602 Stops an existing Azure CDN endpoint that is on a running state.
603
604 :return: deserialized Azure CDN endpoint state dictionary
605 '''
606 self.log(
607 "Stopping the Azure CDN endpoint {0}".format(self.name))
608 try:
609 poller = self.cdn_client.endpoints.begin_stop(self.resource_group, self.profile_name, self.name)
610 response = self.get_poller_result(poller)
611 self.log("Response : {0}".format(response))
612 self.log("Azure CDN endpoint : {0} stopped".format(response.name))
613 return self.get_cdnendpoint()
614 except Exception:
615 self.log('Fail to stop the Azure CDN endpoint.')
616 return False
617
618 def check_update(self, response):
619
620 if self.origin_host_header and response['origin_host_header'] != self.origin_host_header:
621 self.log("Origin host header Diff - Origin {0} / Update {1}".format(response['origin_host_header'], self.origin_host_header))
622 return True
623
624 if self.origin_path and response['origin_path'] != self.origin_path:
625 self.log("Origin path Diff - Origin {0} / Update {1}".format(response['origin_path'], self.origin_path))
626 return True
627
628 if self.content_types_to_compress and response['content_types_to_compress'] != self.content_types_to_compress:
629 self.log("Content types to compress Diff - Origin {0} / Update {1}".format(response['content_types_to_compress'], self.content_types_to_compress))
630 return True
631
632 if self.is_compression_enabled is not None and response['is_compression_enabled'] != self.is_compression_enabled:
633 self.log("is_compression_enabled Diff - Origin {0} / Update {1}".format(response['is_compression_enabled'], self.is_compression_enabled))
634 return True
635
636 if self.is_http_allowed is not None and response['is_http_allowed'] != self.is_http_allowed:
637 self.log("is_http_allowed Diff - Origin {0} / Update {1}".format(response['is_http_allowed'], self.is_http_allowed))
638 return True
639
640 if self.is_https_allowed is not None and response['is_https_allowed'] != self.is_https_allowed:
641 self.log("is_https_allowed Diff - Origin {0} / Update {1}".format(response['is_https_allowed'], self.is_https_allowed))
642 return True
643
644 if self.query_string_caching_behavior and \
645 _snake_to_camel(response['query_string_caching_behavior']).lower() != _snake_to_camel(self.query_string_caching_behavior).lower():
646 self.log("query_string_caching_behavior Diff - Origin {0} / Update {1}".format(response['query_string_caching_behavior'],
647 self.query_string_caching_behavior))
648 return True
649
650 return False
651
652
653 def main():
654 """Main execution"""
655 AzureRMCdnendpoint()
656
657
658 if __name__ == '__main__':
659 main()