From f65e0564bd8df662bbcdfee5dfa26268c9c9e9ec Mon Sep 17 00:00:00 2001 From: lavenderguitar Date: Tue, 25 Apr 2023 15:06:29 -0400 Subject: [PATCH] Copy SGS - Update to handle pre-existing rules. --- copy_security_groups.py | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/copy_security_groups.py b/copy_security_groups.py index 035fe7d..5fabded 100644 --- a/copy_security_groups.py +++ b/copy_security_groups.py @@ -28,10 +28,23 @@ new_security_group = destination_ec2.create_security_group(GroupName=response['S # Add the inbound and outbound rules from the source security group to the new security group for ip_permission in response['SecurityGroups'][0]['IpPermissions']: - destination_ec2.authorize_security_group_ingress(GroupId=new_security_group['GroupId'], - IpPermissions=[ip_permission]) + try: + destination_ec2.authorize_security_group_ingress(GroupId=new_security_group['GroupId'], + IpPermissions=[ip_permission]) + except destination_ec2.exceptions.ClientError as e: + if e.response['Error']['Code'] == 'InvalidPermission.Duplicate': + print(f"Rule already exists in new security group: {ip_permission}") + else: + raise e + for ip_permission in response['SecurityGroups'][0]['IpPermissionsEgress']: - destination_ec2.authorize_security_group_egress(GroupId=new_security_group['GroupId'], - IpPermissions=[ip_permission]) + try: + destination_ec2.authorize_security_group_egress(GroupId=new_security_group['GroupId'], + IpPermissions=[ip_permission]) + except destination_ec2.exceptions.ClientError as e: + if e.response['Error']['Code'] == 'InvalidPermission.Duplicate': + print(f"Rule already exists in new security group: {ip_permission}") + else: + raise e print(f"Security group copied successfully! New security group ID: {new_security_group['GroupId']}")