Debian Codegraph @

ansible_collections/community/aws/plugins/modules/waf_condition.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright (c) 2017 Will Thames
5 # Copyright (c) 2015 Mike Mochan
6 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
7
8 DOCUMENTATION = r"""
9 module: waf_condition
10 short_description: Create and delete WAF Conditions
11 version_added: 1.0.0
12 description:
13 - Read the AWS documentation for WAF
14 U(https://aws.amazon.com/documentation/waf/)
15 - Prior to release 5.0.0 this module was called C(community.aws.aws_waf_condition).
16 The usage did not change.
17
18 author:
19 - Will Thames (@willthames)
20 - Mike Mochan (@mmochan)
21
22 deprecated:
23 removed_in: 12.0.0
24 why: Amazon has retired the "WAF Classic" service.
25 alternative: Please use the "AWS WAF (WAFv2)" service and modules instead.
26
27 options:
28 name:
29 description: Name of the Web Application Firewall condition to manage.
30 required: true
31 type: str
32 type:
33 description: The type of matching to perform.
34 choices:
35 - byte
36 - geo
37 - ip
38 - regex
39 - size
40 - sql
41 - xss
42 type: str
43 required: true
44 filters:
45 description:
46 - A list of the filters against which to match.
47 - For I(type=byte), valid keys are I(field_to_match), I(position), I(header), I(transformation) and I(target_string).
48 - For I(type=geo), the only valid key is I(country).
49 - For I(type=ip), the only valid key is I(ip_address).
50 - For I(type=regex), valid keys are I(field_to_match), I(transformation) and I(regex_pattern).
51 - For I(type=size), valid keys are I(field_to_match), I(transformation), I(comparison) and I(size).
52 - For I(type=sql), valid keys are I(field_to_match) and I(transformation).
53 - For I(type=xss), valid keys are I(field_to_match) and I(transformation).
54 - Required when I(state=present).
55 type: list
56 elements: dict
57 suboptions:
58 field_to_match:
59 description:
60 - The field upon which to perform the match.
61 - Valid when I(type=byte), I(type=regex), I(type=sql) or I(type=xss).
62 type: str
63 choices: ['uri', 'query_string', 'header', 'method', 'body']
64 position:
65 description:
66 - Where in the field the match needs to occur.
67 - Only valid when I(type=byte).
68 type: str
69 choices: ['exactly', 'starts_with', 'ends_with', 'contains', 'contains_word']
70 header:
71 description:
72 - Which specific header should be matched.
73 - Required when I(field_to_match=header).
74 - Valid when I(type=byte).
75 type: str
76 transformation:
77 description:
78 - A transform to apply on the field prior to performing the match.
79 - Valid when I(type=byte), I(type=regex), I(type=sql) or I(type=xss).
80 type: str
81 choices: ['none', 'compress_white_space', 'html_entity_decode', 'lowercase', 'cmd_line', 'url_decode']
82 country:
83 description:
84 - Value of geo constraint (typically a two letter country code).
85 - The only valid key when I(type=geo).
86 type: str
87 ip_address:
88 description:
89 - An IP Address or CIDR to match.
90 - The only valid key when I(type=ip).
91 type: str
92 regex_pattern:
93 description:
94 - A dict describing the regular expressions used to perform the match.
95 - Only valid when I(type=regex).
96 type: dict
97 suboptions:
98 name:
99 description: A name to describe the set of patterns.
100 type: str
101 regex_strings:
102 description: A list of regular expressions to match.
103 type: list
104 elements: str
105 comparison:
106 description:
107 - What type of comparison to perform.
108 - Only valid key when I(type=size).
109 type: str
110 choices: ['EQ', 'NE', 'LE', 'LT', 'GE', 'GT']
111 size:
112 description:
113 - The size of the field (in bytes).
114 - Only valid key when I(type=size).
115 type: int
116 target_string:
117 description:
118 - The string to search for.
119 - May be up to 50 bytes.
120 - Valid when I(type=byte).
121 type: str
122 purge_filters:
123 description:
124 - Whether to remove existing filters from a condition if not passed in I(filters).
125 default: false
126 type: bool
127 waf_regional:
128 description: Whether to use C(waf-regional) module.
129 default: false
130 required: false
131 type: bool
132 state:
133 description: Whether the condition should be C(present) or C(absent).
134 choices:
135 - present
136 - absent
137 default: present
138 type: str
139
140 extends_documentation_fragment:
141 - amazon.aws.common.modules
142 - amazon.aws.region.modules
143 - amazon.aws.boto3
144 """
145
146 EXAMPLES = r"""
147 - name: create WAF byte condition
148 community.aws.waf_condition:
149 name: my_byte_condition
150 filters:
151 - field_to_match: header
152 position: STARTS_WITH
153 target_string: Hello
154 header: Content-type
155 type: byte
156
157 - name: create WAF geo condition
158 community.aws.waf_condition:
159 name: my_geo_condition
160 filters:
161 - country: US
162 - country: AU
163 - country: AT
164 type: geo
165
166 - name: create IP address condition
167 community.aws.waf_condition:
168 name: "{{ resource_prefix }}_ip_condition"
169 filters:
170 - ip_address: "10.0.0.0/8"
171 - ip_address: "192.168.0.0/24"
172 type: ip
173
174 - name: create WAF regex condition
175 community.aws.waf_condition:
176 name: my_regex_condition
177 filters:
178 - field_to_match: query_string
179 regex_pattern:
180 name: greetings
181 regex_strings:
182 - '[hH]ello'
183 - '^Hi there'
184 - '.*Good Day to You'
185 type: regex
186
187 - name: create WAF size condition
188 community.aws.waf_condition:
189 name: my_size_condition
190 filters:
191 - field_to_match: query_string
192 size: 300
193 comparison: GT
194 type: size
195
196 - name: create WAF sql injection condition
197 community.aws.waf_condition:
198 name: my_sql_condition
199 filters:
200 - field_to_match: query_string
201 transformation: url_decode
202 type: sql
203
204 - name: create WAF xss condition
205 community.aws.waf_condition:
206 name: my_xss_condition
207 filters:
208 - field_to_match: query_string
209 transformation: url_decode
210 type: xss
211 """
212
213 RETURN = r"""
214 condition:
215 description: Condition returned by operation.
216 returned: always
217 type: complex
218 contains:
219 condition_id:
220 description: Type-agnostic ID for the condition.
221 returned: when state is present
222 type: str
223 sample: dd74b1ff-8c06-4a4f-897a-6b23605de413
224 byte_match_set_id:
225 description: ID for byte match set.
226 returned: always
227 type: str
228 sample: c4882c96-837b-44a2-a762-4ea87dbf812b
229 byte_match_tuples:
230 description: List of byte match tuples.
231 returned: always
232 type: complex
233 contains:
234 field_to_match:
235 description: Field to match.
236 returned: always
237 type: complex
238 contains:
239 data:
240 description: Which specific header (if type is header).
241 type: str
242 sample: content-type
243 type:
244 description: Type of field
245 type: str
246 sample: HEADER
247 positional_constraint:
248 description: Position in the field to match.
249 type: str
250 sample: STARTS_WITH
251 target_string:
252 description: String to look for.
253 type: str
254 sample: Hello
255 text_transformation:
256 description: Transformation to apply to the field before matching.
257 type: str
258 sample: NONE
259 geo_match_constraints:
260 description: List of geographical constraints.
261 returned: when type is geo and state is present
262 type: complex
263 contains:
264 type:
265 description: Type of geo constraint.
266 type: str
267 sample: Country
268 value:
269 description: Value of geo constraint (typically a country code).
270 type: str
271 sample: AT
272 geo_match_set_id:
273 description: ID of the geo match set.
274 returned: when type is geo and state is present
275 type: str
276 sample: dd74b1ff-8c06-4a4f-897a-6b23605de413
277 ip_set_descriptors:
278 description: list of IP address filters
279 returned: when type is ip and state is present
280 type: complex
281 contains:
282 type:
283 description: Type of IP address (IPV4 or IPV6).
284 returned: always
285 type: str
286 sample: IPV4
287 value:
288 description: IP address.
289 returned: always
290 type: str
291 sample: 10.0.0.0/8
292 ip_set_id:
293 description: ID of condition.
294 returned: when type is ip and state is present
295 type: str
296 sample: 78ad334a-3535-4036-85e6-8e11e745217b
297 name:
298 description: Name of condition.
299 returned: when state is present
300 type: str
301 sample: my_waf_condition
302 regex_match_set_id:
303 description: ID of the regex match set.
304 returned: when type is regex and state is present
305 type: str
306 sample: 5ea3f6a8-3cd3-488b-b637-17b79ce7089c
307 regex_match_tuples:
308 description: List of regex matches.
309 returned: when type is regex and state is present
310 type: complex
311 contains:
312 field_to_match:
313 description: Field on which the regex match is applied.
314 type: complex
315 contains:
316 type:
317 description: The field name.
318 returned: when type is regex and state is present
319 type: str
320 sample: QUERY_STRING
321 regex_pattern_set_id:
322 description: ID of the regex pattern.
323 type: str
324 sample: 6fdf7f2d-9091-445c-aef2-98f3c051ac9e
325 text_transformation:
326 description: transformation applied to the text before matching
327 type: str
328 sample: NONE
329 size_constraint_set_id:
330 description: ID of the size constraint set.
331 returned: when type is size and state is present
332 type: str
333 sample: de84b4b3-578b-447e-a9a0-0db35c995656
334 size_constraints:
335 description: List of size constraints to apply.
336 returned: when type is size and state is present
337 type: complex
338 contains:
339 comparison_operator:
340 description: Comparison operator to apply.
341 type: str
342 sample: GT
343 field_to_match:
344 description: Field on which the size constraint is applied.
345 type: complex
346 contains:
347 type:
348 description: Field name.
349 type: str
350 sample: QUERY_STRING
351 size:
352 description: Size to compare against the field.
353 type: int
354 sample: 300
355 text_transformation:
356 description: Transformation applied to the text before matching.
357 type: str
358 sample: NONE
359 sql_injection_match_set_id:
360 description: ID of the SQL injection match set.
361 returned: when type is sql and state is present
362 type: str
363 sample: de84b4b3-578b-447e-a9a0-0db35c995656
364 sql_injection_match_tuples:
365 description: List of SQL injection match sets.
366 returned: when type is sql and state is present
367 type: complex
368 contains:
369 field_to_match:
370 description: Field on which the SQL injection match is applied.
371 type: complex
372 contains:
373 type:
374 description: Field name.
375 type: str
376 sample: QUERY_STRING
377 text_transformation:
378 description: Transformation applied to the text before matching.
379 type: str
380 sample: URL_DECODE
381 xss_match_set_id:
382 description: ID of the XSS match set.
383 returned: when type is xss and state is present
384 type: str
385 sample: de84b4b3-578b-447e-a9a0-0db35c995656
386 xss_match_tuples:
387 description: List of XSS match sets.
388 returned: when type is xss and state is present
389 type: complex
390 contains:
391 field_to_match:
392 description: Field on which the XSS match is applied.
393 type: complex
394 contains:
395 type:
396 description: Field name
397 type: str
398 sample: QUERY_STRING
399 text_transformation:
400 description: transformation applied to the text before matching.
401 type: str
402 sample: URL_DECODE
403 """
404
405 try:
406 import botocore
407 except ImportError:
408 pass # handled by AnsibleAWSModule
409
410 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
411
412 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
413 from ansible_collections.amazon.aws.plugins.module_utils.policy import compare_policies
414 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
415 from ansible_collections.amazon.aws.plugins.module_utils.waf import MATCH_LOOKUP
416 from ansible_collections.amazon.aws.plugins.module_utils.waf import get_rule_with_backoff
417 from ansible_collections.amazon.aws.plugins.module_utils.waf import list_regional_rules_with_backoff
418 from ansible_collections.amazon.aws.plugins.module_utils.waf import list_rules_with_backoff
419 from ansible_collections.amazon.aws.plugins.module_utils.waf import run_func_with_change_token_backoff
420
421 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
422
423
424 class Condition(object):
425 def __init__(self, client, module):
426 self.client = client
427 self.module = module
428 self.type = module.params["type"]
429 self.method_suffix = MATCH_LOOKUP[self.type]["method"]
430 self.conditionset = MATCH_LOOKUP[self.type]["conditionset"]
431 self.conditionsets = MATCH_LOOKUP[self.type]["conditionset"] + "s"
432 self.conditionsetid = MATCH_LOOKUP[self.type]["conditionset"] + "Id"
433 self.conditiontuple = MATCH_LOOKUP[self.type]["conditiontuple"]
434 self.conditiontuples = MATCH_LOOKUP[self.type]["conditiontuple"] + "s"
435 self.conditiontype = MATCH_LOOKUP[self.type]["type"]
436
437 def format_for_update(self, condition_set_id):
438 # Prep kwargs
439 kwargs = dict()
440 kwargs["Updates"] = list()
441
442 for filtr in self.module.params.get("filters"):
443 # Only for ip_set
444 if self.type == "ip":
445 # there might be a better way of detecting an IPv6 address
446 if ":" in filtr.get("ip_address"):
447 ip_type = "IPV6"
448 else:
449 ip_type = "IPV4"
450 condition_insert = {"Type": ip_type, "Value": filtr.get("ip_address")}
451
452 # Specific for geo_match_set
453 if self.type == "geo":
454 condition_insert = dict(Type="Country", Value=filtr.get("country"))
455
456 # Common For everything but ip_set and geo_match_set
457 if self.type not in ("ip", "geo"):
458 condition_insert = dict(
459 FieldToMatch=dict(Type=filtr.get("field_to_match").upper()),
460 TextTransformation=filtr.get("transformation", "none").upper(),
461 )
462
463 if filtr.get("field_to_match").upper() == "HEADER":
464 if filtr.get("header"):
465 condition_insert["FieldToMatch"]["Data"] = filtr.get("header").lower()
466 else:
467 self.module.fail_json(msg=str("DATA required when HEADER requested"))
468
469 # Specific for byte_match_set
470 if self.type == "byte":
471 condition_insert["TargetString"] = filtr.get("target_string")
472 condition_insert["PositionalConstraint"] = filtr.get("position")
473
474 # Specific for size_constraint_set
475 if self.type == "size":
476 condition_insert["ComparisonOperator"] = filtr.get("comparison")
477 condition_insert["Size"] = filtr.get("size")
478
479 # Specific for regex_match_set
480 if self.type == "regex":
481 condition_insert["RegexPatternSetId"] = self.ensure_regex_pattern_present(filtr.get("regex_pattern"))[
482 "RegexPatternSetId"
483 ]
484
485 kwargs["Updates"].append({"Action": "INSERT", self.conditiontuple: condition_insert})
486
487 kwargs[self.conditionsetid] = condition_set_id
488 return kwargs
489
490 def format_for_deletion(self, condition):
491 return {
492 "Updates": [
493 {"Action": "DELETE", self.conditiontuple: current_condition_tuple}
494 for current_condition_tuple in condition[self.conditiontuples]
495 ],
496 self.conditionsetid: condition[self.conditionsetid],
497 }
498
499 @AWSRetry.exponential_backoff()
500 def list_regex_patterns_with_backoff(self, **params):
501 return self.client.list_regex_pattern_sets(**params)
502
503 @AWSRetry.exponential_backoff()
504 def get_regex_pattern_set_with_backoff(self, regex_pattern_set_id):
505 return self.client.get_regex_pattern_set(RegexPatternSetId=regex_pattern_set_id)
506
507 def list_regex_patterns(self):
508 # at time of writing(2017-11-20) no regex pattern paginator exists
509 regex_patterns = []
510 params = {}
511 while True:
512 try:
513 response = self.list_regex_patterns_with_backoff(**params)
514 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
515 self.module.fail_json_aws(e, msg="Could not list regex patterns")
516 regex_patterns.extend(response["RegexPatternSets"])
517 if "NextMarker" in response:
518 params["NextMarker"] = response["NextMarker"]
519 else:
520 break
521 return regex_patterns
522
523 def get_regex_pattern_by_name(self, name):
524 existing_regex_patterns = self.list_regex_patterns()
525 regex_lookup = dict((item["Name"], item["RegexPatternSetId"]) for item in existing_regex_patterns)
526 if name in regex_lookup:
527 return self.get_regex_pattern_set_with_backoff(regex_lookup[name])["RegexPatternSet"]
528 else:
529 return None
530
531 def ensure_regex_pattern_present(self, regex_pattern):
532 name = regex_pattern["name"]
533
534 pattern_set = self.get_regex_pattern_by_name(name)
535 if not pattern_set:
536 pattern_set = run_func_with_change_token_backoff(
537 self.client, self.module, {"Name": name}, self.client.create_regex_pattern_set
538 )["RegexPatternSet"]
539 missing = set(regex_pattern["regex_strings"]) - set(pattern_set["RegexPatternStrings"])
540 extra = set(pattern_set["RegexPatternStrings"]) - set(regex_pattern["regex_strings"])
541 if not missing and not extra:
542 return pattern_set
543 updates = [{"Action": "INSERT", "RegexPatternString": pattern} for pattern in missing]
544 updates.extend([{"Action": "DELETE", "RegexPatternString": pattern} for pattern in extra])
545 run_func_with_change_token_backoff(
546 self.client,
547 self.module,
548 {"RegexPatternSetId": pattern_set["RegexPatternSetId"], "Updates": updates},
549 self.client.update_regex_pattern_set,
550 wait=True,
551 )
552 return self.get_regex_pattern_set_with_backoff(pattern_set["RegexPatternSetId"])["RegexPatternSet"]
553
554 def delete_unused_regex_pattern(self, regex_pattern_set_id):
555 try:
556 regex_pattern_set = self.client.get_regex_pattern_set(RegexPatternSetId=regex_pattern_set_id)[
557 "RegexPatternSet"
558 ]
559 updates = list()
560 for regex_pattern_string in regex_pattern_set["RegexPatternStrings"]:
561 updates.append({"Action": "DELETE", "RegexPatternString": regex_pattern_string})
562 run_func_with_change_token_backoff(
563 self.client,
564 self.module,
565 {"RegexPatternSetId": regex_pattern_set_id, "Updates": updates},
566 self.client.update_regex_pattern_set,
567 )
568
569 run_func_with_change_token_backoff(
570 self.client,
571 self.module,
572 {"RegexPatternSetId": regex_pattern_set_id},
573 self.client.delete_regex_pattern_set,
574 wait=True,
575 )
576 except is_boto3_error_code("WAFNonexistentItemException"):
577 return
578 except (
579 botocore.exceptions.ClientError,
580 botocore.exceptions.BotoCoreError,
581 ) as e: # pylint: disable=duplicate-except
582 self.module.fail_json_aws(e, msg="Could not delete regex pattern")
583
584 def get_condition_by_name(self, name):
585 all_conditions = [d for d in self.list_conditions() if d["Name"] == name]
586 if all_conditions:
587 return all_conditions[0][self.conditionsetid]
588
589 @AWSRetry.exponential_backoff()
590 def get_condition_by_id_with_backoff(self, condition_set_id):
591 params = dict()
592 params[self.conditionsetid] = condition_set_id
593 func = getattr(self.client, "get_" + self.method_suffix)
594 return func(**params)[self.conditionset]
595
596 def get_condition_by_id(self, condition_set_id):
597 try:
598 return self.get_condition_by_id_with_backoff(condition_set_id)
599 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
600 self.module.fail_json_aws(e, msg="Could not get condition")
601
602 def list_conditions(self):
603 method = "list_" + self.method_suffix + "s"
604 try:
605 paginator = self.client.get_paginator(method)
606 func = paginator.paginate().build_full_result
607 except botocore.exceptions.OperationNotPageableError:
608 # list_geo_match_sets and list_regex_match_sets do not have a paginator
609 func = getattr(self.client, method)
610 try:
611 return func()[self.conditionsets]
612 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
613 self.module.fail_json_aws(e, msg=f"Could not list {self.type} conditions")
614
615 def tidy_up_regex_patterns(self, regex_match_set):
616 all_regex_match_sets = self.list_conditions()
617 all_match_set_patterns = list()
618 for rms in all_regex_match_sets:
619 all_match_set_patterns.extend(
620 conditiontuple["RegexPatternSetId"]
621 for conditiontuple in self.get_condition_by_id(rms[self.conditionsetid])[self.conditiontuples]
622 )
623 for filtr in regex_match_set[self.conditiontuples]:
624 if filtr["RegexPatternSetId"] not in all_match_set_patterns:
625 self.delete_unused_regex_pattern(filtr["RegexPatternSetId"])
626
627 def find_condition_in_rules(self, condition_set_id):
628 rules_in_use = []
629 try:
630 if self.client.__class__.__name__ == "WAF":
631 all_rules = list_rules_with_backoff(self.client)
632 elif self.client.__class__.__name__ == "WAFRegional":
633 all_rules = list_regional_rules_with_backoff(self.client)
634 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
635 self.module.fail_json_aws(e, msg="Could not list rules")
636 for rule in all_rules:
637 try:
638 rule_details = get_rule_with_backoff(self.client, rule["RuleId"])
639 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
640 self.module.fail_json_aws(e, msg="Could not get rule details")
641 if condition_set_id in [predicate["DataId"] for predicate in rule_details["Predicates"]]:
642 rules_in_use.append(rule_details["Name"])
643 return rules_in_use
644
645 def find_and_delete_condition(self, condition_set_id):
646 current_condition = self.get_condition_by_id(condition_set_id)
647 in_use_rules = self.find_condition_in_rules(condition_set_id)
648 if in_use_rules:
649 rulenames = ", ".join(in_use_rules)
650 self.module.fail_json(msg=f"Condition {current_condition['Name']} is in use by {rulenames}")
651 if current_condition[self.conditiontuples]:
652 # Filters are deleted using update with the DELETE action
653 func = getattr(self.client, "update_" + self.method_suffix)
654 params = self.format_for_deletion(current_condition)
655 try:
656 # We do not need to wait for the conditiontuple delete because we wait later for the delete_* call
657 run_func_with_change_token_backoff(self.client, self.module, params, func)
658 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
659 self.module.fail_json_aws(e, msg="Could not delete filters from condition")
660 func = getattr(self.client, "delete_" + self.method_suffix)
661 params = dict()
662 params[self.conditionsetid] = condition_set_id
663 try:
664 run_func_with_change_token_backoff(self.client, self.module, params, func, wait=True)
665 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
666 self.module.fail_json_aws(e, msg="Could not delete condition")
667 # tidy up regex patterns
668 if self.type == "regex":
669 self.tidy_up_regex_patterns(current_condition)
670 return True, {}
671
672 def find_missing(self, update, current_condition):
673 missing = []
674 for desired in update["Updates"]:
675 found = False
676 desired_condition = desired[self.conditiontuple]
677 current_conditions = current_condition[self.conditiontuples]
678 for condition in current_conditions:
679 if not compare_policies(condition, desired_condition):
680 found = True
681 if not found:
682 missing.append(desired)
683 return missing
684
685 def find_and_update_condition(self, condition_set_id):
686 current_condition = self.get_condition_by_id(condition_set_id)
687 update = self.format_for_update(condition_set_id)
688 missing = self.find_missing(update, current_condition)
689 if self.module.params.get("purge_filters"):
690 extra = [
691 {"Action": "DELETE", self.conditiontuple: current_tuple}
692 for current_tuple in current_condition[self.conditiontuples]
693 if current_tuple not in [desired[self.conditiontuple] for desired in update["Updates"]]
694 ]
695 else:
696 extra = []
697 changed = bool(missing or extra)
698 if changed:
699 update["Updates"] = missing + extra
700 func = getattr(self.client, "update_" + self.method_suffix)
701 try:
702 run_func_with_change_token_backoff(self.client, self.module, update, func, wait=True)
703 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
704 self.module.fail_json_aws(e, msg="Could not update condition")
705 return changed, self.get_condition_by_id(condition_set_id)
706
707 def ensure_condition_present(self):
708 name = self.module.params["name"]
709 condition_set_id = self.get_condition_by_name(name)
710 if condition_set_id:
711 return self.find_and_update_condition(condition_set_id)
712 else:
713 params = dict()
714 params["Name"] = name
715 func = getattr(self.client, "create_" + self.method_suffix)
716 try:
717 condition = run_func_with_change_token_backoff(self.client, self.module, params, func)
718 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
719 self.module.fail_json_aws(e, msg="Could not create condition")
720 return self.find_and_update_condition(condition[self.conditionset][self.conditionsetid])
721
722 def ensure_condition_absent(self):
723 condition_set_id = self.get_condition_by_name(self.module.params["name"])
724 if condition_set_id:
725 return self.find_and_delete_condition(condition_set_id)
726 return False, {}
727
728
729 def main():
730 filters_subspec = dict(
731 country=dict(),
732 field_to_match=dict(choices=["uri", "query_string", "header", "method", "body"]),
733 header=dict(),
734 transformation=dict(
735 choices=["none", "compress_white_space", "html_entity_decode", "lowercase", "cmd_line", "url_decode"]
736 ),
737 position=dict(choices=["exactly", "starts_with", "ends_with", "contains", "contains_word"]),
738 comparison=dict(choices=["EQ", "NE", "LE", "LT", "GE", "GT"]),
739 target_string=dict(), # Bytes
740 size=dict(type="int"),
741 ip_address=dict(),
742 regex_pattern=dict(
743 type="dict",
744 options=dict(
745 name=dict(),
746 regex_strings=dict(type="list", elements="str"),
747 ),
748 ),
749 )
750 argument_spec = dict(
751 name=dict(required=True),
752 type=dict(required=True, choices=["byte", "geo", "ip", "regex", "size", "sql", "xss"]),
753 filters=dict(type="list", elements="dict", options=filters_subspec),
754 purge_filters=dict(type="bool", default=False),
755 waf_regional=dict(type="bool", default=False),
756 state=dict(default="present", choices=["present", "absent"]),
757 )
758 module = AnsibleAWSModule(
759 argument_spec=argument_spec,
760 required_if=[["state", "present", ["filters"]]],
761 )
762 state = module.params.get("state")
763
764 resource = "waf" if not module.params["waf_regional"] else "waf-regional"
765 client = module.client(resource)
766
767 condition = Condition(client, module)
768
769 if state == "present":
770 (changed, results) = condition.ensure_condition_present()
771 # return a condition agnostic ID for use by waf_rule
772 results["ConditionId"] = results[condition.conditionsetid]
773 else:
774 (changed, results) = condition.ensure_condition_absent()
775
776 module.exit_json(changed=changed, condition=camel_dict_to_snake_dict(results))
777
778
779 if __name__ == "__main__":
780 main()