Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: Ansible Project
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 DOCUMENTATION = r"""
8 ---
9 module: wafv2_rule_group
10 version_added: 1.5.0
11 author:
12 - "Markus Bergholz (@markuman)"
13 short_description: wafv2_web_acl
14 description:
15 - Create, modify and delete wafv2 rule groups.
16 options:
17 state:
18 description:
19 - Whether the rule is present or absent.
20 choices: ["present", "absent"]
21 required: true
22 type: str
23 name:
24 description:
25 - The name of the rule group.
26 required: true
27 type: str
28 rules:
29 description:
30 - The Rule statements used to identify the web requests that you want to allow, block, or count.
31 type: list
32 elements: dict
33 scope:
34 description:
35 - Scope of wafv2 rule group.
36 required: true
37 choices: ["CLOUDFRONT","REGIONAL"]
38 type: str
39 description:
40 description:
41 - Description of wafv2 rule group.
42 type: str
43 sampled_requests:
44 description:
45 - Sampled requests, true or false.
46 type: bool
47 default: false
48 cloudwatch_metrics:
49 description:
50 - Enable cloudwatch metric for wafv2 rule group
51 type: bool
52 default: true
53 metric_name:
54 description:
55 - Name of cloudwatch metrics.
56 - If not given and cloudwatch_metrics is enabled, the name of the rule group itself will be taken.
57 type: str
58 capacity:
59 description:
60 - capacity of wafv2 rule group.
61 type: int
62 purge_rules:
63 description:
64 - When set to C(no), keep the existing load balancer rules in place. Will modify and add, but will not delete.
65 default: true
66 type: bool
67
68 extends_documentation_fragment:
69 - amazon.aws.common.modules
70 - amazon.aws.region.modules
71 - amazon.aws.tags
72 - amazon.aws.boto3
73 """
74
75 EXAMPLES = r"""
76 - name: change description
77 community.aws.wafv2_rule_group:
78 name: test02
79 state: present
80 description: hallo eins zwei
81 scope: REGIONAL
82 capacity: 500
83 rules:
84 - name: eins
85 priority: 1
86 action:
87 allow: {}
88 visibility_config:
89 sampled_requests_enabled: true
90 cloud_watch_metrics_enabled: true
91 metric_name: fsd
92 statement:
93 ip_set_reference_statement:
94 arn: "{{ IPSET.arn }}"
95 cloudwatch_metrics: true
96 tags:
97 A: B
98 C: D
99 register: out
100
101 - name: add rule
102 community.aws.wafv2_rule_group:
103 name: test02
104 state: present
105 description: hallo eins zwei
106 scope: REGIONAL
107 capacity: 500
108 rules:
109 - name: eins
110 priority: 1
111 action:
112 allow: {}
113 visibility_config:
114 sampled_requests_enabled: true
115 cloud_watch_metrics_enabled: true
116 metric_name: fsd
117 statement:
118 ip_set_reference_statement:
119 arn: "{{ IPSET.arn }}"
120 - name: zwei
121 priority: 2
122 action:
123 block: {}
124 visibility_config:
125 sampled_requests_enabled: true
126 cloud_watch_metrics_enabled: true
127 metric_name: ddos
128 statement:
129 or_statement:
130 statements:
131 - byte_match_statement:
132 search_string: ansible.com
133 positional_constraint: CONTAINS
134 field_to_match:
135 single_header:
136 name: host
137 text_transformations:
138 - type: LOWERCASE
139 priority: 0
140 - xss_match_statement:
141 field_to_match:
142 body: {}
143 text_transformations:
144 - type: NONE
145 priority: 0
146 cloudwatch_metrics: true
147 tags:
148 A: B
149 C: D
150 register: out
151 """
152
153 RETURN = r"""
154 arn:
155 description: Rule group arn
156 sample: arn:aws:wafv2:eu-central-1:11111111:regional/rulegroup/test02/6e90c01a-e4eb-43e5-b6aa-b1604cedf7d7
157 type: str
158 returned: Always, as long as the web acl exists
159 description:
160 description: Description of the rule group
161 sample: Some rule group description
162 returned: Always, as long as the web acl exists
163 type: str
164 capacity:
165 description: Current capacity of the rule group
166 sample: 500
167 returned: Always, as long as the rule group exists
168 type: int
169 name:
170 description: Rule group name
171 sample: test02
172 returned: Always, as long as the rule group exists
173 type: str
174 rules:
175 description: Current rules of the rule group
176 returned: Always, as long as the rule group exists
177 type: list
178 sample:
179 - action:
180 allow: {}
181 name: eins
182 priority: 1
183 statement:
184 ip_set_reference_statement:
185 arn: arn:aws:wafv2:eu-central-1:11111111:regional/ipset/test02/b6978915-c67b-4d1c-8832-2b1bb452143a
186 visibility_config:
187 cloud_watch_metrics_enabled: True
188 metric_name: fsd
189 sampled_requests_enabled: True
190 visibility_config:
191 description: Visibility config of the rule group
192 returned: Always, as long as the rule group exists
193 type: dict
194 sample:
195 cloud_watch_metrics_enabled: True
196 metric_name: blub
197 sampled_requests_enabled: False
198 """
199
200 try:
201 from botocore.exceptions import BotoCoreError
202 from botocore.exceptions import ClientError
203 except ImportError:
204 pass # caught by AnsibleAWSModule
205
206 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
207 from ansible.module_utils.common.dict_transformations import snake_dict_to_camel_dict
208
209 from ansible_collections.amazon.aws.plugins.module_utils.tagging import ansible_dict_to_boto3_tag_list
210
211 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
212 from ansible_collections.community.aws.plugins.module_utils.wafv2 import compare_priority_rules
213 from ansible_collections.community.aws.plugins.module_utils.wafv2 import describe_wafv2_tags
214 from ansible_collections.community.aws.plugins.module_utils.wafv2 import ensure_wafv2_tags
215 from ansible_collections.community.aws.plugins.module_utils.wafv2 import wafv2_list_rule_groups
216 from ansible_collections.community.aws.plugins.module_utils.wafv2 import wafv2_snake_dict_to_camel_dict
217
218
219 class RuleGroup:
220 def __init__(self, wafv2, name, scope, fail_json_aws):
221 self.wafv2 = wafv2
222 self.id = None
223 self.name = name
224 self.scope = scope
225 self.fail_json_aws = fail_json_aws
226 self.existing_group = self.get_group()
227
228 def update(self, description, rules, sampled_requests, cloudwatch_metrics, metric_name):
229 req_obj = {
230 "Name": self.name,
231 "Scope": self.scope,
232 "Id": self.id,
233 "Rules": rules,
234 "LockToken": self.locktoken,
235 "VisibilityConfig": {
236 "SampledRequestsEnabled": sampled_requests,
237 "CloudWatchMetricsEnabled": cloudwatch_metrics,
238 "MetricName": metric_name,
239 },
240 }
241
242 if description:
243 req_obj["Description"] = description
244
245 try:
246 self.wafv2.update_rule_group(**req_obj)
247 except (BotoCoreError, ClientError) as e:
248 self.fail_json_aws(e, msg="Failed to update wafv2 rule group.")
249 return self.refresh_group()
250
251 def get_group(self):
252 if self.id is None:
253 response = self.list()
254
255 for item in response.get("RuleGroups"):
256 if item.get("Name") == self.name:
257 self.id = item.get("Id")
258 self.locktoken = item.get("LockToken")
259 self.arn = item.get("ARN")
260
261 return self.refresh_group()
262
263 def refresh_group(self):
264 existing_group = None
265 if self.id:
266 try:
267 response = self.wafv2.get_rule_group(Name=self.name, Scope=self.scope, Id=self.id)
268 existing_group = response.get("RuleGroup")
269 self.locktoken = response.get("LockToken")
270 except (BotoCoreError, ClientError) as e:
271 self.fail_json_aws(e, msg="Failed to get wafv2 rule group.")
272
273 tags = describe_wafv2_tags(self.wafv2, self.arn, self.fail_json_aws)
274 existing_group["tags"] = tags or {}
275
276 return existing_group
277
278 def list(self):
279 return wafv2_list_rule_groups(self.wafv2, self.scope, self.fail_json_aws)
280
281 def get(self):
282 if self.existing_group:
283 return self.existing_group
284 return None
285
286 def remove(self):
287 try:
288 response = self.wafv2.delete_rule_group(
289 Name=self.name, Scope=self.scope, Id=self.id, LockToken=self.locktoken
290 )
291 except (BotoCoreError, ClientError) as e:
292 self.fail_json_aws(e, msg="Failed to delete wafv2 rule group.")
293 return response
294
295 def create(self, capacity, description, rules, sampled_requests, cloudwatch_metrics, metric_name, tags):
296 req_obj = {
297 "Name": self.name,
298 "Scope": self.scope,
299 "Capacity": capacity,
300 "Rules": rules,
301 "VisibilityConfig": {
302 "SampledRequestsEnabled": sampled_requests,
303 "CloudWatchMetricsEnabled": cloudwatch_metrics,
304 "MetricName": metric_name,
305 },
306 }
307
308 if description:
309 req_obj["Description"] = description
310
311 if tags:
312 req_obj["Tags"] = ansible_dict_to_boto3_tag_list(tags)
313
314 try:
315 self.wafv2.create_rule_group(**req_obj)
316 except (BotoCoreError, ClientError) as e:
317 self.fail_json_aws(e, msg="Failed to create wafv2 rule group.")
318
319 self.existing_group = self.get_group()
320
321 return self.existing_group
322
323
324 def main():
325 arg_spec = dict(
326 state=dict(type="str", required=True, choices=["present", "absent"]),
327 name=dict(type="str", required=True),
328 scope=dict(type="str", required=True, choices=["CLOUDFRONT", "REGIONAL"]),
329 capacity=dict(type="int"),
330 description=dict(type="str"),
331 rules=dict(type="list", elements="dict"),
332 sampled_requests=dict(type="bool", default=False),
333 cloudwatch_metrics=dict(type="bool", default=True),
334 metric_name=dict(type="str"),
335 tags=dict(type="dict", aliases=["resource_tags"]),
336 purge_tags=dict(default=True, type="bool"),
337 purge_rules=dict(default=True, type="bool"),
338 )
339
340 module = AnsibleAWSModule(
341 argument_spec=arg_spec,
342 supports_check_mode=True,
343 required_if=[["state", "present", ["capacity", "rules"]]],
344 )
345
346 state = module.params.get("state")
347 name = module.params.get("name")
348 scope = module.params.get("scope")
349 capacity = module.params.get("capacity")
350 description = module.params.get("description")
351 rules = module.params.get("rules")
352 sampled_requests = module.params.get("sampled_requests")
353 cloudwatch_metrics = module.params.get("cloudwatch_metrics")
354 metric_name = module.params.get("metric_name")
355 tags = module.params.get("tags")
356 purge_tags = module.params.get("purge_tags")
357 purge_rules = module.params.get("purge_rules")
358 check_mode = module.check_mode
359
360 if rules:
361 rules = []
362 for rule in module.params.get("rules"):
363 rules.append(wafv2_snake_dict_to_camel_dict(snake_dict_to_camel_dict(rule, capitalize_first=True)))
364
365 if not metric_name:
366 metric_name = name
367
368 wafv2 = module.client("wafv2")
369 rule_group = RuleGroup(wafv2, name, scope, module.fail_json_aws)
370
371 change = False
372 retval = {}
373
374 if state == "present":
375 if rule_group.get():
376 tagging_change = ensure_wafv2_tags(
377 wafv2, rule_group.arn, tags, purge_tags, module.fail_json_aws, module.check_mode
378 )
379 rules_change, rules = compare_priority_rules(rule_group.get().get("Rules"), rules, purge_rules, state)
380 description_change = bool(description) and (rule_group.get().get("Description") != description)
381 change = tagging_change or rules_change or description_change
382 retval = rule_group.get()
383 if module.check_mode:
384 # In check mode nothing changes...
385 pass
386 elif rules_change or description_change:
387 retval = rule_group.update(description, rules, sampled_requests, cloudwatch_metrics, metric_name)
388 elif tagging_change:
389 retval = rule_group.refresh_group()
390
391 else:
392 change = True
393 if not check_mode:
394 retval = rule_group.create(
395 capacity, description, rules, sampled_requests, cloudwatch_metrics, metric_name, tags
396 )
397
398 elif state == "absent":
399 if rule_group.get():
400 if rules:
401 if len(rules) > 0:
402 change, rules = compare_priority_rules(rule_group.get().get("Rules"), rules, purge_rules, state)
403 if change and not check_mode:
404 retval = rule_group.update(
405 description, rules, sampled_requests, cloudwatch_metrics, metric_name
406 )
407 else:
408 change = True
409 if not check_mode:
410 retval = rule_group.remove()
411
412 module.exit_json(changed=change, **camel_dict_to_snake_dict(retval, ignore_list=["tags"]))
413
414
415 if __name__ == "__main__":
416 main()