Debian Codegraph @

ansible_collections/community/aws/plugins/modules/wafv2_ip_set.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_ip_set
10 version_added: 1.5.0
11 author:
12 - "Markus Bergholz (@markuman)"
13 short_description: wafv2_ip_set
14 description:
15 - Create, modify and delete IP sets for WAFv2.
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 IP set.
26 required: true
27 type: str
28 description:
29 description:
30 - Description of the IP set.
31 required: false
32 type: str
33 scope:
34 description:
35 - Specifies whether this is for an AWS CloudFront distribution or for a regional application,
36 such as API Gateway or Application LoadBalancer.
37 choices: ["CLOUDFRONT","REGIONAL"]
38 required: true
39 type: str
40 ip_address_version:
41 description:
42 - Specifies whether this is an IPv4 or an IPv6 IP set.
43 - Required when I(state=present).
44 choices: ["IPV4","IPV6"]
45 type: str
46 addresses:
47 description:
48 - Contains an array of strings that specify one or more IP addresses or blocks of IP addresses in
49 Classless Inter-Domain Routing (CIDR) notation.
50 - Required when I(state=present).
51 - When I(state=absent) and I(addresses) is defined, only the given IP addresses will be removed
52 from the IP set. The entire IP set itself will stay present.
53 type: list
54 elements: str
55 purge_addresses:
56 description:
57 - When set to C(no), keep the existing addresses in place. Will modify and add, but will not delete.
58 default: true
59 type: bool
60
61 notes:
62 - Support for I(purge_tags) was added in release 4.0.0.
63
64 extends_documentation_fragment:
65 - amazon.aws.common.modules
66 - amazon.aws.region.modules
67 - amazon.aws.tags
68 - amazon.aws.boto3
69 """
70
71 EXAMPLES = r"""
72 - name: test ip set
73 wafv2_ip_set:
74 name: test02
75 state: present
76 description: hallo eins
77 scope: REGIONAL
78 ip_address_version: IPV4
79 addresses:
80 - 8.8.8.8/32
81 - 8.8.4.4/32
82 tags:
83 A: B
84 C: D
85 """
86
87 RETURN = r"""
88 addresses:
89 description: Current addresses of the ip set
90 sample:
91 - 8.8.8.8/32
92 - 8.8.4.4/32
93 returned: Always, as long as the ip set exists
94 type: list
95 arn:
96 description: IP set arn
97 sample: "arn:aws:wafv2:eu-central-1:11111111:regional/ipset/test02/4b007330-2934-4dc5-af24-82dcb3aeb127"
98 type: str
99 returned: Always, as long as the ip set exists
100 description:
101 description: Description of the ip set
102 sample: Some IP set description
103 returned: Always, as long as the ip set exists
104 type: str
105 ip_address_version:
106 description: IP version of the ip set
107 sample: IPV4
108 type: str
109 returned: Always, as long as the ip set exists
110 name:
111 description: IP set name
112 sample: test02
113 returned: Always, as long as the ip set exists
114 type: str
115 """
116
117 try:
118 from botocore.exceptions import BotoCoreError
119 from botocore.exceptions import ClientError
120 except ImportError:
121 pass # caught by AnsibleAWSModule
122
123 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
124
125 from ansible_collections.amazon.aws.plugins.module_utils.tagging import ansible_dict_to_boto3_tag_list
126
127 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
128 from ansible_collections.community.aws.plugins.module_utils.wafv2 import describe_wafv2_tags
129 from ansible_collections.community.aws.plugins.module_utils.wafv2 import ensure_wafv2_tags
130
131
132 class IpSet:
133 def __init__(self, wafv2, name, scope, fail_json_aws):
134 self.wafv2 = wafv2
135 self.name = name
136 self.scope = scope
137 self.fail_json_aws = fail_json_aws
138 self.existing_set, self.set_id, self.locktoken, self.arn = self.get_set()
139
140 def description(self):
141 return self.existing_set.get("Description")
142
143 def _format_set(self, ip_set):
144 if ip_set is None:
145 return None
146 return camel_dict_to_snake_dict(self.existing_set, ignore_list=["tags"])
147
148 def get(self):
149 return self._format_set(self.existing_set)
150
151 def remove(self):
152 try:
153 self.wafv2.delete_ip_set(Name=self.name, Scope=self.scope, Id=self.set_id, LockToken=self.locktoken)
154 except (BotoCoreError, ClientError) as e:
155 self.fail_json_aws(e, msg="Failed to remove wafv2 ip set.")
156 return {}
157
158 def create(self, description, ip_address_version, addresses, tags):
159 req_obj = {
160 "Name": self.name,
161 "Scope": self.scope,
162 "IPAddressVersion": ip_address_version,
163 "Addresses": addresses,
164 }
165
166 if description:
167 req_obj["Description"] = description
168
169 if tags:
170 req_obj["Tags"] = ansible_dict_to_boto3_tag_list(tags)
171
172 try:
173 self.wafv2.create_ip_set(**req_obj)
174 except (BotoCoreError, ClientError) as e:
175 self.fail_json_aws(e, msg="Failed to create wafv2 ip set.")
176
177 self.existing_set, self.set_id, self.locktoken, self.arn = self.get_set()
178 return self._format_set(self.existing_set)
179
180 def update(self, description, addresses):
181 req_obj = {
182 "Name": self.name,
183 "Scope": self.scope,
184 "Id": self.set_id,
185 "Addresses": addresses,
186 "LockToken": self.locktoken,
187 }
188
189 if description:
190 req_obj["Description"] = description
191
192 try:
193 self.wafv2.update_ip_set(**req_obj)
194 except (BotoCoreError, ClientError) as e:
195 self.fail_json_aws(e, msg="Failed to update wafv2 ip set.")
196
197 self.existing_set, self.set_id, self.locktoken, self.arn = self.get_set()
198 return self._format_set(self.existing_set)
199
200 def get_set(self):
201 response = self.list()
202 existing_set = None
203 set_id = None
204 arn = None
205 locktoken = None
206 for item in response.get("IPSets"):
207 if item.get("Name") == self.name:
208 set_id = item.get("Id")
209 locktoken = item.get("LockToken")
210 arn = item.get("ARN")
211 if set_id:
212 try:
213 existing_set = self.wafv2.get_ip_set(Name=self.name, Scope=self.scope, Id=set_id).get("IPSet")
214 except (BotoCoreError, ClientError) as e:
215 self.fail_json_aws(e, msg="Failed to get wafv2 ip set.")
216 tags = describe_wafv2_tags(self.wafv2, arn, self.fail_json_aws)
217 existing_set["tags"] = tags
218
219 return existing_set, set_id, locktoken, arn
220
221 def list(self, Nextmarker=None):
222 # there is currently no paginator for wafv2
223 req_obj = {"Scope": self.scope, "Limit": 100}
224 if Nextmarker:
225 req_obj["NextMarker"] = Nextmarker
226
227 try:
228 response = self.wafv2.list_ip_sets(**req_obj)
229 if response.get("NextMarker"):
230 response["IPSets"] += self.list(Nextmarker=response.get("NextMarker")).get("IPSets")
231 except (BotoCoreError, ClientError) as e:
232 self.fail_json_aws(e, msg="Failed to list wafv2 ip set.")
233
234 return response
235
236
237 def compare(existing_set, addresses, purge_addresses, state):
238 diff = False
239 new_rules = []
240 existing_rules = existing_set.get("addresses")
241 if state == "present":
242 if purge_addresses:
243 new_rules = addresses
244 if sorted(addresses) != sorted(existing_set.get("addresses")):
245 diff = True
246
247 else:
248 for requested_rule in addresses:
249 if requested_rule not in existing_rules:
250 diff = True
251 new_rules.append(requested_rule)
252
253 new_rules += existing_rules
254 else:
255 if purge_addresses and addresses:
256 for requested_rule in addresses:
257 if requested_rule in existing_rules:
258 diff = True
259 existing_rules.pop(existing_rules.index(requested_rule))
260 new_rules = existing_rules
261
262 return diff, new_rules
263
264
265 def main():
266 arg_spec = dict(
267 state=dict(type="str", required=True, choices=["present", "absent"]),
268 name=dict(type="str", required=True),
269 scope=dict(type="str", required=True, choices=["CLOUDFRONT", "REGIONAL"]),
270 description=dict(type="str"),
271 ip_address_version=dict(type="str", choices=["IPV4", "IPV6"]),
272 addresses=dict(type="list", elements="str"),
273 tags=dict(type="dict", aliases=["resource_tags"]),
274 purge_tags=dict(type="bool", default=True),
275 purge_addresses=dict(type="bool", default=True),
276 )
277
278 module = AnsibleAWSModule(
279 argument_spec=arg_spec,
280 supports_check_mode=True,
281 required_if=[["state", "present", ["ip_address_version", "addresses"]]],
282 )
283
284 state = module.params.get("state")
285 name = module.params.get("name")
286 scope = module.params.get("scope")
287 description = module.params.get("description")
288 ip_address_version = module.params.get("ip_address_version")
289 addresses = module.params.get("addresses")
290 tags = module.params.get("tags")
291 purge_tags = module.params.get("purge_tags")
292 purge_addresses = module.params.get("purge_addresses")
293 check_mode = module.check_mode
294
295 wafv2 = module.client("wafv2")
296
297 change = False
298 retval = {}
299
300 ip_set = IpSet(wafv2, name, scope, module.fail_json_aws)
301
302 if state == "present":
303 if ip_set.get():
304 tags_updated = ensure_wafv2_tags(
305 wafv2, ip_set.arn, tags, purge_tags, module.fail_json_aws, module.check_mode
306 )
307 ips_updated, addresses = compare(ip_set.get(), addresses, purge_addresses, state)
308 description_updated = bool(description) and ip_set.description() != description
309 change = ips_updated or description_updated or tags_updated
310 retval = ip_set.get()
311 if module.check_mode:
312 pass
313 elif ips_updated or description_updated:
314 retval = ip_set.update(description=description, addresses=addresses)
315 elif tags_updated:
316 retval, set_id, locktoken, arn = ip_set.get_set()
317 else:
318 if not check_mode:
319 retval = ip_set.create(
320 description=description, ip_address_version=ip_address_version, addresses=addresses, tags=tags
321 )
322 change = True
323
324 if state == "absent":
325 if ip_set.get():
326 if addresses:
327 if len(addresses) > 0:
328 change, addresses = compare(ip_set.get(), addresses, purge_addresses, state)
329 if change and not check_mode:
330 retval = ip_set.update(description=description, addresses=addresses)
331 else:
332 if not check_mode:
333 retval = ip_set.remove()
334 change = True
335
336 module.exit_json(changed=change, **retval)
337
338
339 if __name__ == "__main__":
340 main()