Debian Codegraph @

ansible_collections/amazon/aws/plugins/modules/ec2_vpc_nacl.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 module: ec2_vpc_nacl
9 short_description: create and delete Network ACLs
10 version_added: 1.0.0
11 version_added_collection: community.aws
12 description:
13 - Read the AWS documentation for Network ACLS
14 U(https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_ACLs.html).
15 options:
16 name:
17 description:
18 - Tagged name identifying a network ACL.
19 - One and only one of the O(name) or O(nacl_id) is required.
20 - Mutually exclusive with O(nacl_id).
21 required: false
22 type: str
23 nacl_id:
24 description:
25 - NACL id identifying a network ACL.
26 - One and only one of the O(name) or O(nacl_id) is required.
27 - Mutually exclusive with O(name).
28 required: false
29 type: str
30 vpc_id:
31 description:
32 - VPC id of the requesting VPC.
33 - Required when state present.
34 required: false
35 type: str
36 subnets:
37 description:
38 - The list of subnets that should be associated with the network ACL.
39 - Must be specified as a list
40 - Each subnet can be specified as subnet ID, or its tagged name.
41 required: false
42 type: list
43 elements: str
44 default: []
45 egress:
46 description:
47 - A list of rules for outgoing traffic. Each rule must be specified as a list.
48 Each rule may contain the rule number (integer 1-32766), protocol (one of ['tcp', 'udp', 'icmp', 'ipv6-icmp', '-1', 'all']),
49 the rule action ('allow' or 'deny') the CIDR of the IPv4 or IPv6 network range to allow or deny,
50 the ICMP type (-1 means all types), the ICMP code (-1 means all codes), the last port in the range for
51 TCP or UDP protocols, and the first port in the range for TCP or UDP protocols.
52 See examples.
53 default: []
54 required: false
55 type: list
56 elements: list
57 ingress:
58 description:
59 - List of rules for incoming traffic. Each rule must be specified as a list.
60 Each rule may contain the rule number (integer 1-32766), protocol (one of ['tcp', 'udp', 'icmp', 'ipv6-icmp', '-1', 'all']),
61 the rule action ('allow' or 'deny') the CIDR of the IPv4 or IPv6 network range to allow or deny,
62 the ICMP type (-1 means all types), the ICMP code (-1 means all codes), the last port in the range for
63 TCP or UDP protocols, and the first port in the range for TCP or UDP protocols.
64 See examples.
65 default: []
66 required: false
67 type: list
68 elements: list
69 state:
70 description:
71 - Creates or modifies an existing NACL.
72 - Deletes a NACL and reassociates subnets to the default NACL.
73 required: false
74 type: str
75 choices: ['present', 'absent']
76 default: present
77 author:
78 - Mike Mochan (@mmochan)
79 notes:
80 - Support for I(purge_tags) was added in release 4.0.0.
81 extends_documentation_fragment:
82 - amazon.aws.common.modules
83 - amazon.aws.region.modules
84 - amazon.aws.boto3
85 - amazon.aws.tags
86 """
87
88 EXAMPLES = r"""
89 # Complete example to create and delete a network ACL
90 # that allows SSH, HTTP and ICMP in, and all traffic out.
91 - name: "Create and associate production DMZ network ACL with DMZ subnets"
92 amazon.aws.ec2_vpc_nacl:
93 vpc_id: vpc-12345678
94 name: prod-dmz-nacl
95 region: ap-southeast-2
96 subnets: ['prod-dmz-1', 'prod-dmz-2']
97 tags:
98 CostCode: CC1234
99 Project: phoenix
100 Description: production DMZ
101 ingress:
102 # rule no, protocol, allow/deny, cidr, icmp_type, icmp_code,
103 # port from, port to
104 - [100, 'tcp', 'allow', '0.0.0.0/0', null, null, 22, 22]
105 - [200, 'tcp', 'allow', '0.0.0.0/0', null, null, 80, 80]
106 - [205, 'tcp', 'allow', '::/0', null, null, 80, 80]
107 - [300, 'icmp', 'allow', '0.0.0.0/0', 0, 8]
108 - [305, 'ipv6-icmp', 'allow', '::/0', 0, 8]
109 egress:
110 - [100, 'all', 'allow', '0.0.0.0/0', null, null, null, null]
111 - [105, 'all', 'allow', '::/0', null, null, null, null]
112 state: 'present'
113
114 - name: "Remove the ingress and egress rules - defaults to deny all"
115 amazon.aws.ec2_vpc_nacl:
116 vpc_id: vpc-12345678
117 name: prod-dmz-nacl
118 region: ap-southeast-2
119 subnets:
120 - prod-dmz-1
121 - prod-dmz-2
122 tags:
123 CostCode: CC1234
124 Project: phoenix
125 Description: production DMZ
126 state: present
127
128 - name: "Remove the NACL subnet associations and tags"
129 amazon.aws.ec2_vpc_nacl:
130 vpc_id: 'vpc-12345678'
131 name: prod-dmz-nacl
132 region: ap-southeast-2
133 state: present
134
135 - name: "Delete nacl and subnet associations"
136 amazon.aws.ec2_vpc_nacl:
137 vpc_id: vpc-12345678
138 name: prod-dmz-nacl
139 state: absent
140
141 - name: "Delete nacl by its id"
142 amazon.aws.ec2_vpc_nacl:
143 nacl_id: acl-33b4ee5b
144 state: absent
145 """
146
147 RETURN = r"""
148 nacl_id:
149 description: The id of the NACL (when creating or updating an ACL).
150 returned: success
151 type: str
152 sample: "acl-123456789abcdef01"
153 """
154
155 from typing import Any
156 from typing import Dict
157 from typing import List
158 from typing import Optional
159
160 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AnsibleEC2Error
161 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import create_network_acl
162 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import create_network_acl_entry
163 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import delete_network_acl
164 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import delete_network_acl_entry
165 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_network_acls
166 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_subnets
167 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import ensure_ec2_tags
168 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import replace_network_acl_association
169 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
170
171 # VPC-supported IANA protocol numbers
172 # http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
173 PROTOCOL_NUMBERS = {"all": -1, "icmp": 1, "tcp": 6, "udp": 17, "ipv6-icmp": 58}
174
175
176 # Utility methods
177 def icmp_present(entry: List[str]) -> bool:
178 return len(entry) == 6 and entry[1] in ["icmp", "ipv6-icmp"] or entry[1] in [1, 58]
179
180
181 def subnets_changed(client, module: AnsibleAWSModule, nacl_id: str, subnets_ids: List[str]) -> bool:
182 changed = False
183 vpc_id = module.params.get("vpc_id")
184
185 if not subnets_ids:
186 default_nacl_id = find_default_vpc_nacl(client, vpc_id)
187 # Find subnets by Network ACL ids
188 network_acls = describe_network_acls(
189 client, Filters=[{"Name": "association.network-acl-id", "Values": [nacl_id]}]
190 )
191 subnets = [
192 association["SubnetId"]
193 for nacl in network_acls
194 for association in nacl["Associations"]
195 if association["SubnetId"]
196 ]
197 changed = associate_nacl_to_subnets(client, module, default_nacl_id, subnets)
198 return changed
199
200 network_acls = describe_network_acls(client, NetworkAclIds=[nacl_id])
201 current_subnets = [
202 association["SubnetId"]
203 for nacl in network_acls
204 for association in nacl["Associations"]
205 if association["SubnetId"]
206 ]
207 subnets_added = [subnet for subnet in subnets_ids if subnet not in current_subnets]
208 subnets_removed = [subnet for subnet in current_subnets if subnet not in subnets_ids]
209
210 if subnets_added:
211 changed |= associate_nacl_to_subnets(client, module, nacl_id, subnets_added)
212 if subnets_removed:
213 default_nacl_id = find_default_vpc_nacl(client, vpc_id)
214 changed |= associate_nacl_to_subnets(client, module, default_nacl_id, subnets_removed)
215
216 return changed
217
218
219 def nacls_changed(client, module: AnsibleAWSModule, nacl_info: Dict[str, Any]) -> bool:
220 changed = False
221 entries = nacl_info["Entries"]
222 nacl_id = nacl_info["NetworkAclId"]
223 aws_egress_rules = [rule for rule in entries if rule["Egress"] is True and rule["RuleNumber"] < 32767]
224 aws_ingress_rules = [rule for rule in entries if rule["Egress"] is False and rule["RuleNumber"] < 32767]
225
226 # Egress Rules
227 changed |= rules_changed(client, nacl_id, module.params.get("egress"), aws_egress_rules, True, module.check_mode)
228 # Ingress Rules
229 changed |= rules_changed(client, nacl_id, module.params.get("ingress"), aws_ingress_rules, False, module.check_mode)
230 return changed
231
232
233 def tags_changed(client, module: AnsibleAWSModule, nacl_id: str) -> bool:
234 tags = module.params.get("tags")
235 name = module.params.get("name")
236 purge_tags = module.params.get("purge_tags")
237
238 if name is None and tags is None:
239 return False
240
241 if module.params.get("tags") is None:
242 # Only purge tags if tags is explicitly set to {} and purge_tags is True
243 purge_tags = False
244
245 new_tags = dict()
246 if module.params.get("name") is not None:
247 new_tags["Name"] = module.params.get("name")
248 new_tags.update(module.params.get("tags") or {})
249
250 return ensure_ec2_tags(
251 client, module, nacl_id, tags=new_tags, purge_tags=purge_tags, retry_codes=["InvalidNetworkAclID.NotFound"]
252 )
253
254
255 def ansible_to_boto3_dict_rule(ansible_rule: List[Any], egress: bool) -> Dict[str, Any]:
256 boto3_rule = {}
257 if isinstance(ansible_rule, list):
258 boto3_rule["RuleNumber"] = ansible_rule[0]
259 boto3_rule["Protocol"] = str(PROTOCOL_NUMBERS[ansible_rule[1]])
260 boto3_rule["RuleAction"] = ansible_rule[2]
261 boto3_rule["Egress"] = egress
262 if is_ipv6(ansible_rule[3]):
263 boto3_rule["Ipv6CidrBlock"] = ansible_rule[3]
264 else:
265 boto3_rule["CidrBlock"] = ansible_rule[3]
266 if icmp_present(ansible_rule):
267 boto3_rule["IcmpTypeCode"] = {"Type": int(ansible_rule[4]), "Code": int(ansible_rule[5])}
268 else:
269 if ansible_rule[6] or ansible_rule[7]:
270 boto3_rule["PortRange"] = {"From": ansible_rule[6], "To": ansible_rule[7]}
271 return boto3_rule
272
273
274 def find_added_rules(rules_a: List[Dict[str, Any]], rules_b: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
275 results = []
276 # A rule is considered as a new rule if either the RuleNumber does exist in the list of
277 # current Rules stored in AWS or if the Rule differs with the Rule stored in AWS with the same RuleNumber
278 for a in rules_a:
279 if not any(a["RuleNumber"] == b["RuleNumber"] and a == b for b in rules_b):
280 results.append(a)
281 return results
282
283
284 def rules_changed(
285 client,
286 nacl_id: str,
287 ansible_rules: List[List[str]],
288 aws_rules: List[Dict[str, Any]],
289 egress: bool,
290 check_mode: bool,
291 ) -> bool:
292 # transform rules: from ansible list to boto3 dict
293 ansible_rules = [ansible_to_boto3_dict_rule(r, egress) for r in ansible_rules]
294
295 # find added rules
296 added_rules = find_added_rules(ansible_rules, aws_rules)
297 # find removed rules
298 removed_rules = find_added_rules(aws_rules, ansible_rules)
299
300 changed = False
301 # Removed Rules
302 for rule in removed_rules:
303 changed = True
304 if not check_mode:
305 delete_network_acl_entry(client, network_acl_id=nacl_id, rule_number=rule["RuleNumber"], egress=egress)
306
307 # Added Rules
308 for rule in added_rules:
309 changed = True
310 if not check_mode:
311 rule_number = rule.pop("RuleNumber")
312 protocol = rule.pop("Protocol")
313 rule_action = rule.pop("RuleAction")
314 egress = rule.pop("Egress")
315 create_network_acl_entry(
316 client,
317 network_acl_id=nacl_id,
318 protocol=protocol,
319 egress=egress,
320 rule_action=rule_action,
321 rule_number=rule_number,
322 **rule,
323 )
324
325 return changed
326
327
328 def is_ipv6(cidr: str) -> bool:
329 return ":" in cidr
330
331
332 def process_rule_entry(entry: List[Any]) -> Dict[str, Any]:
333 params = {}
334 if is_ipv6(entry[3]):
335 params["Ipv6CidrBlock"] = entry[3]
336 else:
337 params["CidrBlock"] = entry[3]
338 if icmp_present(entry):
339 params["IcmpTypeCode"] = {"Type": int(entry[4]), "Code": int(entry[5])}
340 else:
341 if entry[6] or entry[7]:
342 params["PortRange"] = {"From": entry[6], "To": entry[7]}
343
344 return params
345
346
347 def add_network_acl_entries(
348 client, nacl_id: str, ansible_entries: List[List[str]], egress: bool, check_mode: bool
349 ) -> bool:
350 changed = False
351 for entry in ansible_entries:
352 changed = True
353 if not check_mode:
354 create_network_acl_entry(
355 client,
356 network_acl_id=nacl_id,
357 protocol=str(PROTOCOL_NUMBERS[entry[1]]),
358 egress=egress,
359 rule_action=entry[2],
360 rule_number=entry[0],
361 **process_rule_entry(entry),
362 )
363 return changed
364
365
366 def associate_nacl_to_subnets(client, module: AnsibleAWSModule, nacl_id: str, subnets_ids: List[str]) -> bool:
367 changed = False
368 if subnets_ids:
369 network_acls = describe_network_acls(client, Filters=[{"Name": "association.subnet-id", "Values": subnets_ids}])
370 associations = [
371 association["NetworkAclAssociationId"]
372 for nacl in network_acls
373 for association in nacl["Associations"]
374 if association["SubnetId"] in subnets_ids
375 ]
376 for association_id in associations:
377 changed = True
378 if not module.check_mode:
379 replace_network_acl_association(client, network_acl_id=nacl_id, association_id=association_id)
380 return changed
381
382
383 def ensure_present(client, module: AnsibleAWSModule) -> None:
384 changed = False
385 nacl = describe_network_acl(client, module)
386 nacl_id = None
387 subnets_ids = []
388 subnets = module.params.get("subnets")
389 if subnets:
390 subnets_ids = find_subnets_ids(client, module, subnets)
391
392 if not nacl:
393 if module.check_mode:
394 module.exit_json(changed=True, msg="Would have created Network ACL if not in check mode.")
395
396 # Create Network ACL
397 tags = {}
398 name = module.params.get("name")
399 vpc_id = module.params.get("vpc_id")
400 if name:
401 tags["Name"] = name
402 if module.params.get("tags"):
403 tags.update(module.params.get("tags"))
404 nacl = create_network_acl(client, vpc_id, tags)
405 changed = True
406
407 # Associate Subnets to Network ACL
408 nacl_id = nacl["NetworkAclId"]
409 changed |= associate_nacl_to_subnets(client, module, nacl_id, subnets_ids)
410
411 # Create Network ACL entries (ingress and egress)
412 changed |= add_network_acl_entries(
413 client, nacl_id, module.params.get("ingress"), egress=False, check_mode=module.check_mode
414 )
415 changed |= add_network_acl_entries(
416 client, nacl_id, module.params.get("egress"), egress=True, check_mode=module.check_mode
417 )
418 else:
419 nacl_id = nacl["NetworkAclId"]
420 changed |= subnets_changed(client, module, nacl_id, subnets_ids)
421 changed |= nacls_changed(client, module, nacl)
422 changed |= tags_changed(client, module, nacl_id)
423
424 module.exit_json(changed=changed, nacl_id=nacl_id)
425
426
427 def ensure_absent(client, module: AnsibleAWSModule) -> None:
428 changed = False
429 nacl = describe_network_acl(client, module)
430 if not nacl:
431 module.exit_json(changed=changed)
432
433 nacl_id = nacl["NetworkAclId"]
434 vpc_id = nacl["VpcId"]
435 associations = nacl["Associations"]
436 assoc_ids = [a["NetworkAclAssociationId"] for a in associations]
437
438 # Find default NACL associated to the VPC
439 default_nacl_id = find_default_vpc_nacl(client, vpc_id)
440 if not default_nacl_id:
441 module.exit_json(changed=changed, msg="Default NACL ID not found - Check the VPC ID")
442
443 # Replace Network ACL association
444 for assoc_id in assoc_ids:
445 changed = True
446 if not module.check_mode:
447 replace_network_acl_association(client, network_acl_id=default_nacl_id, association_id=assoc_id)
448
449 # Delete Network ACL
450 changed = True
451 if module.check_mode:
452 module.exit_json(changed=changed, msg=f"Would have deleted Network ACL id '{nacl_id}' if not in check mode.")
453
454 changed = delete_network_acl(client, network_acl_id=nacl_id)
455 module.exit_json(changed=changed, msg=f"Network ACL id '{nacl_id}' successfully deleted.")
456
457
458 def describe_network_acl(client, module: AnsibleAWSModule) -> Optional[Dict[str, Any]]:
459 nacl_id = module.params.get("nacl_id")
460 name = module.params.get("name")
461
462 if nacl_id:
463 filters = [{"Name": "network-acl-id", "Values": [nacl_id]}]
464 else:
465 filters = [{"Name": "tag:Name", "Values": [name]}]
466 network_acls = describe_network_acls(client, Filters=filters)
467 return None if not network_acls else network_acls[0]
468
469
470 def find_default_vpc_nacl(client, vpc_id: str) -> Optional[str]:
471 default_nacl_id = None
472 for nacl in describe_network_acls(client, Filters=[{"Name": "vpc-id", "Values": [vpc_id]}]):
473 if nacl.get("IsDefault", False):
474 default_nacl_id = nacl["NetworkAclId"]
475 break
476 return default_nacl_id
477
478
479 def find_subnets_ids(client, module: AnsibleAWSModule, subnets_ids_or_names: List[str]) -> List[str]:
480 subnets_ids = []
481 subnets_names = []
482
483 # Find Subnets by ID
484 subnets = describe_subnets(client, Filters=[{"Name": "subnet-id", "Values": subnets_ids_or_names}])
485 subnets_ids += [subnet["SubnetId"] for subnet in subnets]
486 subnets_names += [tag["Value"] for subnet in subnets for tag in subnet.get("Tags", []) if tag["Key"] == "Name"]
487
488 # Find Subnets by Name
489 subnets = describe_subnets(client, Filters=[{"Name": "tag:Name", "Values": subnets_ids_or_names}])
490 subnets_ids += [subnet["SubnetId"] for subnet in subnets]
491 subnets_names += [tag["Value"] for subnet in subnets for tag in subnet.get("Tags", []) if tag["Key"] == "Name"]
492
493 unexisting_subnets = [s for s in subnets_ids_or_names if s not in subnets_names + subnets_ids]
494 if unexisting_subnets:
495 module.fail_json(msg=f"The following subnets do not exist: {unexisting_subnets}")
496 return subnets_ids
497
498
499 def main():
500 argument_spec = dict(
501 vpc_id=dict(),
502 name=dict(),
503 nacl_id=dict(),
504 subnets=dict(required=False, type="list", default=[], elements="str"),
505 tags=dict(required=False, type="dict", aliases=["resource_tags"]),
506 purge_tags=dict(required=False, type="bool", default=True),
507 ingress=dict(required=False, type="list", default=list(), elements="list"),
508 egress=dict(required=False, type="list", default=list(), elements="list"),
509 state=dict(default="present", choices=["present", "absent"]),
510 )
511
512 mutually_exclusive = [
513 ["name", "nacl_id"],
514 ]
515
516 module = AnsibleAWSModule(
517 argument_spec=argument_spec,
518 supports_check_mode=True,
519 required_one_of=[["name", "nacl_id"]],
520 required_if=[["state", "present", ["vpc_id"]]],
521 mutually_exclusive=mutually_exclusive,
522 )
523
524 client = module.client("ec2")
525
526 try:
527 if module.params.get("state") == "present":
528 ensure_present(client, module)
529 else:
530 ensure_absent(client, module)
531 except AnsibleEC2Error as e:
532 module.fail_json_aws_error(e)
533
534
535 if __name__ == "__main__":
536 main()