From 6d41ad72e09b49f61e54d47880f8a65026e7c0e4 Mon Sep 17 00:00:00 2001 From: Bert Blommers Date: Tue, 24 Jan 2023 22:35:55 -0100 Subject: [PATCH] EC2: Simplify describe_sg_rules() logic (#5875) --- moto/ec2/models/security_groups.py | 17 +++++------------ moto/ec2/responses/security_groups.py | 26 ++++++++++++++------------ 2 files changed, 19 insertions(+), 24 deletions(-) diff --git a/moto/ec2/models/security_groups.py b/moto/ec2/models/security_groups.py index 31bee8255..c0ba1470d 100644 --- a/moto/ec2/models/security_groups.py +++ b/moto/ec2/models/security_groups.py @@ -521,18 +521,11 @@ class SecurityGroupBackend: return matches def describe_security_group_rules(self, group_ids=None, filters=None): - matches = itertools.chain(*[x.copy().values() for x in self.groups.values()]) - if group_ids: - matches = [grp for grp in matches if grp.id in group_ids] - if len(group_ids) > len(matches): - unknown_ids = set(group_ids) - set(matches) - raise InvalidSecurityGroupNotFoundError(unknown_ids) - if filters: - matches = [grp for grp in matches if grp.matches_filters(filters)] - if not matches: - raise InvalidSecurityGroupNotFoundError( - "No security groups found matching the filters provided." - ) + matches = self.describe_security_groups(group_ids=group_ids, filters=filters) + if not matches: + raise InvalidSecurityGroupNotFoundError( + "No security groups found matching the filters provided." + ) rules = [] for group in matches: rules.extend(group.ingress_rules) diff --git a/moto/ec2/responses/security_groups.py b/moto/ec2/responses/security_groups.py index 236e270ef..a1b0bdb23 100644 --- a/moto/ec2/responses/security_groups.py +++ b/moto/ec2/responses/security_groups.py @@ -251,20 +251,22 @@ DESCRIBE_SECURITY_GROUP_RULES_RESPONSE = """ {{ request_id }} - {% for rule in rules %} + {% for rule in rules %} {% if rule.from_port is not none %} - {{ rule.from_port }} - {% endif %} - {% if rule.to_port is not none %} - {{ rule.to_port }} - {% endif %} - {{ rule.ip_ranges[0]['CidrIp'] }} - {{ rule.ip_protocol }} - {{ rule.owner_id }} - true - {{ rule.id }} - + {{ rule.from_port }} + {% endif %} + {% if rule.to_port is not none %} + {{ rule.to_port }} + {% endif %} + {% if rule.ip_ranges %} + {{ rule.ip_ranges[0]['CidrIp'] }} + {% endif %} + {{ rule.ip_protocol }} + {{ rule.owner_id }} + true + {{ rule.id }} + {% endfor %} """