Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4 #
5 # Python SDK Reference: https://learn.microsoft.com/en-us/python/api/azure-mgmt-cdn/azure.mgmt.cdn.operations.routesoperations?view=azure-python
6 #
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10 DOCUMENTATION = '''
11 ---
12 module: azure_rm_afdroute
13 version_added: "3.4.0"
14 short_description: Manage an Azure Front Door Route
15 description:
16 - Create, update and delete an Azure Front Door Route to be used by a Front Door Service Profile created using azure_rm_cdnprofile.
17
18 options:
19 content_types_to_compress:
20 description:
21 - The caching configuration/compression settings for this route.
22 - List of content types (str) on which compression applies. The value should be a valid MIME type.
23 - Required together (is_compression_enabled, content_types_to_compress, query_string_caching_behavior, query_parameters)
24 type: list
25 elements: str
26 custom_domains:
27 description:
28 - Domain names referenced by this endpoint. ID will be looked up based on the name.
29 type: list
30 elements: str
31 disable_cache_configuration:
32 description:
33 - To disable cache configuration, set this to true and do not include cache_configuration.
34 - This will override any cache_configuration settings you include.
35 type: bool
36 default: false
37 enabled_state:
38 description:
39 - Whether to enable use of this rule. Permitted values are 'Enabled' or 'Disabled'.
40 type: str
41 choices:
42 - Enabled
43 - Disabled
44 endpoint_name:
45 description:
46 - Name of the endpoint under the profile which is unique globally.
47 required: true
48 type: str
49 forwarding_protocol:
50 description:
51 - Protocol this rule will use when forwarding traffic to backends.
52 type: str
53 choices:
54 - HttpOnly
55 - HttpsOnly
56 - MatchRequest
57 https_redirect:
58 description:
59 - Whether to automatically redirect HTTP traffic to HTTPS traffic.
60 type: str
61 default: Disabled
62 choices:
63 - Enabled
64 - Disabled
65 is_compression_enabled:
66 description:
67 - The caching configuration/compression settings for this route.
68 - Indicates whether content compression is enabled on AzureFrontDoor.
69 - If compression is enabled, content will be served as compressed if user requests for a compressed version.
70 - Content won't be compressed on AzureFrontDoor when requested content is smaller than 1 byte or larger than 1 MB.
71 - Required together (is_compression_enabled, content_types_to_compress, query_string_caching_behavior, query_parameters)
72 type: bool
73 link_to_default_domain:
74 description:
75 - whether this route will be linked to the default endpoint domain.
76 type: str
77 default: Disabled
78 choices:
79 - Enabled
80 - Disabled
81 name:
82 description:
83 - Name of the routing rule.
84 required: true
85 type: str
86 origin_group:
87 description:
88 - A reference to the origin group.
89 type: str
90 origin_path:
91 description:
92 - A directory path on the origin that AzureFrontDoor can use to retrieve content from, e.g. contoso.cloudapp.net/originpath.
93 type: str
94 patterns_to_match:
95 description:
96 - The route patterns of the rule.
97 type: list
98 elements: str
99 profile_name:
100 description:
101 - Name of the Azure Front Door Standard or Azure Front Door Premium profile which is unique within the resource group.
102 required: true
103 type: str
104 query_parameters:
105 description:
106 - The caching configuration for this route.
107 - query parameters to include or exclude (comma separated).
108 - Required together (is_compression_enabled, content_types_to_compress, query_string_caching_behavior, query_parameters)
109 type: str
110 query_string_caching_behavior:
111 description:
112 - The caching configuration for this route.
113 - Defines how Frontdoor caches requests that include query strings.
114 - You can ignore any query strings when caching, ignore specific query strings,
115 - cache every request with a unique URL, or cache specific query strings.
116 - Required together (is_compression_enabled, content_types_to_compress, query_string_caching_behavior, query_parameters)
117 type: str
118 choices:
119 - IgnoreQueryString
120 - IgnoreSpecifiedQueryStrings
121 - IncludeSpecifiedQueryStrings
122 - UseQueryString
123 resource_group:
124 description:
125 - Name of the Resource group within the Azure subscription.
126 required: true
127 type: str
128 rule_sets:
129 description:
130 - List of rule set names referenced by this endpoint.
131 type: list
132 elements: str
133 state:
134 description:
135 - Assert the state of the Route. Use C(present) to create or update a CDN profile and C(absent) to delete it.
136 default: present
137 type: str
138 choices:
139 - absent
140 - present
141 supported_protocols:
142 description:
143 - List of supported protocols for this route.
144 type: list
145 elements: str
146 default: ['Http', 'Https']
147 choices:
148 - Http
149 - Https
150
151 extends_documentation_fragment:
152 - azure.azcollection.azure
153
154 author:
155 - Jarret Tooley (@jartoo)
156 '''
157
158 EXAMPLES = '''
159 - name: Create an AFD Route
160 azure_rm_afdroute:
161 name: myRoute
162 endpoint_name: myEndpoint
163 origin_group: myOriginGroup
164 profile_name: myProfile
165 resource_group_name: myResourceGroup
166 state: present
167 route:
168 enabled_state: Disabled
169 forwarding_protocol: HttpsOnly
170 https_redirect: Enabled
171 patterns_to_match:
172 - "/*"
173 rule_sets:
174 - Security
175 supported_protocols:
176 - Https
177 - Http
178 link_to_default_domain: Enabled
179
180 - name: Delete an AFD Origin
181 azure_rm_afdroute:
182 name: myRoute
183 endpoint_name: myEndpoint
184 origin_group: myOriginGroup
185 profile_name: myProfile
186 resource_group_name: myResourceGroup
187 state: absent
188 '''
189 RETURN = '''
190 id:
191 description:
192 - ID of the Route.
193 returned: always
194 type: str
195 sample: "id: '/subscriptions/xxxxxx-xxxx-xxxx-xxxx-xxxxxxxx/resourcegroups/myRG/providers/Microsoft.Cdn/profiles/myProf/afdendpoints/myEP/routes/myRoute'"
196 '''
197 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase
198 # from azure.core.serialization import NULL as AzureCoreNull
199
200 try:
201 from azure.mgmt.cdn.models import Route, RouteUpdateParameters, CompressionSettings, \
202 ResourceReference, AfdRouteCacheConfiguration
203 except ImportError as ec:
204 # This is handled in azure_rm_common
205 pass
206
207
208 class AzureRMRoute(AzureRMModuleBase):
209 ''' Main Class '''
210 def __init__(self):
211 self.module_arg_spec = dict(
212 content_types_to_compress=dict(
213 type='list',
214 elements='str'
215 ),
216 custom_domains=dict(
217 type='list',
218 elements='str'
219 ),
220 disable_cache_configuration=dict(
221 type='bool',
222 default=False
223 ),
224 enabled_state=dict(
225 type='str',
226 choices=['Enabled', 'Disabled']
227 ),
228 endpoint_name=dict(
229 type='str',
230 required=True
231 ),
232 forwarding_protocol=dict(
233 type='str',
234 choices=['HttpOnly', 'HttpsOnly', 'MatchRequest']
235 ),
236 https_redirect=dict(
237 type='str',
238 choices=['Enabled', 'Disabled'],
239 default='Disabled'
240 ),
241 is_compression_enabled=dict(
242 type='bool'
243 ),
244 link_to_default_domain=dict(
245 type='str',
246 choices=['Enabled', 'Disabled'],
247 default='Disabled'
248 ),
249 name=dict(
250 type='str',
251 required=True
252 ),
253 origin_group=dict(
254 type='str'
255 ),
256 origin_path=dict(
257 type='str'
258 ),
259 patterns_to_match=dict(
260 type='list',
261 elements='str'
262 ),
263 profile_name=dict(
264 type='str',
265 required=True
266 ),
267 query_string_caching_behavior=dict(
268 type='str',
269 choices=['IgnoreQueryString', 'IgnoreSpecifiedQueryStrings', 'IncludeSpecifiedQueryStrings', 'UseQueryString']
270 ),
271 query_parameters=dict(
272 type='str'
273 ),
274 resource_group=dict(
275 type='str',
276 required=True
277 ),
278 rule_sets=dict(
279 type='list',
280 elements='str'
281 ),
282 state=dict(
283 type='str',
284 default='present',
285 choices=['present', 'absent']
286 ),
287 supported_protocols=dict(
288 type='list',
289 elements='str',
290 choices=['Http', 'Https'],
291 default=['Http', 'Https']
292 )
293 )
294
295 self.content_types_to_compress = None
296 self.custom_domains = None
297 self.disable_cache_configuration = None
298 self.enabled_state = None
299 self.forwarding_protocol = None
300 self.https_redirect = None
301 self.is_compression_enabled = None
302 self.link_to_default_domain = None
303 self.origin_path = None
304 self.origin_group = None
305 self.patterns_to_match = None
306 self.query_parameters = None
307 self.query_string_caching_behavior = None
308 self.rule_sets = []
309 self.supported_protocols = None
310
311 self.origin_group_id = None
312
313 self.name = None
314 self.endpoint_name = None
315 self.profile_name = None
316 self.resource_group = None
317 self.state = None
318
319 self.rule_set_ids = []
320 self.custom_domain_ids = []
321
322 required_together = [['is_compression_enabled', 'content_types_to_compress', 'query_string_caching_behavior', 'query_parameters']]
323
324 self.results = dict(changed=False)
325
326 super(AzureRMRoute, self).__init__(
327 derived_arg_spec=self.module_arg_spec,
328 supports_check_mode=True,
329 supports_tags=False,
330 required_together=required_together
331 )
332
333 def exec_module(self, **kwargs):
334 """Main module execution method"""
335
336 for key in list(self.module_arg_spec.keys()):
337 setattr(self, key, kwargs[key])
338
339 to_be_updated = False
340
341 # Ignore query_parameters when query_string_caching_behavior is "IgnoreQueryString" or "UseQueryString"
342 if self.query_string_caching_behavior in ["IgnoreQueryString", "UseQueryString"]:
343 self.query_parameters = None
344 self.log("Ignoring query_parameters when query_string_caching_behavior is IgnoreQueryString or UseQueryString")
345
346 # Get the existing resource
347 response = self.get_route()
348
349 if self.state == 'present':
350 # Get the Origin Group ID
351 self.origin_group_id = self.get_origin_group_id()
352 if self.origin_group_id is False:
353 self.fail("Could not obtain Origin Group ID from {0}, please create it first.".format(self.origin_group))
354
355 # Get a list of all the Custom Domain IDs
356 if isinstance(self.custom_domains, list):
357 if len(self.custom_domains) > 0:
358 for custom_domain in self.custom_domains:
359 cd_id = self.get_custom_domain_id(custom_domain)
360 if cd_id:
361 ref = ResourceReference(
362 id=cd_id)
363 self.custom_domain_ids.append(ref)
364
365 # Populate the rule_set_ids
366 convert_rules = self.get_rule_set_ids()
367 if not convert_rules:
368 self.fail("Failed to convert the Rule Set names to IDs")
369
370 if not response:
371 self.log("Need to create the Route")
372
373 if not self.check_mode:
374 new_results = self.create_route()
375 self.results['id'] = new_results['id']
376 self.results['changed'] = True
377
378 else:
379 self.log('Results : {0}'.format(response))
380
381 to_be_updated = self.update_needed(response)
382
383 self.results['id'] = response['id']
384 if to_be_updated:
385 self.log("Need to update the Route")
386
387 if not self.check_mode:
388 new_results = self.update_route()
389 self.results['id'] = new_results['id']
390
391 self.results['changed'] = True
392
393 elif self.state == 'absent':
394 if not response:
395 self.log("Route {0} does not exist.".format(self.name))
396 self.results['id'] = None
397 self.results['changed'] = False
398 else:
399 self.log("Need to delete the Route")
400 self.results['changed'] = True
401
402 if not self.check_mode:
403 self.delete_route()
404 self.results['id'] = response['id']
405 return self.results
406
407 def update_needed(self, response):
408 '''
409 Check if the resource needs to be updated
410
411 return: bool
412 '''
413 to_be_updated = False
414 cache_configuration = response['cache_configuration']
415 if cache_configuration and self.disable_cache_configuration:
416 to_be_updated = True
417 if cache_configuration:
418 if cache_configuration.query_parameters != self.query_parameters and self.query_parameters:
419 to_be_updated = True
420 if cache_configuration.query_string_caching_behavior != self.query_string_caching_behavior and self.query_string_caching_behavior:
421 to_be_updated = True
422 if cache_configuration.compression_settings.is_compression_enabled != self.is_compression_enabled and self.is_compression_enabled:
423 to_be_updated = True
424 if cache_configuration.compression_settings.content_types_to_compress != self.content_types_to_compress and self.content_types_to_compress:
425 to_be_updated = True
426 else:
427 if self.is_compression_enabled or self.query_parameters or self.query_string_caching_behavior or self.content_types_to_compress:
428 to_be_updated = True
429 # Test for custom_domain equality
430 equal = True
431 if len(response['custom_domains']) != len(self.custom_domain_ids):
432 equal = False
433 for x in response['custom_domains']:
434 found = False
435 for y in self.custom_domain_ids:
436 if x.id == y.id:
437 found = True
438 continue
439 if not found:
440 equal = False
441 if not equal:
442 to_be_updated = True
443
444 if response['enabled_state'] != self.enabled_state and self.enabled_state:
445 to_be_updated = True
446 if response['forwarding_protocol'] != self.forwarding_protocol and self.forwarding_protocol:
447 to_be_updated = True
448 if response['https_redirect'] != self.https_redirect and self.https_redirect:
449 to_be_updated = True
450 if response['link_to_default_domain'] != self.link_to_default_domain and self.link_to_default_domain:
451 to_be_updated = True
452 if response['origin_group_id'] != self.origin_group_id and self.origin_group_id:
453 to_be_updated = True
454 if response['origin_path'] != self.origin_path and self.origin_path:
455 to_be_updated = True
456 if response['patterns_to_match'] != self.patterns_to_match and self.patterns_to_match:
457 to_be_updated = True
458 if response["rule_sets"] != self.rule_set_ids and self.rule_set_ids:
459 to_be_updated = True
460 if response['supported_protocols'] != self.supported_protocols and self.supported_protocols:
461 to_be_updated = True
462
463 return to_be_updated
464
465 def create_route(self):
466 '''
467 Creates a Azure Route.
468
469 :return: deserialized Azure Route instance state dictionary
470 '''
471 self.log("Creating the Azure Route instance {0}".format(self.name))
472 cache_configuration = None
473 compression_settings = None
474
475 if self.disable_cache_configuration:
476 # cache_configuration = AzureCoreNull # Reported as issue to azure-mgmt-cdn: https://github.com/Azure/azure-sdk-for-python/issues/35801
477 cache_configuration = None
478 else:
479 if not self.is_compression_enabled and not self.content_types_to_compress:
480 compression_settings = None
481 else:
482 compression_settings = CompressionSettings(
483 content_types_to_compress=self.content_types_to_compress,
484 is_compression_enabled=self.is_compression_enabled
485 )
486 if not self.query_string_caching_behavior and not self.query_parameters and not compression_settings:
487 cache_configuration = None
488 else:
489 cache_configuration = AfdRouteCacheConfiguration(
490 query_string_caching_behavior=self.query_string_caching_behavior,
491 query_parameters=self.query_parameters,
492 compression_settings=compression_settings
493 )
494
495 origin_group = ResourceReference(
496 id=self.origin_group_id
497 )
498
499 parameters = Route(
500 cache_configuration=cache_configuration,
501 custom_domains=self.custom_domain_ids,
502 enabled_state=self.enabled_state,
503 forwarding_protocol=self.forwarding_protocol,
504 https_redirect=self.https_redirect,
505 link_to_default_domain=self.link_to_default_domain,
506 origin_group=origin_group,
507 origin_path=self.origin_path,
508 patterns_to_match=self.patterns_to_match,
509 rule_sets=self.rule_set_ids,
510 supported_protocols=self.supported_protocols
511 )
512
513 try:
514 poller = self.cdn_client.routes.begin_create(
515 resource_group_name=self.resource_group,
516 profile_name=self.profile_name,
517 endpoint_name=self.endpoint_name,
518 route_name=self.name,
519 route=parameters
520 )
521 response = self.get_poller_result(poller)
522 return route_to_dict(response)
523 except Exception as exc:
524 self.log('Error attempting to create Azure Route instance.')
525 self.fail("Error Creating Azure Route instance: {0}".format(str(exc)))
526
527 def update_route(self):
528 '''
529 Updates an Azure Route.
530
531 :return: deserialized Azure Route instance state dictionary
532 '''
533 self.log("Updating the Azure Route instance {0}".format(self.name))
534
535 cache_configuration = None
536 compression_settings = None
537
538 if self.disable_cache_configuration:
539 # cache_configuration = AzureCoreNull # Reported as issue to azure-mgmt-cdn: https://github.com/Azure/azure-sdk-for-python/issues/35801
540 cache_configuration = None
541 else:
542 if not self.is_compression_enabled and not self.content_types_to_compress:
543 compression_settings = None
544 else:
545 compression_settings = CompressionSettings(
546 content_types_to_compress=self.content_types_to_compress,
547 is_compression_enabled=self.is_compression_enabled
548 )
549 if not self.query_string_caching_behavior and not self.query_parameters and not compression_settings:
550 cache_configuration = None
551 else:
552 cache_configuration = AfdRouteCacheConfiguration(
553 query_string_caching_behavior=self.query_string_caching_behavior,
554 query_parameters=self.query_parameters,
555 compression_settings=compression_settings
556 )
557
558 origin_group = ResourceReference(
559 id=self.origin_group_id
560 )
561
562 parameters = RouteUpdateParameters(
563 cache_configuration=cache_configuration,
564 custom_domains=self.custom_domain_ids,
565 enabled_state=self.enabled_state,
566 forwarding_protocol=self.forwarding_protocol,
567 https_redirect=self.https_redirect,
568 link_to_default_domain=self.link_to_default_domain,
569 origin_group=origin_group,
570 origin_path=self.origin_path,
571 patterns_to_match=self.patterns_to_match,
572 rule_sets=self.rule_set_ids,
573 supported_protocols=self.supported_protocols
574 )
575
576 try:
577 poller = self.cdn_client.routes.begin_update(
578 resource_group_name=self.resource_group,
579 profile_name=self.profile_name,
580 endpoint_name=self.endpoint_name,
581 route_name=self.name,
582 route_update_properties=parameters
583 )
584 response = self.get_poller_result(poller)
585 return route_to_dict(response)
586 except Exception as exc:
587 self.log('Error attempting to update Azure Route instance.')
588 self.fail("Error updating Azure Route instance: {0}".format(str(exc)))
589
590 def delete_route(self):
591 '''
592 Deletes the specified Azure Route in the specified subscription and resource group.
593
594 :return: True
595 '''
596 self.log("Deleting the Route {0}".format(self.name))
597 try:
598 poller = self.cdn_client.routes.begin_delete(
599 resource_group_name=self.resource_group,
600 profile_name=self.profile_name,
601 endpoint_name=self.endpoint_name,
602 route_name=self.name
603 )
604 self.get_poller_result(poller)
605 return True
606 except Exception as exc:
607 self.log('Error attempting to delete the Route.')
608 self.fail("Error deleting the Route: {0}".format(str(exc)))
609 return False
610
611 def get_route(self):
612 '''
613 Gets the properties of the specified Route.
614
615 :return: deserialized Route state dictionary
616 '''
617 self.log(
618 "Checking if the Route {0} is present".format(self.name))
619 try:
620 response = self.cdn_client.routes.get(
621 resource_group_name=self.resource_group,
622 profile_name=self.profile_name,
623 endpoint_name=self.endpoint_name,
624 route_name=self.name,
625 )
626 self.log("Response : {0}".format(response))
627 self.log("Route : {0} found".format(response.name))
628 return route_to_dict(response)
629 except Exception as err:
630 self.log('Did not find the Route.' + err.args[0])
631 return False
632
633 def get_origin_group_id(self):
634 '''
635 Gets the ID of the specified Origin Group.
636
637 :return: ID for the Origin Group.
638 '''
639 self.log(
640 "Obtaining ID for Origin Group {0}".format(self.origin_group))
641 try:
642 response = self.cdn_client.afd_origin_groups.get(
643 resource_group_name=self.resource_group,
644 profile_name=self.profile_name,
645 origin_group_name=self.origin_group
646 )
647 self.log("Response : {0}".format(response))
648 self.log("Origin Group ID found : {0} found".format(response.id))
649 return response.id
650 except Exception as err:
651 self.log('Did not find the Origin Group.' + err.args[0])
652 return False
653
654 def get_custom_domain_id(self, custom_domain):
655 '''
656 Gets the ID of the specified Custom Domain.
657
658 :return: ID for the Custom Domain.
659 '''
660 self.log("Obtaining ID for Custom Domain {0}".format(self.origin_group))
661 try:
662 response = self.cdn_client.afd_custom_domains.get(
663 resource_group_name=self.resource_group,
664 profile_name=self.profile_name,
665 custom_domain_name=custom_domain
666 )
667 self.log("Response : {0}".format(response))
668 self.log("Custom Domain found : {0} found".format(response.id))
669 return response.id
670 except Exception as err:
671 self.log('Did not find the Custom Domain.' + err.args[0])
672 return False
673
674 def get_rule_set_ids(self):
675 '''
676 Gets the IDs of the specified Rule Sets.
677
678 :return: Boolean if Rule Sets were found and translated.
679 '''
680 if self.rule_sets is None or len(self.rule_sets) == 0:
681 return True
682
683 self.log("Obtaining IDs for Rule Sets")
684
685 try:
686 for rule_name in self.rule_sets:
687 response = self.cdn_client.rule_sets.get(
688 resource_group_name=self.resource_group,
689 profile_name=self.profile_name,
690 rule_set_name=rule_name,
691 )
692 self.log("Response : {0}".format(response))
693 self.log("Rule Set ID found : {0} found".format(response.id))
694 self.rule_set_ids.append(ResourceReference(id=response.id))
695 return True
696 except Exception as err:
697 self.log('Error getting the Rule Set IDs.' + err.args[0])
698 return False
699
700
701 def route_to_dict(route):
702 '''
703 Convert the object to dictionary
704 '''
705 return dict(
706 custom_domains=route.custom_domains,
707 cache_configuration=route.cache_configuration,
708 deployment_status=route.deployment_status,
709 enabled_state=route.enabled_state,
710 forwarding_protocol=route.forwarding_protocol,
711 https_redirect=route.https_redirect,
712 id=route.id,
713 link_to_default_domain=route.link_to_default_domain,
714 name=route.name,
715 origin_group_id=route.origin_group.id,
716 origin_path=route.origin_path,
717 patterns_to_match=route.patterns_to_match,
718 provisioning_state=route.provisioning_state,
719 rule_sets=route.rule_sets,
720 supported_protocols=route.supported_protocols,
721 type=route.type
722 )
723
724
725 def main():
726 """Main execution"""
727 AzureRMRoute()
728 # x = CdnManagementClient()
729 # x.routes.begin_update()
730
731
732 if __name__ == '__main__':
733 main()