Debian Codegraph @

ansible_collections/amazon/aws/plugins/modules/ec2_security_group.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: Contributors to the 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: ec2_security_group
10 version_added: 1.0.0
11 author:
12 - "Andrew de Quincey (@adq)"
13 - "Razique Mahroua (@Razique)"
14 short_description: Maintain an EC2 security group
15 description:
16 - Maintains EC2 security groups.
17 options:
18 name:
19 description:
20 - Name of the security group.
21 - One of and only one of O(name) or O(group_id) is required.
22 - Required if O(state=present).
23 required: false
24 type: str
25 group_id:
26 description:
27 - Id of group to delete (works only with absent).
28 - One of and only one of O(name) or O(group_id) is required.
29 required: false
30 type: str
31 description:
32 description:
33 - Description of the security group.
34 - Required when O(state) is V(present).
35 required: false
36 type: str
37 vpc_id:
38 description:
39 - ID of the VPC to create the group in.
40 required: false
41 type: str
42 rules:
43 description:
44 - List of firewall inbound rules to enforce in this group (see example). If none are supplied,
45 no inbound rules will be enabled. Rules list may include its own name in O(rules.group_name).
46 This allows idempotent loopback additions (e.g. allow group to access itself).
47 required: false
48 type: list
49 elements: dict
50 suboptions:
51 cidr_ip:
52 type: list
53 elements: str
54 description:
55 - The IPv4 CIDR range traffic is coming from.
56 - You can specify only one of O(rules.cidr_ip), O(rules.cidr_ipv6), O(rules.ip_prefix), O(rules.group_id)
57 and I(group_name).
58 cidr_ipv6:
59 type: list
60 elements: str
61 description:
62 - The IPv6 CIDR range traffic is coming from.
63 - You can specify only one of O(rules.cidr_ip), O(rules.cidr_ipv6), O(rules.ip_prefix), O(rules.group_id)
64 and I(rules.group_name).
65 ip_prefix:
66 type: list
67 elements: str
68 description:
69 - The IP Prefix U(https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-prefix-lists.html)
70 that traffic is coming from.
71 - You can specify only one of O(rules.cidr_ip), O(rules.cidr_ipv6), O(rules.ip_prefix), O(rules.group_id)
72 and O(rules.group_name).
73 group_id:
74 type: list
75 elements: str
76 description:
77 - The ID of the Security Group that traffic is coming from.
78 - You can specify only one of O(rules.cidr_ip), O(rules.cidr_ipv6), O(rules.ip_prefix), O(rules.group_id)
79 and O(rules.group_name).
80 group_name:
81 type: list
82 elements: str
83 description:
84 - Name of the Security Group that traffic is coming from.
85 - If the Security Group doesn't exist a new Security Group will be
86 created with O(rules.group_desc) as the description.
87 - O(rules.group_name) can accept values of type str and list.
88 - You can specify only one of O(rules.cidr_ip), O(rules.cidr_ipv6), O(rules.ip_prefix), O(rules.group_id)
89 and O(rules.group_name).
90 group_desc:
91 type: str
92 description:
93 - If the O(rules.group_name) is set and the Security Group doesn't exist a new Security Group will be
94 created with O(rules.group_desc) as the description.
95 proto:
96 type: str
97 description:
98 - The IP protocol name (V(tcp), V(udp), V(icmp), V(icmpv6)) or
99 number (U(https://en.wikipedia.org/wiki/List_of_IP_protocol_numbers)).
100 default: tcp
101 from_port:
102 type: int
103 description:
104 - The start of the range of ports that traffic is going to.
105 - A value can be between V(0) to V(65535).
106 - When O(rules.proto=icmp) a value of V(-1) indicates all ports.
107 - Mutually exclusive with O(rules.icmp_code), O(rules.icmp_type) and O(rules.ports).
108 to_port:
109 type: int
110 description:
111 - The end of the range of ports that traffic is going to.
112 - A value can be between V(0) to V(65535).
113 - When O(rules.proto=icmp) a value of V(-1) indicates all ports.
114 - Mutually exclusive with O(rules.icmp_code), O(rules.icmp_type) and O(rules.ports).
115 ports:
116 type: list
117 elements: str
118 description:
119 - A list of ports that traffic is going to.
120 - Elements of the list can be a single port (for example V(8080)), or a range of ports
121 specified as V(<START>-<END>), (for example V(1011-1023)).
122 - Mutually exclusive with O(rules.icmp_code), O(rules.icmp_type), O(rules.from_port) and O(rules.to_port).
123 icmp_type:
124 version_added: 3.3.0
125 type: int
126 description:
127 - The ICMP type of the packet.
128 - A value of V(-1) indicates all ICMP types.
129 - Requires O(rules.proto=icmp) or O(rules.proto=icmpv6).
130 - Mutually exclusive withot O(rules.ports), O(rules.from_port) and O(rules.to_port).
131 icmp_code:
132 version_added: 3.3.0
133 type: int
134 description:
135 - The ICMP code of the packet.
136 - A value of V(-1) indicates all ICMP codes.
137 - Requires O(rules.proto=icmp) or O(rules.proto=icmpv6).
138 - Mutually exclusive with O(rules.ports), O(rules.from_port) and O(rules.to_port).
139 rule_desc:
140 type: str
141 description: A description for the rule.
142
143 rules_egress:
144 description:
145 - List of firewall outbound rules to enforce in this group (see example). If none are supplied,
146 a default all-out rule is assumed. If an empty list is supplied, no outbound rules will be enabled.
147 required: false
148 type: list
149 elements: dict
150 aliases: ['egress_rules']
151 suboptions:
152 cidr_ip:
153 type: list
154 elements: str
155 description:
156 - The IPv4 CIDR range traffic is going to.
157 - You can specify only one of O(rules_egress.cidr_ip), O(rules_egress.cidr_ipv6), O(rules_egress.ip_prefix), O(rules_egress.group_id)
158 and I(rules_egress.group_name).
159 cidr_ipv6:
160 type: list
161 elements: str
162 description:
163 - The IPv6 CIDR range traffic is going to.
164 - You can specify only one of O(rules_egress.cidr_ip), O(rules_egress.cidr_ipv6), O(rules_egress.ip_prefix), O(rules_egress.group_id)
165 and O(rules_egress.group_name).
166 ip_prefix:
167 type: list
168 elements: str
169 description:
170 - The IP Prefix U(https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-prefix-lists.html)
171 that traffic is going to.
172 - You can specify only one of O(rules_egress.cidr_ip), O(rules_egress.cidr_ipv6), O(rules_egress.ip_prefix), O(rules_egress.group_id)
173 and O(rules_egress.group_name).
174 group_id:
175 type: list
176 elements: str
177 description:
178 - The ID of the Security Group that traffic is going to.
179 - You can specify only one of O(rules_egress.cidr_ip), O(rules_egress.cidr_ipv6), O(rules_egress.ip_prefix), O(rules_egress.group_id)
180 and O(rules_egress.group_name).
181 group_name:
182 type: list
183 elements: str
184 description:
185 - Name of the Security Group that traffic is going to.
186 - If the Security Group doesn't exist a new Security Group will be
187 created with O(rules_egress.group_desc) as the description.
188 - You can specify only one of O(rules_egress.cidr_ip), O(rules_egress.cidr_ipv6), O(rules_egress.ip_prefix), O(rules_egress.group_id)
189 and O(rules_egress.group_name).
190 group_desc:
191 type: str
192 description:
193 - If the O(rules_egress.group_name) is set and the Security Group doesn't exist a new Security Group will be
194 created with O(rules_egress.group_desc) as the description.
195 proto:
196 type: str
197 description:
198 - The IP protocol name (V(tcp), V(udp), V(icmp), V(icmpv6)) or
199 number (U(https://en.wikipedia.org/wiki/List_of_IP_protocol_numbers)).
200 default: 'tcp'
201 from_port:
202 type: int
203 description:
204 - The start of the range of ports that traffic is going to.
205 - A value can be between V(0) to V(65535).
206 - When O(rules_egress.proto=icmp) a value of V(-1) indicates all ports.
207 - Mutually exclusive with O(rules_egress.icmp_code), O(rules_egress.icmp_type) and O(rules_egress.ports).
208 to_port:
209 type: int
210 description:
211 - The end of the range of ports that traffic is going to.
212 - A value can be between C(0) to C(65535).
213 - When O(rules_egress.proto=icmp) a value of V(-1) indicates all ports.
214 - Mutually exclusive with O(rules_egress.icmp_code), O(rules_egress.icmp_type) and O(rules_egress.ports).
215 ports:
216 type: list
217 elements: str
218 description:
219 - A list of ports that traffic is going to.
220 - Elements of the list can be a single port (for example V(8080)), or a range of ports
221 specified as V(<START>-<END>), (for example V(1011-1023)).
222 - Mutually exclusive with O(rules_egress.icmp_code), O(rules_egress.icmp_type), O(rules_egress.from_port) and O(rules_egress.to_port).
223 icmp_type:
224 version_added: 3.3.0
225 type: int
226 description:
227 - The ICMP type of the packet.
228 - A value of CV(-1) indicates all ICMP types.
229 - Requires O(rules_egress.proto=icmp) or O(rules_egress.proto=icmpv6).
230 - Mutually exclusive with O(rules_egress.ports), O(rules_egress.from_port) and O(rules_egress.to_port).
231 icmp_code:
232 version_added: 3.3.0
233 type: int
234 description:
235 - The ICMP code of the packet.
236 - A value of V(-1) indicates all ICMP codes.
237 - Requires O(rules_egress.proto=icmp) or O(rules_egress.proto=icmpv6).
238 - Mutually exclusive with O(rules_egress.ports), O(rules_egress.from_port) and O(rules_egress.to_port).
239 rule_desc:
240 type: str
241 description: A description for the rule.
242 state:
243 description:
244 - Create or delete a security group.
245 required: false
246 default: 'present'
247 choices: [ "present", "absent" ]
248 aliases: []
249 type: str
250 purge_rules:
251 description:
252 - Purge existing rules on security group that are not found in rules.
253 required: false
254 default: 'true'
255 aliases: []
256 type: bool
257 purge_rules_egress:
258 description:
259 - Purge existing rules_egress on security group that are not found in rules_egress.
260 required: false
261 default: 'true'
262 aliases: ['purge_egress_rules']
263 type: bool
264
265 extends_documentation_fragment:
266 - amazon.aws.common.modules
267 - amazon.aws.region.modules
268 - amazon.aws.tags
269 - amazon.aws.boto3
270
271 notes:
272 - If a rule declares a group_name and that group doesn't exist, it will be
273 automatically created. In that case, group_desc should be provided as well.
274 The module will refuse to create a depended-on group without a description.
275 - Prior to release 5.0.0 this module was called M(amazon.aws.ec2_group_info). The usage did not
276 change.
277 """
278
279 EXAMPLES = r"""
280 # Note: These examples do not set authentication details, see the AWS Guide for details.
281
282 - name: example using security group rule descriptions
283 amazon.aws.ec2_security_group:
284 name: "{{ name }}"
285 description: sg with rule descriptions
286 vpc_id: vpc-xxxxxxxx
287 rules:
288 - proto: tcp
289 ports:
290 - 80
291 cidr_ip: 0.0.0.0/0
292 rule_desc: allow all on port 80
293
294 - name: example using ICMP types and codes
295 amazon.aws.ec2_security_group:
296 name: "{{ name }}"
297 description: sg for ICMP
298 vpc_id: vpc-xxxxxxxx
299 rules:
300 - proto: icmp
301 icmp_type: 3
302 icmp_code: 1
303 cidr_ip: 0.0.0.0/0
304
305 - name: example ec2 group
306 amazon.aws.ec2_security_group:
307 name: example
308 description: an example EC2 group
309 vpc_id: 12345
310 rules:
311 - proto: tcp
312 from_port: 80
313 to_port: 80
314 cidr_ip: 0.0.0.0/0
315 - proto: tcp
316 from_port: 22
317 to_port: 22
318 cidr_ip: 10.0.0.0/8
319 - proto: tcp
320 from_port: 443
321 to_port: 443
322 # this should only be needed for EC2 Classic security group rules
323 # because in a VPC an ELB will use a user-account security group
324 group_id: amazon-elb/sg-87654321/amazon-elb-sg
325 - proto: tcp
326 from_port: 3306
327 to_port: 3306
328 group_id: 123456789012/sg-87654321/exact-name-of-sg
329 - proto: udp
330 from_port: 10050
331 to_port: 10050
332 cidr_ip: 10.0.0.0/8
333 - proto: udp
334 from_port: 10051
335 to_port: 10051
336 group_id: sg-12345678
337 - proto: icmp
338 from_port: 8 # icmp type, -1 = any type
339 to_port: -1 # icmp subtype, -1 = any subtype
340 cidr_ip: 10.0.0.0/8
341 - proto: all
342 # the containing group name may be specified here
343 group_name: example
344 - proto: all
345 # in the 'proto' attribute, if you specify -1 (only supported when I(proto=icmp)), all, or a protocol number
346 # other than tcp, udp, icmp, or 58 (ICMPv6), traffic on all ports is allowed, regardless of any ports that
347 # you specify.
348 from_port: 10050 # this value is ignored
349 to_port: 10050 # this value is ignored
350 cidr_ip: 10.0.0.0/8
351
352 rules_egress:
353 - proto: tcp
354 from_port: 80
355 to_port: 80
356 cidr_ip: 0.0.0.0/0
357 cidr_ipv6: 64:ff9b::/96
358 group_name: example-other
359 # description to use if example-other needs to be created
360 group_desc: other example EC2 group
361
362 - name: example2 ec2 group
363 amazon.aws.ec2_security_group:
364 name: example2
365 description: an example2 EC2 group
366 vpc_id: 12345
367 rules:
368 # 'ports' rule keyword was introduced in version 2.4. It accepts a single
369 # port value or a list of values including ranges (from_port-to_port).
370 - proto: tcp
371 ports: 22
372 group_name: example-vpn
373 - proto: tcp
374 ports:
375 - 80
376 - 443
377 - 8080-8099
378 cidr_ip: 0.0.0.0/0
379 # Rule sources list support was added in version 2.4. This allows to
380 # define multiple sources per source type as well as multiple source types per rule.
381 - proto: tcp
382 ports:
383 - 6379
384 - 26379
385 group_name:
386 - example-vpn
387 - example-redis
388 - proto: tcp
389 ports: 5665
390 group_name: example-vpn
391 cidr_ip:
392 - 172.16.1.0/24
393 - 172.16.17.0/24
394 cidr_ipv6:
395 - 2607:F8B0::/32
396 - 64:ff9b::/96
397 group_id:
398 - sg-edcd9784
399 diff: true
400
401 - name: "Delete group by its id"
402 amazon.aws.ec2_security_group:
403 group_id: sg-33b4ee5b
404 state: absent
405 """
406
407 RETURN = r"""
408 description:
409 description: Description of security group.
410 sample: My Security Group
411 type: str
412 returned: on create/update
413 group_id:
414 description: Security group id.
415 sample: sg-abcd1234
416 type: str
417 returned: on create/update
418 group_name:
419 description: Security group name.
420 sample: My Security Group
421 type: str
422 returned: on create/update
423 ip_permissions:
424 description: The inbound rules associated with the security group.
425 returned: always
426 type: list
427 elements: dict
428 contains:
429 from_port:
430 description: If the protocol is TCP or UDP, this is the start of the port range.
431 type: int
432 sample: 80
433 ip_protocol:
434 description: The IP protocol name or number.
435 returned: always
436 type: str
437 ip_ranges:
438 description: The IPv4 ranges.
439 returned: always
440 type: list
441 elements: dict
442 contains:
443 cidr_ip:
444 description: The IPv4 CIDR range.
445 returned: always
446 type: str
447 ipv6_ranges:
448 description: The IPv6 ranges.
449 returned: always
450 type: list
451 elements: dict
452 contains:
453 cidr_ipv6:
454 description: The IPv6 CIDR range.
455 returned: always
456 type: str
457 prefix_list_ids:
458 description: The prefix list IDs.
459 returned: always
460 type: list
461 elements: dict
462 contains:
463 prefix_list_id:
464 description: The ID of the prefix.
465 returned: always
466 type: str
467 to_group:
468 description: If the protocol is TCP or UDP, this is the end of the port range.
469 type: int
470 sample: 80
471 user_id_group_pairs:
472 description: The security group and AWS account ID pairs.
473 returned: always
474 type: list
475 elements: dict
476 contains:
477 group_id:
478 description: The security group ID of the pair.
479 returned: always
480 type: str
481 user_id:
482 description: The user ID of the pair.
483 returned: always
484 type: str
485 ip_permissions_egress:
486 description: The outbound rules associated with the security group.
487 returned: always
488 type: list
489 elements: dict
490 contains:
491 ip_protocol:
492 description: The IP protocol name or number.
493 returned: always
494 type: str
495 ip_ranges:
496 description: The IPv4 ranges.
497 returned: always
498 type: list
499 elements: dict
500 contains:
501 cidr_ip:
502 description: The IPv4 CIDR range.
503 returned: always
504 type: str
505 ipv6_ranges:
506 description: The IPv6 ranges.
507 returned: always
508 type: list
509 elements: dict
510 contains:
511 cidr_ipv6:
512 description: The IPv6 CIDR range.
513 returned: always
514 type: str
515 prefix_list_ids:
516 description: The prefix list IDs.
517 returned: always
518 type: list
519 elements: dict
520 contains:
521 prefix_list_id:
522 description: The ID of the prefix.
523 returned: always
524 type: str
525 user_id_group_pairs:
526 description: The security group and AWS account ID pairs.
527 returned: always
528 type: list
529 elements: dict
530 contains:
531 group_id:
532 description: The security group ID of the pair.
533 returned: always
534 type: str
535 user_id:
536 description: The user ID of the pair.
537 returned: always
538 type: str
539 owner_id:
540 description: AWS Account ID of the security group.
541 sample: 123456789012
542 type: int
543 returned: on create/update
544 tags:
545 description: Tags associated with the security group.
546 sample:
547 Name: My Security Group
548 Purpose: protecting stuff
549 type: dict
550 returned: on create/update
551 vpc_id:
552 description: ID of VPC to which the security group belongs.
553 sample: vpc-abcd1234
554 type: str
555 returned: on create/update
556 """
557
558
559 import itertools
560 import json
561 import re
562 from collections import namedtuple
563 from copy import deepcopy
564 from ipaddress import ip_network
565 from time import sleep
566 from typing import Any
567 from typing import Dict
568 from typing import List
569 from typing import Optional
570 from typing import Tuple
571
572 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
573 from ansible.module_utils.common.network import to_ipv6_subnet
574 from ansible.module_utils.common.network import to_subnet
575 from ansible.module_utils.common.text.converters import to_text
576
577 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AnsibleEC2Error
578 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import authorize_security_group_egress
579 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import authorize_security_group_ingress
580 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import create_security_group
581 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import delete_security_group
582 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_security_groups
583 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import ensure_ec2_tags
584 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import revoke_security_group_egress
585 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import revoke_security_group_ingress
586 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import update_security_group_rule_descriptions_egress
587 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import update_security_group_rule_descriptions_ingress
588 from ansible_collections.amazon.aws.plugins.module_utils.exceptions import AnsibleAWSError
589 from ansible_collections.amazon.aws.plugins.module_utils.exceptions import is_ansible_aws_error_code
590 from ansible_collections.amazon.aws.plugins.module_utils.iam import get_aws_account_id
591 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
592 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict
593 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_specifications
594 from ansible_collections.amazon.aws.plugins.module_utils.tagging import compare_aws_tags
595 from ansible_collections.amazon.aws.plugins.module_utils.transformation import ansible_dict_to_boto3_filter_list
596 from ansible_collections.amazon.aws.plugins.module_utils.transformation import scrub_none_parameters
597 from ansible_collections.amazon.aws.plugins.module_utils.waiters import wait_for_resource_state
598
599 Rule = namedtuple("Rule", ["port_range", "protocol", "target", "target_type", "description"])
600 TARGET_TYPES_ALL = {"ipv4", "ipv6", "group", "ip_prefix"}
601 SOURCE_TYPES_ALL = {"cidr_ip", "cidr_ipv6", "group_id", "group_name", "ip_prefix"}
602 PORT_TYPES_ALL = {"from_port", "to_port", "ports", "icmp_type", "icmp_code"}
603 current_account_id = None
604
605
606 class SecurityGroupError(Exception):
607 def __init__(self, msg, e=None, **kwargs):
608 super().__init__(msg)
609 self.message = msg
610 self.exception = e
611 self.kwargs = kwargs
612
613 # Simple helper to perform the module.fail_... call once we have module available to us
614 def fail(self, module):
615 if self.exception:
616 if isinstance(self.exception, AnsibleEC2Error):
617 module.fail_json_aws_error(self.exception)
618 module.fail_json_aws(self.exception, msg=self.message, **self.kwargs)
619 module.fail_json(msg=self.message, **self.kwargs)
620
621
622 def rule_cmp(a, b):
623 """Compare rules without descriptions"""
624 for prop in ["port_range", "protocol", "target", "target_type"]:
625 if prop == "port_range" and to_text(a.protocol) == to_text(b.protocol):
626 # equal protocols can interchange `(-1, -1)` and `(None, None)`
627 if a.port_range in ((None, None), (-1, -1)) and b.port_range in ((None, None), (-1, -1)):
628 continue
629 if getattr(a, prop) != getattr(b, prop):
630 return False
631 elif getattr(a, prop) != getattr(b, prop):
632 return False
633 return True
634
635
636 def rules_to_permissions(rules):
637 return [to_permission(rule) for rule in rules]
638
639
640 def to_permission(rule):
641 # take a Rule, output the serialized grant
642 perm = {
643 "IpProtocol": rule.protocol,
644 }
645 perm["FromPort"], perm["ToPort"] = rule.port_range
646 if rule.target_type == "ipv4":
647 perm["IpRanges"] = [
648 {
649 "CidrIp": rule.target,
650 }
651 ]
652 if rule.description:
653 perm["IpRanges"][0]["Description"] = rule.description
654 elif rule.target_type == "ipv6":
655 perm["Ipv6Ranges"] = [
656 {
657 "CidrIpv6": rule.target,
658 }
659 ]
660 if rule.description:
661 perm["Ipv6Ranges"][0]["Description"] = rule.description
662 elif rule.target_type == "group":
663 if isinstance(rule.target, tuple):
664 pair = {}
665 if rule.target[0]:
666 pair["UserId"] = rule.target[0]
667 # group_id/group_name are mutually exclusive - give group_id more precedence as it is more specific
668 if rule.target[1]:
669 pair["GroupId"] = rule.target[1]
670 elif rule.target[2]:
671 pair["GroupName"] = rule.target[2]
672 perm["UserIdGroupPairs"] = [pair]
673 else:
674 perm["UserIdGroupPairs"] = [{"GroupId": rule.target}]
675 if rule.description:
676 perm["UserIdGroupPairs"][0]["Description"] = rule.description
677 elif rule.target_type == "ip_prefix":
678 perm["PrefixListIds"] = [
679 {
680 "PrefixListId": rule.target,
681 }
682 ]
683 if rule.description:
684 perm["PrefixListIds"][0]["Description"] = rule.description
685 elif rule.target_type not in TARGET_TYPES_ALL:
686 raise ValueError(f"Invalid target type for rule {rule}")
687 return fix_port_and_protocol(perm)
688
689
690 def rule_from_group_permission(perm):
691 """
692 Returns a rule dict from an existing security group.
693
694 When using a security group as a target all 3 fields (OwnerId, GroupId, and
695 GroupName) need to exist in the target. This ensures consistency of the
696 values that will be compared to desired_ingress or desired_egress
697 in wait_for_rule_propagation().
698 GroupId is preferred as it is more specific except when targeting 'amazon-'
699 prefixed security groups (such as EC2 Classic ELBs).
700 """
701
702 def ports_from_permission(p):
703 if "FromPort" not in p and "ToPort" not in p:
704 return (None, None)
705 return (int(perm["FromPort"]), int(perm["ToPort"]))
706
707 # outputs a rule tuple
708 for target_key, target_subkey, target_type in [
709 ("IpRanges", "CidrIp", "ipv4"),
710 ("Ipv6Ranges", "CidrIpv6", "ipv6"),
711 ("PrefixListIds", "PrefixListId", "ip_prefix"),
712 ]:
713 if target_key not in perm:
714 continue
715 for r in perm[target_key]:
716 # there may be several IP ranges here, which is ok
717 yield Rule(
718 ports_from_permission(perm),
719 to_text(perm["IpProtocol"]),
720 r[target_subkey],
721 target_type,
722 r.get("Description"),
723 )
724 if "UserIdGroupPairs" in perm and perm["UserIdGroupPairs"]:
725 for pair in perm["UserIdGroupPairs"]:
726 target = (
727 pair.get("UserId", current_account_id),
728 pair.get("GroupId", None),
729 None,
730 )
731 if pair.get("UserId", "").startswith("amazon-"):
732 # amazon-elb and amazon-prefix rules don't need
733 # group-id specified, so remove it when querying
734 # from permission
735 target = (
736 pair.get("UserId", None),
737 None,
738 pair.get("GroupName", None),
739 )
740 elif "VpcPeeringConnectionId" not in pair and pair["UserId"] != current_account_id:
741 # EC2-Classic cross-account
742 pass
743 elif "VpcPeeringConnectionId" in pair:
744 # EC2-VPC cross-account VPC peering
745 target = (
746 pair.get("UserId", None),
747 pair.get("GroupId", None),
748 None,
749 )
750
751 yield Rule(
752 ports_from_permission(perm), to_text(perm["IpProtocol"]), target, "group", pair.get("Description")
753 )
754
755
756 def deduplicate_rules_args(rules):
757 """Returns unique rules"""
758 if rules is None:
759 return None
760 return list(dict(zip((json.dumps(r, sort_keys=True) for r in rules), rules)).values())
761
762
763 def validate_rule(rule):
764 icmp_type = rule.get("icmp_type", None)
765 icmp_code = rule.get("icmp_code", None)
766 proto = rule["proto"]
767 if (icmp_type is not None or icmp_code is not None) and ("icmp" not in proto):
768 raise SecurityGroupError(msg="Specify proto: icmp or icmpv6 when using icmp_type/icmp_code")
769
770
771 def _target_from_rule_with_group_id(rule, groups):
772 owner_id = current_account_id
773 FOREIGN_SECURITY_GROUP_REGEX = r"^([^/]+)/?(sg-[^/]+)?/([^/]+)$"
774 foreign_rule = re.match(FOREIGN_SECURITY_GROUP_REGEX, rule["group_id"])
775
776 if not foreign_rule:
777 return "group", (owner_id, rule["group_id"], None), False
778
779 # this is a foreign Security Group. Since you can't fetch it you must create an instance of it
780 # Matches on groups like amazon-elb/sg-5a9c116a/amazon-elb-sg, amazon-elb/amazon-elb-sg,
781 # and peer-VPC groups like 0987654321/sg-1234567890/example
782 owner_id, group_id, group_name = foreign_rule.groups()
783 group_instance = dict(UserId=owner_id, GroupId=group_id, GroupName=group_name)
784 groups[group_id] = group_instance
785 groups[group_name] = group_instance
786 if group_id and group_name:
787 if group_name.startswith("amazon-"):
788 # amazon-elb and amazon-prefix rules don't need group_id specified,
789 group_id = None
790 else:
791 # For cross-VPC references we'll use group_id as it is more specific
792 group_name = None
793 return "group", (owner_id, group_id, group_name), False
794
795
796 def _lookup_target_or_fail(client, group_name: str, vpc_id: Optional[str], msg: str) -> Optional[Dict[str, Any]]:
797 filters = {"group-name": group_name}
798 if vpc_id:
799 filters["vpc-id"] = vpc_id
800
801 filters = ansible_dict_to_boto3_filter_list(filters)
802 try:
803 found_group = describe_security_groups(client, Filters=filters)
804 if not found_group:
805 raise SecurityGroupError(msg=msg)
806 return found_group[0]
807 except AnsibleEC2Error as e:
808 raise SecurityGroupError(msg="Failed to get security group", e=e)
809
810
811 def _create_target_from_rule(
812 client, module: AnsibleAWSModule, rule: Dict[str, Any], vpc_id: str, tags: Dict[str, Any]
813 ) -> Tuple[Optional[Dict[str, Any]], bool]:
814 # We can't create a group in check mode...
815 if module.check_mode:
816 return None, True
817
818 group_name = rule["group_name"]
819 changed = False
820 group = None
821
822 try:
823 group = _create_security_group_with_wait(client, module, group_name, rule["group_desc"], vpc_id, tags)
824 changed = True
825 except is_ansible_aws_error_code("InvalidGroup.Duplicate"):
826 # The group exists, but didn't show up in any of our previous describe-security-groups calls
827 # Try searching on a filter for the name, and allow a retry window for AWS to update
828 # the model on their end.
829 fail_msg = (
830 f"Could not create or use existing group '{group_name}' in rule {rule}. "
831 "Make sure the group exists and try using the group_id "
832 "instead of the name"
833 )
834 group = _lookup_target_or_fail(client, group_name, vpc_id, fail_msg)
835 changed = False
836 except AnsibleAWSError as e: # pylint: disable=duplicate-except
837 raise SecurityGroupError(msg=f"Failed to create security group '{group_name}' in rule {rule}", e=e)
838 return group, changed
839
840
841 def _target_from_rule_with_group_name(
842 client,
843 module: AnsibleAWSModule,
844 rule: Dict[str, Any],
845 name: str,
846 group: Dict[str, Any],
847 groups: Dict[str, Any],
848 vpc_id: str,
849 tags: Dict[str, Any],
850 ) -> Tuple[str, bool]:
851 group_name = rule["group_name"]
852 if group_name == name:
853 # Simplest case, the rule references itself
854 group_id = group["GroupId"]
855 groups[group_id] = group
856 groups[group_name] = group
857 return group_id, False
858
859 # Already cached groups
860 if group_name in groups and group.get("VpcId") and groups[group_name].get("VpcId"):
861 # both are VPC groups, this is ok
862 group_id = groups[group_name]["GroupId"]
863 return group_id, False
864
865 if group_name in groups and not (group.get("VpcId") or groups[group_name].get("VpcId")):
866 # both are EC2 classic, this is ok
867 group_id = groups[group_name]["GroupId"]
868 return group_id, False
869
870 # if we got here, either the target group does not exist, or there
871 # is a mix of EC2 classic + VPC groups. Mixing of EC2 classic + VPC
872 # is bad, so we have to create a new SG because no compatible group
873 # exists
874
875 changed = False
876 # Without a group description we can't create a new group, try looking up the group, or fail
877 # with a descriptive error message
878 if not rule.get("group_desc", "").strip():
879 # retry describing the group
880 fail_msg = (
881 f"group '{group_name}' not found and would be automatically created by rule {rule} but "
882 "no description was provided"
883 )
884 created_group = _lookup_target_or_fail(client, group_name, vpc_id, fail_msg)
885 else:
886 created_group, changed = _create_target_from_rule(client, module, rule, vpc_id, tags)
887
888 group_id = None
889 if created_group:
890 group_id = created_group["GroupId"]
891 groups[group_id] = created_group
892 groups[group_name] = created_group
893
894 return group_id, changed
895
896
897 def get_target_from_rule(module, client, rule, name, group, groups, vpc_id, tags):
898 """
899 Returns tuple of (target_type, target, group_created) after validating rule params.
900
901 rule: Dict describing a rule.
902 name: Name of the security group being managed.
903 groups: Dict of all available security groups.
904
905 AWS accepts an ip range or a security group as target of a rule. This
906 function validate the rule specification and return either a non-None
907 group_id or a non-None ip range.
908
909 When using a security group as a target all 3 fields (OwnerId, GroupId, and
910 GroupName) need to exist in the target. This ensures consistency of the
911 values that will be compared to current_rules (from current_ingress and
912 current_egress) in wait_for_rule_propagation().
913 """
914 try:
915 if rule.get("group_id"):
916 return _target_from_rule_with_group_id(rule, groups)
917 if "group_name" in rule:
918 group_id, changed = _target_from_rule_with_group_name(
919 client, module, rule, name, group, groups, vpc_id, tags
920 )
921 return "group", (current_account_id, group_id, None), changed
922 if "cidr_ip" in rule:
923 return "ipv4", validate_ip(module, rule["cidr_ip"]), False
924 if "cidr_ipv6" in rule:
925 return "ipv6", validate_ip(module, rule["cidr_ipv6"]), False
926 if "ip_prefix" in rule:
927 return "ip_prefix", rule["ip_prefix"], False
928 except SecurityGroupError as e:
929 e.fail(module)
930
931 module.fail_json(msg="Could not match target for rule", failed_rule=rule)
932
933
934 def _strip_rule(rule):
935 """
936 Returns a copy of the rule with the Target/Source and Port information
937 from a rule stripped out.
938 This can then be combined with the expanded information
939 """
940 stripped_rule = deepcopy(rule)
941 # Get just the non-source/port info from the rule
942 [stripped_rule.pop(source_type, None) for source_type in SOURCE_TYPES_ALL]
943 [stripped_rule.pop(port_type, None) for port_type in PORT_TYPES_ALL]
944 return stripped_rule
945
946
947 def expand_rules(rules):
948 if rules is None:
949 return rules
950
951 expanded_rules = []
952 for rule in rules:
953 expanded_rules.extend(expand_rule(rule))
954
955 return expanded_rules
956
957
958 def expand_rule(rule):
959 rule = scrub_none_parameters(rule)
960 ports_list = expand_ports_from_rule(rule)
961 sources_list = expand_sources_from_rule(rule)
962 stripped_rule = _strip_rule(rule)
963
964 # expands out all possible combinations of ports and sources for the rule
965 # This results in a list of pairs of dictionaries...
966 ports_and_sources = itertools.product(ports_list, sources_list)
967
968 # Combines each pair of port/source dictionaries with rest of the info from the rule
969 return [{**stripped_rule, **port, **source} for (port, source) in ports_and_sources]
970
971
972 def expand_sources_from_rule(rule):
973 sources = []
974 for type_name in sorted(SOURCE_TYPES_ALL):
975 if rule.get(type_name) is not None:
976 sources.extend([{type_name: target} for target in rule.get(type_name)])
977 if not sources:
978 raise SecurityGroupError("Unable to find source/target information in rule", rule=rule)
979 return tuple(sources)
980
981
982 def expand_ports_from_rule(rule):
983 # While icmp_type/icmp_code could have been aliases, this wouldn't be obvious in the
984 # documentation
985 if rule.get("icmp_type") is not None:
986 return ({"from_port": rule.get("icmp_type"), "to_port": rule.get("icmp_code")},)
987 if rule.get("from_port") is not None or rule.get("to_port") is not None:
988 return ({"from_port": rule.get("from_port"), "to_port": rule.get("to_port")},)
989 if rule.get("ports") is not None:
990 ports = expand_ports_list(rule.get("ports"))
991 return tuple({"from_port": from_port, "to_port": to_port} for (from_port, to_port) in ports)
992 return ({},)
993
994
995 def expand_ports_list(ports):
996 # takes a list of ports and returns a list of (port_from, port_to)
997 ports_expanded = []
998 for port in ports:
999 try:
1000 port_list = (int(port.strip()),) * 2
1001 except ValueError as e:
1002 # Someone passed a range
1003 if "-" in port:
1004 port_list = [int(p.strip()) for p in port.split("-", 1)]
1005 else:
1006 raise SecurityGroupError("Unable to parse port", port=port) from e
1007 ports_expanded.append(tuple(sorted(port_list)))
1008
1009 return ports_expanded
1010
1011
1012 def update_rules_description(
1013 module: AnsibleAWSModule, client, rule_type: str, group_id: str, ip_permissions: List[Dict[str, Any]]
1014 ) -> bool:
1015 if module.check_mode:
1016 return True
1017 try:
1018 if rule_type == "in":
1019 changed = update_security_group_rule_descriptions_ingress(
1020 client, GroupId=group_id, IpPermissions=ip_permissions
1021 )
1022 if rule_type == "out":
1023 changed = update_security_group_rule_descriptions_egress(
1024 client, GroupId=group_id, IpPermissions=ip_permissions
1025 )
1026 except AnsibleEC2Error as e:
1027 module.fail_json_aws(e, msg=f"Unable to update rule description for group {group_id}")
1028 return changed
1029
1030
1031 def fix_port_and_protocol(permission):
1032 for key in ("FromPort", "ToPort"):
1033 if key in permission:
1034 if permission[key] is None:
1035 del permission[key]
1036 else:
1037 permission[key] = int(permission[key])
1038
1039 permission["IpProtocol"] = to_text(permission["IpProtocol"])
1040
1041 return permission
1042
1043
1044 def remove_old_permissions(
1045 client,
1046 module: AnsibleAWSModule,
1047 revoke_ingress: List[Dict[str, Any]],
1048 revoke_egress: List[Dict[str, Any]],
1049 group_id: str,
1050 ) -> bool:
1051 changed = False
1052 if revoke_ingress:
1053 changed |= revoke(client, module, revoke_ingress, group_id, "in")
1054 if revoke_egress:
1055 changed |= revoke(client, module, revoke_egress, group_id, "out")
1056 return changed
1057
1058
1059 def revoke(
1060 client, module: AnsibleAWSModule, ip_permissions: List[Dict[str, Any]], group_id: str, rule_type: str
1061 ) -> bool:
1062 if module.check_mode:
1063 return True
1064 try:
1065 if rule_type == "in":
1066 changed = revoke_security_group_ingress(client, GroupId=group_id, IpPermissions=ip_permissions)
1067 elif rule_type == "out":
1068 changed = revoke_security_group_egress(client, GroupId=group_id, IpPermissions=ip_permissions)
1069 except AnsibleEC2Error as e:
1070 rules = "ingress rules" if rule_type == "in" else "egress rules"
1071 module.fail_json_aws(e, f"Unable to revoke {rules}: {ip_permissions}")
1072 return changed
1073
1074
1075 def add_new_permissions(
1076 client, module: AnsibleAWSModule, new_ingress: List[Dict[str, Any]], new_egress: List[Dict[str, Any]], group_id: str
1077 ) -> bool:
1078 changed = False
1079 if new_ingress:
1080 changed |= authorize(client, module, new_ingress, group_id, "in")
1081 if new_egress:
1082 changed |= authorize(client, module, new_egress, group_id, "out")
1083 return changed
1084
1085
1086 def authorize(
1087 client, module: AnsibleAWSModule, ip_permissions: List[Dict[str, Any]], group_id: str, rule_type: str
1088 ) -> bool:
1089 if module.check_mode:
1090 return True
1091 try:
1092 if rule_type == "in":
1093 changed = authorize_security_group_ingress(client, GroupId=group_id, IpPermissions=ip_permissions)
1094 elif rule_type == "out":
1095 changed = authorize_security_group_egress(client, GroupId=group_id, IpPermissions=ip_permissions)
1096 except AnsibleEC2Error as e:
1097 rules = "ingress rules" if rule_type == "in" else "egress rules"
1098 module.fail_json_aws(e, f"Unable to authorize {rules}: {ip_permissions}")
1099 return changed
1100
1101
1102 def validate_ip(module, cidr_ip):
1103 split_addr = cidr_ip.split("/")
1104 if len(split_addr) != 2:
1105 return cidr_ip
1106
1107 try:
1108 ip = ip_network(to_text(cidr_ip))
1109 return str(ip)
1110 except ValueError:
1111 # If a host bit is incorrectly set, ip_network will throw an error at us,
1112 # we'll continue, convert the address to a CIDR AWS will accept, but issue a warning.
1113 pass
1114
1115 # Try evaluating as an IPv4 network, it'll throw a ValueError if it can't parse cidr_ip as an
1116 # IPv4 network
1117 try:
1118 ip = to_subnet(split_addr[0], split_addr[1])
1119 module.warn(
1120 f"One of your CIDR addresses ({cidr_ip}) has host bits set. To get rid of this warning, check the network"
1121 f" mask and make sure that only network bits are set: {ip}."
1122 )
1123 return ip
1124 except ValueError:
1125 pass
1126
1127 # Try again, evaluating as an IPv6 network.
1128 try:
1129 ip6 = to_ipv6_subnet(split_addr[0]) + "/" + split_addr[1]
1130 module.warn(
1131 f"One of your IPv6 CIDR addresses ({cidr_ip}) has host bits set. To get rid of this warning, check the"
1132 f" network mask and make sure that only network bits are set: {ip6}."
1133 )
1134 return ip6
1135 except ValueError:
1136 module.warn(f"Unable to parse CIDR ({cidr_ip}).")
1137 return cidr_ip
1138
1139
1140 def update_rule_descriptions(
1141 module, client, group_id, present_ingress, named_tuple_ingress_list, present_egress, named_tuple_egress_list
1142 ):
1143 changed = False
1144 ingress_needs_desc_update = []
1145 egress_needs_desc_update = []
1146
1147 for present_rule in present_egress:
1148 needs_update = [
1149 r
1150 for r in named_tuple_egress_list
1151 if rule_cmp(r, present_rule) and r.description != present_rule.description
1152 ]
1153 for r in needs_update:
1154 named_tuple_egress_list.remove(r)
1155 egress_needs_desc_update.extend(needs_update)
1156 for present_rule in present_ingress:
1157 needs_update = [
1158 r
1159 for r in named_tuple_ingress_list
1160 if rule_cmp(r, present_rule) and r.description != present_rule.description
1161 ]
1162 for r in needs_update:
1163 named_tuple_ingress_list.remove(r)
1164 ingress_needs_desc_update.extend(needs_update)
1165
1166 if ingress_needs_desc_update:
1167 changed |= update_rules_description(
1168 module, client, "in", group_id, rules_to_permissions(ingress_needs_desc_update)
1169 )
1170 if egress_needs_desc_update:
1171 changed |= update_rules_description(
1172 module, client, "out", group_id, rules_to_permissions(egress_needs_desc_update)
1173 )
1174 return changed
1175
1176
1177 def _create_security_group_with_wait(
1178 client, module: AnsibleAWSModule, name: str, description: str, vpc_id: Optional[str], tags: Dict[str, str]
1179 ) -> Dict[str, Any]:
1180 params = dict(GroupName=name, Description=description)
1181 if vpc_id:
1182 params["VpcId"] = vpc_id
1183 if tags:
1184 params["TagSpecifications"] = boto3_tag_specifications(tags, ["security-group"])
1185
1186 created_group = create_security_group(client, **params)
1187 wait_for_resource_state(client, module, "security_group_exists", GroupIds=[created_group["GroupId"]])
1188 return created_group
1189
1190
1191 def create_ec2_security_group(
1192 client, module: AnsibleAWSModule, name: str, description: str, vpc_id: Optional[str], tags: Optional[Dict[str, str]]
1193 ) -> Dict[str, Any]:
1194 params = dict(GroupName=name, Description=description)
1195 if vpc_id:
1196 params["VpcId"] = vpc_id
1197 if tags:
1198 params["TagSpecifications"] = boto3_tag_specifications(tags, ["security-group"])
1199 try:
1200 group = create_security_group(client, **params)
1201 except AnsibleEC2Error as e:
1202 module.fail_json_aws(e, msg="Unable to create security group")
1203 # When a group is created, an egress_rule ALLOW ALL
1204 # to 0.0.0.0/0 is added automatically but it's not
1205 # reflected in the object returned by the AWS API
1206 # call. We re-read the group for getting an updated object
1207 # amazon sometimes takes a couple seconds to update the security group so wait till it exists
1208 while True:
1209 sleep(3)
1210 groups = describe_security_groups(client, GroupIds=[group["GroupId"]])
1211 if groups[0].get("VpcId") and not groups[0].get("IpPermissionsEgress"):
1212 pass
1213 else:
1214 return groups[0]
1215
1216
1217 def wait_for_rule_propagation(module, client, group, desired_ingress, desired_egress, purge_ingress, purge_egress):
1218 group_id = group["GroupId"]
1219 tries = 6
1220
1221 def await_rules(group, desired_rules, purge, rule_key):
1222 for _i in range(tries):
1223 current_rules = set(sum([list(rule_from_group_permission(p)) for p in group[rule_key]], []))
1224 if purge and len(current_rules ^ set(desired_rules)) == 0:
1225 return group
1226 elif purge:
1227 conflicts = current_rules ^ set(desired_rules)
1228 # For cases where set comparison is equivalent, but invalid port/proto exist
1229 for a, b in itertools.combinations(conflicts, 2):
1230 if rule_cmp(a, b):
1231 conflicts.discard(a)
1232 conflicts.discard(b)
1233 if not len(conflicts):
1234 return group
1235 elif current_rules.issuperset(desired_rules) and not purge:
1236 return group
1237 sleep(10)
1238 group = describe_security_groups(client, GroupIds=[group_id])[0]
1239 module.warn(
1240 f"Ran out of time waiting for {group_id} {rule_key}. Current: {current_rules}, Desired: {desired_rules}"
1241 )
1242 return group
1243
1244 group = describe_security_groups(client, GroupIds=[group_id])[0]
1245 if "VpcId" in group and module.params.get("rules_egress") is not None:
1246 group = await_rules(group, desired_egress, purge_egress, "IpPermissionsEgress")
1247 return await_rules(group, desired_ingress, purge_ingress, "IpPermissions")
1248
1249
1250 def group_exists(
1251 client, module: AnsibleAWSModule, vpc_id: Optional[str], group_id: Optional[str], name: Optional[str]
1252 ) -> Tuple[Optional[Dict[str, Any]], Dict[str, Any]]:
1253 filters = dict()
1254 params = dict()
1255 if group_id:
1256 if isinstance(group_id, list):
1257 params["GroupIds"] = group_id
1258 else:
1259 params["GroupIds"] = [group_id]
1260 if name:
1261 # Add name to filters rather than params['GroupNames']
1262 # because params['GroupNames'] only checks the default vpc if no vpc is provided
1263 filters["group-name"] = name
1264 if vpc_id:
1265 filters["vpc-id"] = vpc_id
1266 # Don't filter by description to maintain backwards compatibility
1267 params["Filters"] = ansible_dict_to_boto3_filter_list(filters)
1268 try:
1269 security_groups = describe_security_groups(client, **params)
1270 all_groups = describe_security_groups(client)
1271 except AnsibleEC2Error as e:
1272 module.fail_json_aws_error(e)
1273
1274 if security_groups:
1275 groups = dict((group["GroupId"], group) for group in all_groups)
1276 groups.update(dict((group["GroupName"], group) for group in all_groups))
1277 if vpc_id:
1278 vpc_wins = dict(
1279 (group["GroupName"], group) for group in all_groups if group.get("VpcId") and group["VpcId"] == vpc_id
1280 )
1281 groups.update(vpc_wins)
1282 # maintain backwards compatibility by using the last matching group
1283 return security_groups[-1], groups
1284 return None, {}
1285
1286
1287 def get_diff_final_resource(client, module, security_group):
1288 def get_final_tags(security_group_tags, specified_tags, purge_tags):
1289 if specified_tags is None:
1290 return security_group_tags
1291 tags_need_modify, tags_to_delete = compare_aws_tags(security_group_tags, specified_tags, purge_tags)
1292 end_result_tags = dict((k, v) for k, v in specified_tags.items() if k not in tags_to_delete)
1293 end_result_tags.update(dict((k, v) for k, v in security_group_tags.items() if k not in tags_to_delete))
1294 end_result_tags.update(tags_need_modify)
1295 return end_result_tags
1296
1297 def get_final_rules(client, module, security_group_rules, specified_rules, purge_rules):
1298 if specified_rules is None:
1299 return security_group_rules
1300 if purge_rules:
1301 final_rules = []
1302 else:
1303 final_rules = list(security_group_rules)
1304 specified_rules = deepcopy(specified_rules)
1305 for rule in specified_rules:
1306 format_rule = {
1307 "from_port": None,
1308 "to_port": None,
1309 "ip_protocol": rule.get("proto"),
1310 "ip_ranges": [],
1311 "ipv6_ranges": [],
1312 "prefix_list_ids": [],
1313 "user_id_group_pairs": [],
1314 }
1315 if rule.get("proto") in ("all", "-1", -1):
1316 format_rule["ip_protocol"] = "-1"
1317 format_rule.pop("from_port")
1318 format_rule.pop("to_port")
1319 elif rule.get("ports"):
1320 if rule.get("ports") and (isinstance(rule["ports"], str) or isinstance(rule["ports"], int)):
1321 rule["ports"] = [rule["ports"]]
1322 for port in rule.get("ports"):
1323 if isinstance(port, str) and "-" in port:
1324 format_rule["from_port"], format_rule["to_port"] = port.split("-")
1325 else:
1326 format_rule["from_port"] = format_rule["to_port"] = port
1327 elif rule.get("from_port") or rule.get("to_port"):
1328 format_rule["from_port"] = rule.get("from_port", rule.get("to_port"))
1329 format_rule["to_port"] = rule.get("to_port", rule.get("from_port"))
1330 for source_type in ("cidr_ip", "cidr_ipv6"):
1331 if rule.get(source_type):
1332 rule_key = {
1333 "cidr_ip": "ip_ranges",
1334 "cidr_ipv6": "ipv6_ranges",
1335 }.get(source_type)
1336 if not isinstance(rule[source_type], list):
1337 rule[source_type] = [rule[source_type]]
1338 if rule.get("rule_desc"):
1339 format_rule[rule_key] = [
1340 {source_type: target, "description": rule["rule_desc"]} for target in rule[source_type]
1341 ]
1342 else:
1343 format_rule[rule_key] = [{source_type: target} for target in rule[source_type]]
1344 # Prefix list (ansible option is 'ip_prefix')
1345 if rule.get("ip_prefix"):
1346 ip_prefix = rule["ip_prefix"]
1347 if not isinstance(ip_prefix, list):
1348 ip_prefix = [ip_prefix]
1349 if rule.get("rule_desc"):
1350 format_rule["prefix_list_ids"] = [
1351 {"prefix_list_id": i, "description": rule["rule_desc"]} for i in ip_prefix
1352 ]
1353 else:
1354 format_rule["prefix_list_ids"] = [{"prefix_list_id": i} for i in ip_prefix]
1355 if rule.get("group_id") or rule.get("group_name"):
1356 # XXX bug - doesn't cope with a list of ids/names
1357 rule_sg = group_exists(
1358 client, module, module.params["vpc_id"], rule.get("group_id"), rule.get("group_name")
1359 )[0]
1360 if rule_sg is None:
1361 # --diff during --check
1362 format_rule["user_id_group_pairs"] = [
1363 {
1364 "group_id": rule.get("group_id"),
1365 "group_name": rule.get("group_name"),
1366 "peering_status": None,
1367 "user_id": security_group.get("owner_id", current_account_id),
1368 "vpc_id": module.params["vpc_id"],
1369 "vpc_peering_connection_id": None,
1370 }
1371 ]
1372 else:
1373 rule_sg = camel_dict_to_snake_dict(rule_sg)
1374 format_rule["user_id_group_pairs"] = [
1375 {
1376 "description": rule_sg.get("description", rule_sg.get("group_desc")),
1377 "group_id": rule_sg.get("group_id", rule.get("group_id")),
1378 "group_name": rule_sg.get("group_name", rule.get("group_name")),
1379 "peering_status": rule_sg.get("peering_status"),
1380 "user_id": rule_sg.get("user_id", security_group.get("owner_id", current_account_id)),
1381 "vpc_id": rule_sg.get("vpc_id", module.params["vpc_id"]),
1382 "vpc_peering_connection_id": rule_sg.get("vpc_peering_connection_id"),
1383 }
1384 ]
1385 for k, v in list(format_rule["user_id_group_pairs"][0].items()):
1386 if v is None:
1387 format_rule["user_id_group_pairs"][0].pop(k)
1388 final_rules.append(format_rule)
1389 return final_rules
1390
1391 security_group_ingress = security_group.get("ip_permissions", [])
1392 specified_ingress = module.params["rules"]
1393 purge_ingress = module.params["purge_rules"]
1394 security_group_egress = security_group.get("ip_permissions_egress", [])
1395 specified_egress = module.params["rules_egress"]
1396 purge_egress = module.params["purge_rules_egress"]
1397 return {
1398 "description": module.params["description"],
1399 "group_id": security_group.get("group_id", "sg-xxxxxxxx"),
1400 "group_name": security_group.get("group_name", module.params["name"]),
1401 "ip_permissions": get_final_rules(client, module, security_group_ingress, specified_ingress, purge_ingress),
1402 "ip_permissions_egress": get_final_rules(client, module, security_group_egress, specified_egress, purge_egress),
1403 "owner_id": security_group.get("owner_id", current_account_id),
1404 "tags": get_final_tags(security_group.get("tags", {}), module.params["tags"], module.params["purge_tags"]),
1405 "vpc_id": security_group.get("vpc_id", module.params["vpc_id"]),
1406 }
1407
1408
1409 def get_rule_sort_key(dicts):
1410 if dicts.get("cidr_ip"):
1411 return str(dicts.get("cidr_ip"))
1412 if dicts.get("cidr_ipv6"):
1413 return str(dicts.get("cidr_ipv6"))
1414 if dicts.get("prefix_list_id"):
1415 return str(dicts.get("prefix_list_id"))
1416 if dicts.get("group_id"):
1417 return str(dicts.get("group_id"))
1418 return None
1419
1420
1421 def get_ip_permissions_sort_key(rule):
1422 RULE_KEYS_ALL = {"ip_ranges", "ipv6_ranges", "prefix_list_ids", "user_id_group_pairs"}
1423 # Ensure content of these keys is sorted
1424 for rule_key in RULE_KEYS_ALL:
1425 if rule.get(rule_key):
1426 rule.get(rule_key).sort(key=get_rule_sort_key)
1427
1428 # Returns the first value plus a prefix so the types get clustered together when sorted
1429 if rule.get("ip_ranges"):
1430 value = str(rule.get("ip_ranges")[0]["cidr_ip"])
1431 return f"ipv4:{value}"
1432 if rule.get("ipv6_ranges"):
1433 value = str(rule.get("ipv6_ranges")[0]["cidr_ipv6"])
1434 return f"ipv6:{value}"
1435 if rule.get("prefix_list_ids"):
1436 value = str(rule.get("prefix_list_ids")[0]["prefix_list_id"])
1437 return f"pl:{value}"
1438 if rule.get("user_id_group_pairs"):
1439 value = str(rule.get("user_id_group_pairs")[0].get("group_id", ""))
1440 return f"ugid:{value}"
1441 return None
1442
1443
1444 def sort_security_group(security_group):
1445 if not security_group:
1446 return security_group
1447
1448 if security_group.get("ip_permissions"):
1449 security_group["ip_permissions"].sort(key=get_ip_permissions_sort_key)
1450 if security_group.get("ip_permissions_egress"):
1451 security_group["ip_permissions_egress"].sort(key=get_ip_permissions_sort_key)
1452
1453 return security_group
1454
1455
1456 def validate_rules(module, rules):
1457 if not rules:
1458 return
1459 try:
1460 for rule in rules:
1461 validate_rule(rule)
1462 except SecurityGroupError as e:
1463 e.fail(module)
1464
1465
1466 def ensure_absent(client, group: Optional[Dict[str, Any]], check_mode: bool) -> bool:
1467 if not group:
1468 return False
1469 if check_mode:
1470 return True
1471
1472 try:
1473 return delete_security_group(client, group_id=group["GroupId"])
1474 except AnsibleEC2Error as e:
1475 raise SecurityGroupError(f"Unable to delete security group '{group}'", e=e)
1476
1477
1478 def ensure_present(
1479 module: AnsibleAWSModule, client, group: Optional[Dict[str, Any]], groups: Dict[str, Any]
1480 ) -> Tuple[bool, Dict[str, Any]]:
1481 name = module.params["name"]
1482 description = module.params["description"]
1483 vpc_id = module.params["vpc_id"]
1484 rules = deepcopy(module.params["rules"])
1485 rules_egress = deepcopy(module.params["rules_egress"])
1486 validate_rules(module, rules)
1487 validate_rules(module, rules_egress)
1488 rules = deduplicate_rules_args(expand_rules(rules))
1489 rules_egress = deduplicate_rules_args(expand_rules(rules_egress))
1490 purge_rules = module.params["purge_rules"]
1491 purge_rules_egress = module.params["purge_rules_egress"]
1492 tags = module.params["tags"]
1493 purge_tags = module.params["purge_tags"]
1494
1495 changed = False
1496 group_created_new = False
1497
1498 if not group:
1499 changed = True
1500 # Short circuit things if we're in check_mode
1501 if module.check_mode:
1502 return changed, {"group_id": None}
1503
1504 group = create_ec2_security_group(client, module, name, description, vpc_id, tags)
1505 group_created_new = True
1506
1507 else:
1508 # Description is immutable
1509 if group["Description"] != description:
1510 module.warn(
1511 "Group description does not match existing group. Descriptions cannot be changed without deleting "
1512 "and re-creating the security group. Try using state=absent to delete, then rerunning this task."
1513 )
1514
1515 changed |= ensure_ec2_tags(client, module, group["GroupId"], tags=tags, purge_tags=purge_tags)
1516
1517 named_tuple_ingress_list: List[Rule] = []
1518 named_tuple_egress_list: List[Rule] = []
1519 current_ingress = sum([list(rule_from_group_permission(p)) for p in group["IpPermissions"]], [])
1520 current_egress = sum([list(rule_from_group_permission(p)) for p in group["IpPermissionsEgress"]], [])
1521
1522 for new_rules, named_tuple_rule_list in [
1523 (rules, named_tuple_ingress_list),
1524 (rules_egress, named_tuple_egress_list),
1525 ]:
1526 if new_rules is None:
1527 continue
1528 for rule in new_rules:
1529 target_type, target, target_group_created = get_target_from_rule(
1530 module, client, rule, name, group, groups, vpc_id, tags
1531 )
1532 changed |= target_group_created
1533
1534 if rule.get("proto") in ("all", "-1", -1):
1535 rule["proto"] = "-1"
1536 rule["from_port"] = None
1537 rule["to_port"] = None
1538
1539 try:
1540 int(rule.get("proto"))
1541 rule["proto"] = to_text(rule.get("proto"))
1542 rule["from_port"] = None
1543 rule["to_port"] = None
1544 except ValueError:
1545 # rule does not use numeric protocol spec
1546 pass
1547 named_tuple_rule_list.append(
1548 Rule(
1549 port_range=(rule["from_port"], rule["to_port"]),
1550 protocol=to_text(rule.get("proto")),
1551 target=target,
1552 target_type=target_type,
1553 description=rule.get("rule_desc"),
1554 )
1555 )
1556
1557 # List comprehensions for rules to add, rules to modify, and rule ids to determine purging
1558 new_ingress_permissions = [to_permission(r) for r in (set(named_tuple_ingress_list) - set(current_ingress))]
1559 new_egress_permissions = [to_permission(r) for r in (set(named_tuple_egress_list) - set(current_egress))]
1560
1561 if module.params.get("rules_egress") is None and "VpcId" in group:
1562 # when no egress rules are specified and we're in a VPC,
1563 # we add in a default allow all out rule, which was the
1564 # default behavior before egress rules were added
1565 rule = Rule((None, None), "-1", "0.0.0.0/0", "ipv4", None)
1566 if rule in current_egress:
1567 named_tuple_egress_list.append(rule)
1568 if rule not in current_egress:
1569 current_egress.append(rule)
1570
1571 # List comprehensions for rules to add, rules to modify, and rule ids to determine purging
1572 present_ingress = list(set(named_tuple_ingress_list).union(set(current_ingress)))
1573 present_egress = list(set(named_tuple_egress_list).union(set(current_egress)))
1574
1575 if purge_rules:
1576 revoke_ingress = []
1577 for p in present_ingress:
1578 if not any(rule_cmp(p, b) for b in named_tuple_ingress_list):
1579 revoke_ingress.append(to_permission(p))
1580 else:
1581 revoke_ingress = []
1582
1583 if purge_rules_egress and module.params.get("rules_egress") is not None:
1584 revoke_egress = []
1585 for p in present_egress:
1586 if not any(rule_cmp(p, b) for b in named_tuple_egress_list):
1587 revoke_egress.append(to_permission(p))
1588 else:
1589 revoke_egress = []
1590
1591 # named_tuple_ingress_list and named_tuple_egress_list get updated by
1592 # method update_rule_descriptions, deep copy these two lists to new
1593 # variables for the record of the 'desired' ingress and egress sg permissions
1594 desired_ingress = deepcopy(named_tuple_ingress_list)
1595 desired_egress = deepcopy(named_tuple_egress_list)
1596
1597 changed |= update_rule_descriptions(
1598 module,
1599 client,
1600 group["GroupId"],
1601 present_ingress,
1602 named_tuple_ingress_list,
1603 present_egress,
1604 named_tuple_egress_list,
1605 )
1606
1607 # Revoke old rules
1608 changed |= remove_old_permissions(client, module, revoke_ingress, revoke_egress, group["GroupId"])
1609
1610 new_ingress_permissions = [to_permission(r) for r in (set(named_tuple_ingress_list) - set(current_ingress))]
1611 new_ingress_permissions = rules_to_permissions(set(named_tuple_ingress_list) - set(current_ingress))
1612 new_egress_permissions = rules_to_permissions(set(named_tuple_egress_list) - set(current_egress))
1613 # Authorize new rules
1614 changed |= add_new_permissions(client, module, new_ingress_permissions, new_egress_permissions, group["GroupId"])
1615
1616 if group_created_new and module.params.get("rules") is None and module.params.get("rules_egress") is None:
1617 # A new group with no rules provided is already being awaited.
1618 # When it is created we wait for the default egress rule to be added by AWS
1619 security_group = describe_security_groups(client, GroupIds=[group["GroupId"]])[0]
1620 elif changed and not module.check_mode:
1621 # keep pulling until current security group rules match the desired ingress and egress rules
1622 security_group = wait_for_rule_propagation(
1623 module, client, group, desired_ingress, desired_egress, purge_rules, purge_rules_egress
1624 )
1625 else:
1626 security_group = describe_security_groups(client, GroupIds=[group["GroupId"]])[0]
1627 security_group = camel_dict_to_snake_dict(security_group, ignore_list=["Tags"])
1628 security_group["tags"] = boto3_tag_list_to_ansible_dict(security_group.get("tags", []))
1629
1630 return changed, security_group
1631
1632
1633 def main():
1634 rule_spec = dict(
1635 rule_desc=dict(type="str"),
1636 cidr_ip=dict(type="list", elements="str"),
1637 cidr_ipv6=dict(type="list", elements="str"),
1638 ip_prefix=dict(type="list", elements="str"),
1639 group_id=dict(type="list", elements="str"),
1640 group_name=dict(type="list", elements="str"),
1641 group_desc=dict(type="str"),
1642 proto=dict(type="str", default="tcp"),
1643 ports=dict(type="list", elements="str"),
1644 from_port=dict(type="int"),
1645 to_port=dict(type="int"),
1646 icmp_type=dict(type="int"),
1647 icmp_code=dict(type="int"),
1648 )
1649 rule_requirements = dict(
1650 mutually_exclusive=(
1651 # PORTS / ICMP_TYPE + ICMP_CODE / TO_PORT + FROM_PORT
1652 (
1653 "ports",
1654 "to_port",
1655 ),
1656 (
1657 "ports",
1658 "from_port",
1659 ),
1660 (
1661 "ports",
1662 "icmp_type",
1663 ),
1664 (
1665 "ports",
1666 "icmp_code",
1667 ),
1668 (
1669 "icmp_type",
1670 "to_port",
1671 ),
1672 (
1673 "icmp_code",
1674 "to_port",
1675 ),
1676 (
1677 "icmp_type",
1678 "from_port",
1679 ),
1680 (
1681 "icmp_code",
1682 "from_port",
1683 ),
1684 ),
1685 required_one_of=(
1686 # A target must be specified
1687 (
1688 "group_id",
1689 "group_name",
1690 "cidr_ip",
1691 "cidr_ipv6",
1692 "ip_prefix",
1693 ),
1694 ),
1695 required_by=dict(
1696 # If you specify an ICMP code, you must specify the ICMP type
1697 icmp_code=("icmp_type",),
1698 ),
1699 )
1700
1701 argument_spec = dict(
1702 name=dict(),
1703 group_id=dict(),
1704 description=dict(),
1705 vpc_id=dict(),
1706 rules=dict(type="list", elements="dict", options=rule_spec, **rule_requirements),
1707 rules_egress=dict(
1708 type="list", elements="dict", aliases=["egress_rules"], options=rule_spec, **rule_requirements
1709 ),
1710 state=dict(default="present", type="str", choices=["present", "absent"]),
1711 purge_rules=dict(default=True, required=False, type="bool"),
1712 purge_rules_egress=dict(default=True, required=False, type="bool", aliases=["purge_egress_rules"]),
1713 tags=dict(required=False, type="dict", aliases=["resource_tags"]),
1714 purge_tags=dict(default=True, required=False, type="bool"),
1715 )
1716 module = AnsibleAWSModule(
1717 argument_spec=argument_spec,
1718 supports_check_mode=True,
1719 required_one_of=[["name", "group_id"]],
1720 required_if=[["state", "present", ["name", "description"]]],
1721 )
1722
1723 name = module.params["name"]
1724 group_id = module.params["group_id"]
1725 vpc_id = module.params["vpc_id"]
1726 state = module.params.get("state")
1727
1728 client = module.client("ec2")
1729
1730 group, groups = group_exists(client, module, vpc_id, group_id, name)
1731
1732 global current_account_id
1733 current_account_id = get_aws_account_id(module)
1734
1735 before = {}
1736 after = {}
1737
1738 if group:
1739 before = camel_dict_to_snake_dict(group, ignore_list=["Tags"])
1740 before["tags"] = boto3_tag_list_to_ansible_dict(before.get("tags", []))
1741
1742 security_group = {"group_id": None}
1743 try:
1744 # Ensure requested group is absent
1745 if state == "absent":
1746 changed = ensure_absent(client, group, module.check_mode)
1747 # Ensure requested group is present
1748 elif state == "present":
1749 (changed, security_group) = ensure_present(module, client, group, groups)
1750 except SecurityGroupError as e:
1751 e.fail(module)
1752
1753 if module._diff:
1754 if state == "present":
1755 after = get_diff_final_resource(client, module, security_group)
1756
1757 # Order final rules consistently
1758 before = sort_security_group(before)
1759 after = sort_security_group(after)
1760
1761 security_group["diff"] = [{"before": before, "after": after}]
1762
1763 module.exit_json(changed=changed, **security_group)
1764
1765
1766 if __name__ == "__main__":
1767 main()