Debian Codegraph @

ansible_collections/azure/azcollection/plugins/modules/azure_rm_afdrules.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.rulesoperations?view=azure-python
6
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10 DOCUMENTATION = '''
11 ---
12 module: azure_rm_afdrules
13 version_added: "3.4.0"
14 short_description: Manage an Azure Front Door Rules
15 description:
16 - Create, update and delete an Azure Front Door Rules to be used by a Front Door Service Profile created using azure_rm_cdnprofile.
17
18 options:
19 actions:
20 description:
21 - A list of actions that are executed when all the conditions of a rule are satisfied.
22 type: list
23 elements: dict
24 suboptions:
25 cache_behavior:
26 description:
27 - Caching behavior for the requests.
28 type: str
29 choices:
30 - BypassCache
31 - Override
32 - SetIfMissing
33 - HonorOrigin
34 - OverrideAlways
35 - OverrideIfOriginMissing
36 cache_duration:
37 description:
38 - The duration for which the content needs to be cached. Allowed format is [d.]hh:mm:ss.
39 type: str
40 custom_fragment:
41 description:
42 - Fragment to add to the redirect URL. Fragment is the part of the URL that comes after #. Do not include the #
43 type: str
44 custom_hostname:
45 description:
46 - Host to redirect. Leave empty to use the incoming host as the destination host.
47 type: str
48 custom_path:
49 description:
50 - The full path to redirect. Path cannot be empty and must start with /. Leave empty to use the incoming path as destination path.
51 type: str
52 custom_query_string:
53 description:
54 - The set of query strings to be placed in the redirect URL.
55 - Setting this value would replace any existing query string; leave empty to preserve the incoming query string.
56 - Query string must be in <key>=:code:<value> format. ? and & will be added automatically so do not include them.
57 type: str
58 destination:
59 description:
60 - Define the relative URL to which the above requests will be rewritten by.
61 type: str
62 destination_protocol:
63 description:
64 - Protocol to use for the redirect.
65 default: MatchRequest
66 type: str
67 choices:
68 - Http
69 - Https
70 - MatchRequest
71 forwarding_protocol:
72 description:
73 - Protocol this rule will use when forwarding traffic to backends.
74 default: MatchRequest
75 type: str
76 choices:
77 - Http
78 - Https
79 - MatchRequest
80 header_action:
81 description:
82 - Action to perform.
83 type: str
84 choices:
85 - Append
86 - Overwrite
87 - Delete
88 header_name:
89 description:
90 - Name of the header to modify.
91 type: str
92 is_compression_enabled:
93 description:
94 - The caching configuration for this route. Indicates whether content compression is enabled on AzureFrontDoor.
95 - If compression is enabled, content will be served as compressed if user requests for a compressed version.
96 - Content won't be compressed on AzureFrontDoor when requested content is smaller than 1 byte or larger than 1 MB.
97 type: str
98 choices:
99 - Enabled
100 - Disabled
101 name:
102 description:
103 - The name of the action for the delivery rule.
104 type: str
105 required: true
106 choices:
107 - ModifyRequestHeader
108 - ModifyResponseHeader
109 - RouteConfigurationOverride
110 - UrlRedirect
111 - UrlRewrite
112 origin_group:
113 description:
114 - defines the OriginGroup that would override the DefaultOriginGroup.
115 type: str
116 preserve_unmatched_path:
117 description:
118 - Whether to preserve unmatched path.
119 default: True
120 type: bool
121 query_parameters:
122 description:
123 - query parameters to include or exclude (comma separated).
124 type: str
125 query_string_caching_behavior:
126 description:
127 - The caching configuration for this route. Defines how Frontdoor caches requests that include query strings.
128 - You can ignore any query strings when caching, ignore specific query strings, cache every request with a unique URL,
129 - or cache specific query strings.
130 type: str
131 choices:
132 - IgnoreQueryString
133 - UseQueryString
134 - IgnoreSpecifiedQueryStrings
135 - IncludeSpecifiedQueryStrings
136 redirect_type:
137 description:
138 - The redirect type the rule will use when redirecting traffic.
139 type: str
140 choices:
141 - Moved
142 - Found
143 - TemporaryRedirect
144 - PermanentRedirect
145 source_pattern:
146 description:
147 - Define a request URI pattern that identifies the type of requests that may be rewritten.
148 - If value is blank, all strings are matched.
149 type: str
150 value:
151 description:
152 - Value for the specified action.
153 type: str
154 conditions:
155 description:
156 - A list of conditions that must be matched for the actions to be executed.
157 type: list
158 elements: dict
159 suboptions:
160 name:
161 description:
162 - The name of the condition for the delivery rule.
163 type: str
164 required: true
165 choices:
166 - ClientPort
167 - Cookies
168 - HostName
169 - HttpVersion
170 - IsDevice
171 - PostArgs
172 - QueryString
173 - RemoteAddress
174 - RequestBody
175 - RequestHeader
176 - RequestMethod
177 - RequestScheme
178 - RequestUri
179 - ServerPort
180 - SocketAddr
181 - SslProtocol
182 - UrlFileExtension
183 - UrlFileName
184 - UrlPath
185 operator:
186 description:
187 - Describes operator to be matched.
188 type: str
189 required: true
190 choices:
191 - Any
192 - Equal
193 - Contains
194 - BeginsWith
195 - EndsWith
196 - LessThan
197 - LessThanOrEqual
198 - GreaterThan
199 - GreaterThanOrEqual
200 - RegEx
201 - IPMatch
202 - GeoMatch
203 match_values:
204 description:
205 - The match value for the condition of the delivery rule.
206 type: list
207 elements: str
208 negate_condition:
209 description:
210 - Describes if this is a negate condition or not.
211 type: bool
212 selector:
213 description:
214 - Name of item to be matched.
215 type: str
216 transforms:
217 description:
218 - List of transforms.
219 type: list
220 elements: str
221 choices:
222 - Lowercase
223 - RemoveNulls
224 - Trim
225 - Uppercase
226 - URLDecode
227 - URLEncode
228 match_processing_behavior:
229 description:
230 - If this rule is a match should the rules engine continue running the remaining rules or stop.
231 default: Continue
232 type: str
233 choices:
234 - Continue
235 - Stop
236 name:
237 description:
238 - Name of the delivery rule which is unique within the endpoint.
239 required: true
240 type: str
241 order:
242 description:
243 - The order in which the rules are applied for the endpoint.
244 - A rule with a lesser order will be applied before a rule with a greater order. Rule with order 0 is a special rule.
245 - It does not require any condition and actions listed in it will always be applied.
246 type: int
247 profile_name:
248 description:
249 - Name of the Azure Front Door Standard or Azure Front Door Premium profile which is unique within the resource group.
250 required: true
251 type: str
252 resource_group:
253 description:
254 - Name of the Resource group within the Azure subscription.
255 required: true
256 type: str
257 rule_set_name:
258 description:
259 - Name of the rule set under the profile.
260 required: true
261 type: str
262 state:
263 description:
264 - Assert the state of the CDN profile. Use C(present) to create or update a CDN profile and C(absent) to delete it.
265 default: present
266 type: str
267 choices:
268 - absent
269 - present
270
271 extends_documentation_fragment:
272 - azure.azcollection.azure
273
274 author:
275 - Jarret Tooley (@jartoo)
276 '''
277 EXAMPLES = '''
278 - name: Create an AFD Rule with some actions and conditions
279 azure_rm_afdrules:
280 name: myRule1
281 rule_set_name: myRuleset
282 profile_name: myProfile
283 resource_group: myResourceGroup
284 match_processing_behavior: Continue
285 order: 1
286 action:
287 - name: ModifyResponseHeader
288 header_action: Append
289 header_name: Content-Security-Policy
290 value: "frame-ancestors 'response'"
291 - name: RouteConfigurationOverride
292 origin_group: "myOtherOriginGroup"
293 conditions:
294 - name: UrlPath
295 match_values:
296 - ".auth"
297 negate_condition: false
298 operator: "BeginsWith"
299 transforms:
300 - LowerCase
301 '''
302 RETURN = '''
303 id:
304 description:
305 - Resource ID.
306 returned: always
307 type: str
308 example: # TODO: Put example value in here
309 '''
310 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase
311
312 try:
313 from azure.mgmt.cdn.models import Rule, RuleUpdateParameters, ResourceReference
314
315 # Models for Actions:
316 from azure.mgmt.cdn.models import DeliveryRuleRequestHeaderAction, HeaderActionParameters # ModifyRequestHeader
317 from azure.mgmt.cdn.models import DeliveryRuleResponseHeaderAction # ModifyResponseHeader
318 from azure.mgmt.cdn.models import DeliveryRuleRouteConfigurationOverrideAction, RouteConfigurationOverrideActionParameters, \
319 OriginGroupOverride, ForwardingProtocol, CacheConfiguration # RouteConfigurationOverride
320 from azure.mgmt.cdn.models import UrlRedirectAction, UrlRedirectActionParameters # UrlRedirect
321 from azure.mgmt.cdn.models import UrlRewriteAction, UrlRewriteActionParameters # UrlRewrite
322
323 # Models for Conditions:
324 from azure.mgmt.cdn.models import DeliveryRuleClientPortCondition, ClientPortMatchConditionParameters # ClientPort
325 from azure.mgmt.cdn.models import DeliveryRuleCookiesCondition, CookiesMatchConditionParameters # Cookies
326 from azure.mgmt.cdn.models import DeliveryRuleHostNameCondition, HostNameMatchConditionParameters # HostName
327 from azure.mgmt.cdn.models import DeliveryRuleHttpVersionCondition, HttpVersionMatchConditionParameters # HttpVersion
328 from azure.mgmt.cdn.models import DeliveryRuleIsDeviceCondition, IsDeviceMatchConditionParameters # IsDevice
329 from azure.mgmt.cdn.models import DeliveryRulePostArgsCondition, PostArgsMatchConditionParameters # PostArgs
330 from azure.mgmt.cdn.models import DeliveryRuleQueryStringCondition, QueryStringMatchConditionParameters # QueryString
331 from azure.mgmt.cdn.models import DeliveryRuleRemoteAddressCondition, RemoteAddressMatchConditionParameters # RemoteAddress
332 from azure.mgmt.cdn.models import DeliveryRuleRequestBodyCondition, RequestBodyMatchConditionParameters # RequestBody
333 from azure.mgmt.cdn.models import DeliveryRuleRequestHeaderCondition, RequestHeaderMatchConditionParameters # RequestHeader
334 from azure.mgmt.cdn.models import DeliveryRuleRequestMethodCondition, RequestMethodMatchConditionParameters # RequestMethod
335 from azure.mgmt.cdn.models import DeliveryRuleRequestSchemeCondition, RequestSchemeMatchConditionParameters # RequestScheme
336 from azure.mgmt.cdn.models import DeliveryRuleRequestUriCondition, RequestUriMatchConditionParameters # RequestUri
337 from azure.mgmt.cdn.models import DeliveryRuleServerPortCondition, ServerPortMatchConditionParameters # ServerPort
338 from azure.mgmt.cdn.models import DeliveryRuleSocketAddrCondition, SocketAddrMatchConditionParameters # SocketAddr
339 from azure.mgmt.cdn.models import DeliveryRuleSslProtocolCondition, SslProtocolMatchConditionParameters # SslProtocol
340 from azure.mgmt.cdn.models import DeliveryRuleUrlFileExtensionCondition, UrlFileExtensionMatchConditionParameters # UrlFileExtension
341 from azure.mgmt.cdn.models import DeliveryRuleUrlFileNameCondition, UrlFileNameMatchConditionParameters # UrlFileName
342 from azure.mgmt.cdn.models import DeliveryRuleUrlPathCondition, UrlPathMatchConditionParameters # UrlPath
343
344 from azure.core.serialization import NULL as AzureCoreNull
345 except ImportError as ec:
346 # This is handled in azure_rm_common
347 pass
348
349
350 class AzureRMRules(AzureRMModuleBase):
351 ''' Class for Azure Front Door Rules '''
352
353 def __init__(self):
354 self.module_arg_spec = dict(
355 actions=dict(
356 type='list',
357 elements='dict',
358 options=dict(
359 cache_behavior=dict(
360 type='str',
361 choices=[
362 'BypassCache',
363 'Override',
364 'SetIfMissing',
365 'HonorOrigin',
366 'OverrideAlways',
367 'OverrideIfOriginMissing'
368 ]
369 ),
370 cache_duration=dict(type='str'),
371 custom_fragment=dict(type='str'),
372 custom_hostname=dict(type='str'),
373 custom_path=dict(type='str'),
374 custom_query_string=dict(type='str'),
375 destination=dict(type='str'),
376 destination_protocol=dict(
377 type='str',
378 default='MatchRequest',
379 choices=['Http', 'Https', 'MatchRequest']
380 ),
381 forwarding_protocol=dict(
382 type='str',
383 default="MatchRequest",
384 choices=['Http', 'Https', 'MatchRequest']
385 ),
386 header_action=dict(
387 type='str',
388 choices=['Append', 'Overwrite', 'Delete']
389 ),
390 header_name=dict(type='str'),
391 is_compression_enabled=dict(
392 type='str',
393 choices=['Enabled', 'Disabled']
394 ),
395 name=dict(
396 type='str',
397 required=True,
398 choices=[
399 'ModifyRequestHeader',
400 'ModifyResponseHeader',
401 'RouteConfigurationOverride',
402 'UrlRedirect',
403 'UrlRewrite'
404 ]
405 ),
406 origin_group=dict(type='str'),
407 preserve_unmatched_path=dict(type='bool', default=True),
408 query_parameters=dict(type='str'),
409 query_string_caching_behavior=dict(
410 type='str',
411 choices=[
412 "IgnoreQueryString",
413 "UseQueryString",
414 "IgnoreSpecifiedQueryStrings",
415 "IncludeSpecifiedQueryStrings"
416 ]
417 ),
418 redirect_type=dict(
419 type='str',
420 choices=[
421 "Moved",
422 "Found",
423 "TemporaryRedirect",
424 "PermanentRedirect"
425 ]
426 ),
427 source_pattern=dict(type='str'),
428 value=dict(type='str')
429 )
430 ),
431 conditions=dict(
432 type='list',
433 elements='dict',
434 options=dict(
435 name=dict(
436 type='str',
437 required=True,
438 choices=[
439 "ClientPort",
440 "Cookies",
441 "HostName",
442 "HttpVersion",
443 "IsDevice",
444 "PostArgs",
445 "QueryString",
446 "RemoteAddress",
447 "RequestBody",
448 "RequestHeader",
449 "RequestMethod",
450 "RequestScheme",
451 "RequestUri",
452 "ServerPort",
453 "SocketAddr",
454 "SslProtocol",
455 "UrlFileExtension",
456 "UrlFileName",
457 "UrlPath"
458 ]
459 ),
460 operator=dict(
461 type='str',
462 required=True,
463 choices=[
464 'Any',
465 'Equal',
466 'Contains',
467 'BeginsWith',
468 'EndsWith',
469 'LessThan',
470 'LessThanOrEqual',
471 'GreaterThan',
472 'GreaterThanOrEqual',
473 'RegEx',
474 'IPMatch',
475 'GeoMatch'
476 ]
477 ),
478 match_values=dict(type='list', elements='str'),
479 negate_condition=dict(type='bool'),
480 selector=dict(type='str'),
481 transforms=dict(
482 type='list',
483 elements='str',
484 choices=[
485 'Lowercase',
486 'RemoveNulls',
487 'Trim',
488 'Uppercase',
489 'URLDecode',
490 'URLEncode'
491 ]
492 )
493 )
494 ),
495 match_processing_behavior=dict(
496 type='str',
497 default='Continue',
498 choices=['Continue', 'Stop']
499 ),
500 name=dict(type='str', required=True),
501 order=dict(type='int'),
502 profile_name=dict(type='str', required=True),
503 resource_group=dict(type='str', required=True),
504 rule_set_name=dict(type='str', required=True),
505 state=dict(
506 type='str',
507 default='present',
508 choices=['present', 'absent']
509 )
510 )
511 self.actions = None
512 self.conditions = None
513 self.match_processing_behavior = None
514 self.rule_set_name = None
515
516 self.name = None
517 self.order = None
518 self.profile_name = None
519 self.resource_group = None
520 self.state = None
521
522 self.response = None
523 self.parameters = None
524
525 self.results = dict(changed=False)
526
527 super(AzureRMRules, self).__init__(
528 derived_arg_spec=self.module_arg_spec,
529 supports_check_mode=True,
530 supports_tags=False)
531
532 def check_for_field(self, param_list, item, field):
533 ''' Utility to check for a field and fail if not found '''
534 if field not in param_list.keys():
535 self.fail('Required field {1} missing for {0}'.format(item, field))
536 elif param_list[field] is None:
537 self.fail('Required field {1} missing for {0}'.format(item, field))
538 return
539
540 def check_required_fields(self):
541 ''' A slightly more complex parameters check for Actions and Conditions '''
542
543 if self.actions:
544 required_fields_actions = {
545 'ModifyRequestHeader': ['header_action', 'header_name'],
546 'ModifyResponseHeader': ['header_action', 'header_name'],
547 'RouteConfigurationOverride': [],
548 'UrlRedirect': ['redirect_type', 'custom_path'],
549 'UrlRewrite': ['source_pattern', 'destination']
550 }
551 for action in self.actions:
552 if 'name' not in action.keys():
553 self.fail("Required field 'Name' missing for Action")
554 fields = required_fields_actions[action['name']]
555 for field in fields:
556 self.check_for_field(action, action['name'], field)
557
558 if len(self.actions) > 10:
559 self.fail("Error: You cannot have more than 10 Actions in a single Rule.")
560
561 if self.conditions:
562 for condition in self.conditions:
563 if 'name' not in condition.keys():
564 self.fail("Required field 'Name' missing for Condition")
565 field = "operator"
566 self.check_for_field(condition, condition['name'], field)
567
568 if len(self.conditions) > 10:
569 self.fail("Error: You cannot have more than 10 Conditions in a single Rule.")
570
571 return False
572
573 def exec_module(self, **kwargs):
574 """Main module execution method"""
575
576 for key in list(self.module_arg_spec.keys()):
577 setattr(self, key, kwargs[key])
578
579 self.check_required_fields()
580
581 self.response = self.get_rule()
582
583 if self.state == 'present':
584
585 if not self.response:
586 self.log("Need to create the Rule")
587 self.build_parameters()
588
589 if not self.check_mode:
590 new_response = self.create_rules()
591 self.results['id'] = new_response['id']
592
593 self.results['changed'] = True
594
595 else:
596 self.build_parameters(update=True)
597 if self.check_if_rules_are_different():
598 self.update_rules()
599 self.results['changed'] = True
600
601 self.results['id'] = self.response['id']
602 self.log('Results : {0}'.format(self.response))
603
604 elif self.state == 'absent':
605 if not self.response:
606 self.log("Rule {0} does not exist.".format(self.name))
607 else:
608 self.log("Need to delete the Rule")
609 self.results['changed'] = True
610
611 self.results['id'] = self.response['id']
612 if not self.check_mode:
613 self.delete_rules()
614
615 return self.results
616
617 def create_rules(self):
618 '''
619 Creates a Azure Rules.
620
621 :return: deserialized Azure Rules instance state dictionary
622 '''
623 self.log("Creating the Azure Rules instance {0}".format(self.name))
624
625 try:
626 poller = self.cdn_client.rules.begin_create(
627 resource_group_name=self.resource_group,
628 profile_name=self.profile_name,
629 rule_set_name=self.rule_set_name,
630 rule_name=self.name,
631 rule=self.parameters
632 )
633 response = self.get_poller_result(poller)
634 return rules_to_dict(response)
635 except Exception as exc:
636 self.log('Error attempting to create Azure Rules instance.')
637 self.fail("Error Creating Azure Rules instance: {0}".format(str(exc)))
638
639 def update_rules(self):
640 '''
641 Update Azure Rules.
642
643 :return: deserialized Azure Rules instance state dictionary
644 '''
645 self.log("Updating the Azure Rules instance {0}".format(self.name))
646
647 try:
648 poller = self.cdn_client.rules.begin_update(
649 resource_group_name=self.resource_group,
650 profile_name=self.profile_name,
651 rule_set_name=self.rule_set_name,
652 rule_name=self.name,
653 rule_update_properties=self.parameters
654 )
655 response = self.get_poller_result(poller)
656 return rules_to_dict(response)
657 except Exception as exc:
658 self.log('Error attempting to update Azure Rules instance.')
659 self.fail("Error Updating Azure Rules instance: {0}".format(str(exc)))
660
661 def check_if_rules_are_different(self):
662 ''' Check if the Rules are different from what exists and what is defined in the yaml '''
663
664 if self.response['match_processing_behavior'] != self.match_processing_behavior:
665 return True
666 if self.response['order'] != self.order:
667 return True
668
669 if len(self.response['actions']) != len(self.actions):
670 return True
671 for i, item in enumerate(self.response['actions']):
672 for field in item:
673 if field not in ['type_name']:
674 if field not in ['cache_configuration', 'origin_group_override']:
675 if item[field] != self.actions[i][field]:
676 return True
677 elif field == 'origin_group_override':
678 if (not item[field] and self.actions[i].get("origin_group")) or (item[field] and not self.actions[i].get("origin_group")):
679 return True
680 if item[field] and self.actions[i].get("origin_group"): # They both exist so check if the values match
681 origin_group_id = item[field].origin_group.id
682 forwarding_protocol = item[field].forwarding_protocol
683 if origin_group_id != self.actions[i].get("origin_group_id"):
684 return True
685 if forwarding_protocol != self.actions[i].get("forwarding_protocol"):
686 return True
687 elif field == 'cache_configuration':
688 if not item[field] and (
689 self.actions[i].get("query_string_caching_behavior") or
690 self.actions[i].get("query_parameters") or
691 self.actions[i].get("is_compression_enabled") or
692 self.actions[i].get("cache_behavior") or
693 self.actions[i].get("cache_duration")
694 ):
695 return True
696 elif item[field] and not (
697 self.actions[i].get("query_string_caching_behavior") or
698 self.actions[i].get("query_parameters") or
699 self.actions[i].get("is_compression_enabled") or
700 self.actions[i].get("cache_behavior") or
701 self.actions[i].get("cache_duration")
702 ):
703 return True
704 elif item[field]:
705 if item[field].query_string_caching_behavior != self.actions[i].get("query_string_caching_behavior"):
706 return True
707 elif item[field].query_parameters != self.actions[i].get("query_parameters"):
708 return True
709 elif item[field].is_compression_enabled != self.actions[i].get("is_compression_enabled"):
710 return True
711 elif item[field].cache_behavior != self.actions[i].get("cache_behavior"):
712 return True
713 elif item[field].cache_duration != self.actions[i].get("cache_duration"):
714 return True
715 if len(self.response['conditions']) != len(self.conditions):
716 return True
717 for i, item in enumerate(self.response['conditions']):
718 for field in item:
719 if field not in ['type_name']:
720 if isinstance(item[field], list) and len(item[field]) == 0 and not self.conditions[i][field]:
721 pass # Catch the edge case where we have an empty list and a None object
722 elif item[field] is False and not self.conditions[i][field]:
723 pass # Catch where a default of False matches the None object
724 elif item[field] != self.conditions[i][field]:
725 return True
726 return False
727
728 def build_parameters(self, update=False):
729 ''' Build the parameters to be used by either Create or Update '''
730 conditions = None
731 if self.conditions:
732 conditions = []
733 for condition in self.conditions:
734 conditionrule = None
735 if condition.get('name') == 'ClientPort':
736 conditionrule = DeliveryRuleClientPortCondition(
737 parameters=ClientPortMatchConditionParameters(
738 type_name='DeliveryRuleClientPortConditionParameters',
739 operator=condition.get('operator'),
740 negate_condition=condition.get('negate_condition'),
741 match_values=condition.get('match_values'),
742 transforms=condition.get('transforms')
743 )
744 )
745 elif condition.get('name') == 'Cookies':
746 conditionrule = DeliveryRuleCookiesCondition(
747 parameters=CookiesMatchConditionParameters(
748 type_name='DeliveryRuleCookiesConditionParameters',
749 selector=condition.get('selector'),
750 operator=condition.get('operator'),
751 negate_condition=condition.get('negate_condition'),
752 match_values=condition.get('match_values'),
753 transforms=condition.get('transforms')
754 )
755 )
756 elif condition.get('name') == 'HostName':
757 conditionrule = DeliveryRuleHostNameCondition(
758 parameters=HostNameMatchConditionParameters(
759 type_name='DeliveryRuleHostNameConditionParameters',
760 operator=condition.get('operator'),
761 negate_condition=condition.get('negate_condition'),
762 match_values=condition.get('match_values'),
763 transforms=condition.get('transforms')
764 )
765 )
766 elif condition.get('name') == 'HttpVersion':
767 conditionrule = DeliveryRuleHttpVersionCondition(
768 parameters=HttpVersionMatchConditionParameters(
769 type_name='DeliveryRuleHttpVersionConditionParameters',
770 operator=condition.get('operator'),
771 negate_condition=condition.get('negate_condition'),
772 match_values=condition.get('match_values'),
773 transforms=condition.get('transforms')
774 )
775 )
776 elif condition.get('name') == 'IsDevice':
777 conditionrule = DeliveryRuleIsDeviceCondition(
778 parameters=IsDeviceMatchConditionParameters(
779 type_name='DeliveryRuleIsDeviceConditionParameters',
780 operator=condition.get('operator'),
781 negate_condition=condition.get('negate_condition'),
782 match_values=condition.get('match_values'),
783 transforms=condition.get('transforms')
784 )
785 )
786 elif condition.get('name') == 'PostArgs':
787 conditionrule = DeliveryRulePostArgsCondition(
788 parameters=PostArgsMatchConditionParameters(
789 type_name='DeliveryRulePostArgsConditionParameters',
790 selector=condition.get('selector'),
791 operator=condition.get('operator'),
792 negate_condition=condition.get('negate_condition'),
793 match_values=condition.get('match_values'),
794 transforms=condition.get('transforms')
795 )
796 )
797 elif condition.get('name') == 'QueryString':
798 conditionrule = DeliveryRuleQueryStringCondition(
799 parameters=QueryStringMatchConditionParameters(
800 type_name='DeliveryRuleQueryStringConditionParameters',
801 operator=condition.get('operator'),
802 negate_condition=condition.get('negate_condition'),
803 match_values=condition.get('match_values'),
804 transforms=condition.get('transforms')
805 )
806 )
807 elif condition.get('name') == 'RemoteAddress':
808 conditionrule = DeliveryRuleRemoteAddressCondition(
809 parameters=RemoteAddressMatchConditionParameters(
810 type_name='DeliveryRuleRemoteAddressConditionParameters',
811 operator=condition.get('operator'),
812 negate_condition=condition.get('negate_condition'),
813 match_values=condition.get('match_values'),
814 transforms=condition.get('transforms')
815 )
816 )
817 elif condition.get('name') == 'RequestBody':
818 conditionrule = DeliveryRuleRequestBodyCondition(
819 parameters=RequestBodyMatchConditionParameters(
820 type_name='DeliveryRuleRequestBodyConditionParameters',
821 operator=condition.get('operator'),
822 negate_condition=condition.get('negate_condition'),
823 match_values=condition.get('match_values'),
824 transforms=condition.get('transforms')
825 )
826 )
827 elif condition.get('name') == 'RequestHeader':
828 conditionrule = DeliveryRuleRequestHeaderCondition(
829 parameters=RequestHeaderMatchConditionParameters(
830 type_name='DeliveryRuleRequestHeaderConditionParameters',
831 selector=condition.get('selector'),
832 operator=condition.get('operator'),
833 negate_condition=condition.get('negate_condition'),
834 match_values=condition.get('match_values'),
835 transforms=condition.get('transforms')
836 )
837 )
838 elif condition.get('name') == 'RequestMethod':
839 conditionrule = DeliveryRuleRequestMethodCondition(
840 parameters=RequestMethodMatchConditionParameters(
841 type_name='DeliveryRuleRequestMethodConditionParameters',
842 operator=condition.get('operator'),
843 negate_condition=condition.get('negate_condition'),
844 match_values=condition.get('match_values'),
845 transforms=condition.get('transforms')
846 )
847 )
848 elif condition.get('name') == 'RequestScheme':
849 conditionrule = DeliveryRuleRequestSchemeCondition(
850 parameters=RequestSchemeMatchConditionParameters(
851 type_name='DeliveryRuleRequestSchemeConditionParameters',
852 operator=condition.get('operator'),
853 negate_condition=condition.get('negate_condition'),
854 match_values=condition.get('match_values'),
855 transforms=condition.get('transforms')
856 )
857 )
858 elif condition.get('name') == 'RequestUri':
859 conditionrule = DeliveryRuleRequestUriCondition(
860 parameters=RequestUriMatchConditionParameters(
861 type_name='DeliveryRuleRequestUriConditionParameters',
862 operator=condition.get('operator'),
863 negate_condition=condition.get('negate_condition'),
864 match_values=condition.get('match_values'),
865 transforms=condition.get('transforms')
866 )
867 )
868 elif condition.get('name') == 'ServerPort':
869 conditionrule = DeliveryRuleServerPortCondition(
870 parameters=ServerPortMatchConditionParameters(
871 type_name='DeliveryRuleServerPortConditionParameters',
872 operator=condition.get('operator'),
873 negate_condition=condition.get('negate_condition'),
874 match_values=condition.get('match_values'),
875 transforms=condition.get('transforms')
876 )
877 )
878 elif condition.get('name') == 'SocketAddr':
879 conditionrule = DeliveryRuleSocketAddrCondition(
880 parameters=SocketAddrMatchConditionParameters(
881 type_name='DeliveryRuleSocketAddrConditionParameters',
882 operator=condition.get('operator'),
883 negate_condition=condition.get('negate_condition'),
884 match_values=condition.get('match_values'),
885 transforms=condition.get('transforms')
886 )
887 )
888 elif condition.get('name') == 'SslProtocol':
889 conditionrule = DeliveryRuleSslProtocolCondition(
890 parameters=SslProtocolMatchConditionParameters(
891 type_name='DeliveryRuleSslProtocolConditionParameters',
892 operator=condition.get('operator'),
893 negate_condition=condition.get('negate_condition'),
894 match_values=condition.get('match_values'),
895 transforms=condition.get('transforms')
896 )
897 )
898 elif condition.get('name') == 'UrlFileExtension':
899 conditionrule = DeliveryRuleUrlFileExtensionCondition(
900 parameters=UrlFileExtensionMatchConditionParameters(
901 type_name='DeliveryRuleUrlFileExtensionMatchConditionParameters',
902 operator=condition.get('operator'),
903 negate_condition=condition.get('negate_condition'),
904 match_values=condition.get('match_values'),
905 transforms=condition.get('transforms')
906 )
907 )
908 elif condition.get('name') == 'UrlFileName':
909 conditionrule = DeliveryRuleUrlFileNameCondition(
910 parameters=UrlFileNameMatchConditionParameters(
911 type_name='DeliveryRuleUrlFilenameConditionParameters',
912 operator=condition.get('operator'),
913 negate_condition=condition.get('negate_condition'),
914 match_values=condition.get('match_values'),
915 transforms=condition.get('transforms')
916 )
917 )
918 elif condition.get('name') == 'UrlPath':
919 conditionrule = DeliveryRuleUrlPathCondition(
920 parameters=UrlPathMatchConditionParameters(
921 type_name='DeliveryRuleUrlPathMatchConditionParameters',
922 operator=condition.get('operator'),
923 negate_condition=condition.get('negate_condition'),
924 match_values=condition.get('match_values'),
925 transforms=condition.get('transforms')
926 )
927 )
928 if conditionrule:
929 conditions.append(conditionrule)
930
931 actions = None
932 if self.actions:
933 actions = []
934 for action in self.actions:
935 actionrule = None
936 if action.get('name') == 'ModifyRequestHeader':
937 actionrule = DeliveryRuleRequestHeaderAction(
938 parameters=HeaderActionParameters(
939 type_name='DeliveryRuleHeaderActionParameters',
940 header_action=action.get('header_action'),
941 header_name=action.get('header_name'),
942 value=action.get('value')
943 )
944 )
945 elif action.get('name') == 'ModifyResponseHeader':
946 actionrule = DeliveryRuleResponseHeaderAction(
947 parameters=HeaderActionParameters(
948 type_name='DeliveryRuleHeaderActionParameters',
949 header_action=action.get('header_action'),
950 header_name=action.get('header_name'),
951 value=action.get('value')
952 )
953 )
954 elif action.get('name') == 'RouteConfigurationOverride':
955 origin_group_override = None
956 action['origin_group_id'] = None
957 if action.get('origin_group'):
958 origin_group_id = self.get_origin_group_id(action.get('origin_group'))
959 origin_group_ref = ResourceReference(id=origin_group_id)
960 action['origin_group_id'] = origin_group_id
961 origin_group_override = OriginGroupOverride(
962 origin_group=origin_group_ref,
963 forwarding_protocol=ForwardingProtocol(
964 action.get('forwarding_protocol')
965 )
966 )
967 cache_configuration = AzureCoreNull
968 if action.get('query_string_caching_behavior') or action.get('query_parameters') or \
969 action.get('is_compression_enabled') or action.get('cache_behavior') or action.get('cache_duration'):
970 cache_configuration = CacheConfiguration(
971 query_string_caching_behavior=action.get('query_string_caching_behavior'),
972 query_parameters=action.get('query_parameters'),
973 is_compression_enabled=action.get('is_compression_enabled'),
974 cache_behavior=action.get('cache_behavior'),
975 cache_duration=action.get('cache_duration')
976 )
977 actionrule = DeliveryRuleRouteConfigurationOverrideAction(
978 parameters=RouteConfigurationOverrideActionParameters(
979 type_name="DeliveryRuleRouteConfigurationOverrideActionParameters",
980 origin_group_override=origin_group_override,
981 cache_configuration=cache_configuration
982 )
983 )
984 elif action.get('name') == 'UrlRedirect':
985 actionrule = UrlRedirectAction(
986 parameters=UrlRedirectActionParameters(
987 type_name='DeliveryRuleUrlRedirectActionParameters',
988 redirect_type=action.get('redirect_type'),
989 destination_protocol=action.get('destination_protocol'),
990 custom_path=action.get('custom_path'),
991 custom_hostname=action.get('custom_hostname'),
992 custom_query_string=action.get('custom_query_string'),
993 custom_fragment=action.get('custom_fragment')
994 )
995 )
996 elif action.get('name') == 'UrlRewrite':
997 actionrule = UrlRewriteAction(
998 parameters=UrlRewriteActionParameters(
999 type_name='DeliveryRuleUrlRewriteActionParameters',
1000 source_pattern=action.get('source_pattern'),
1001 destination=action.get('destination'),
1002 preserve_unmatched_path=action.get('preserve_unmatched_path')
1003 )
1004 )
1005
1006 if actionrule:
1007 actions.append(actionrule)
1008
1009 if update:
1010 self.parameters = RuleUpdateParameters(
1011 order=self.order,
1012 conditions=conditions,
1013 actions=actions,
1014 match_processing_behavior=self.match_processing_behavior
1015 )
1016 else:
1017 self.parameters = Rule(
1018 order=self.order,
1019 conditions=conditions,
1020 actions=actions,
1021 match_processing_behavior=self.match_processing_behavior
1022 )
1023 return
1024
1025 def delete_rules(self):
1026 '''
1027 Deletes the specified Azure Rules in the specified subscription and resource group.
1028
1029 :return: True
1030 '''
1031 self.log("Deleting the Rules {0}".format(self.name))
1032 try:
1033 poller = self.cdn_client.rules.begin_delete(
1034 resource_group_name=self.resource_group,
1035 profile_name=self.profile_name,
1036 rule_set_name=self.rule_set_name,
1037 rule_name=self.name)
1038 self.get_poller_result(poller)
1039 return True
1040 except Exception as exc:
1041 self.log('Error attempting to delete the Rules.')
1042 self.fail("Error deleting the Rules: {0}".format(str(exc)))
1043 return False
1044
1045 def get_rule(self):
1046 '''
1047 Gets the properties of the specified Rules.
1048
1049 :return: deserialized Rules state dictionary
1050 '''
1051 self.log(
1052 "Checking if the Rules {0} is present".format(self.name))
1053 try:
1054 response = self.cdn_client.rules.get(
1055 resource_group_name=self.resource_group,
1056 profile_name=self.profile_name,
1057 rule_set_name=self.rule_set_name,
1058 rule_name=self.name
1059 )
1060 self.log("Response : {0}".format(response))
1061 self.log("Rules : {0} found".format(response.name))
1062 return rules_to_dict(response)
1063 except Exception as err:
1064 self.log('Did not find the Rule: {0}'.format(str(err)))
1065 return False
1066
1067 def get_origin_group_id(self, origin_group):
1068 '''
1069 Gets the ID of the specified Origin Group.
1070
1071 :return: ID for the Origin Group.
1072 '''
1073 self.log(
1074 "Obtaining ID for Origin Group {0}".format(origin_group))
1075 try:
1076 response = self.cdn_client.afd_origin_groups.get(
1077 resource_group_name=self.resource_group,
1078 profile_name=self.profile_name,
1079 origin_group_name=origin_group)
1080 self.log("Response : {0}".format(response))
1081 self.log("Origin Group ID found : {0} found".format(response.id))
1082 return response.id
1083 except Exception as err:
1084 self.fail('Did not find the Origin Group.' + str(err))
1085 return False
1086
1087
1088 def parse_action_condition(items):
1089 ''' Convert Actions and Conditions objects to list '''
1090
1091 parsed = []
1092 for item in items:
1093 new_item = {}
1094 vitem = vars(item)
1095 for field in vitem:
1096 if field == 'parameters':
1097 subvitem = vars(vitem.get('parameters'))
1098 for subfield in subvitem:
1099 if subfield != 'additional_properties':
1100 new_item[subfield] = subvitem[subfield]
1101 elif field != 'additional_properties':
1102 new_item[field] = vitem[field]
1103 parsed.append(new_item)
1104 return parsed
1105
1106
1107 def rules_to_dict(rules):
1108 ''' Convert Rules object to dictionary '''
1109
1110 return dict(
1111 actions=parse_action_condition(rules.actions),
1112 conditions=parse_action_condition(rules.conditions),
1113 deployment_status=rules.deployment_status,
1114 id=rules.id,
1115 match_processing_behavior=rules.match_processing_behavior,
1116 name=rules.name,
1117 order=rules.order,
1118 provisioning_state=rules.provisioning_state,
1119 rule_set_name=rules.rule_set_name,
1120 type=rules.type
1121 )
1122
1123
1124 def main():
1125 """Main execution"""
1126 AzureRMRules()
1127
1128
1129 if __name__ == '__main__':
1130 main()