def delete_dependencies()

in functions/source/CleanupSecurityGroupDependencies/lambda_function.py [0:0]


def delete_dependencies(sg_id, c):
    complete = True
    filters = [{'Name': 'ip-permission.group-id', 'Values': [sg_id]}]
    for sg in c.describe_security_groups(Filters=filters)['SecurityGroups']:
        for p in sg['IpPermissions']:
            if 'UserIdGroupPairs' in p.keys():
                if sg_id in [x['GroupId'] for x in p['UserIdGroupPairs']]:
                    try:
                        c.revoke_security_group_ingress(GroupId=sg['GroupId'], IpPermissions=[p])
                    except Exception as e:
                        complete = False
                        logger.error("ERROR: %s %s" % (sg['GroupId'], str(e)))
    filters = [{'Name': 'egress.ip-permission.group-id', 'Values': [sg_id]}]
    for sg in c.describe_security_groups(Filters=filters)['SecurityGroups']:
        for p in sg['IpPermissionsEgress']:
            if 'UserIdGroupPairs' in p.keys():
                if sg_id in [x['GroupId'] for x in p['UserIdGroupPairs']]:
                    try:
                        c.revoke_security_group_egress(GroupId=sg['GroupId'], IpPermissions=[p])
                    except Exception as e:
                        complete = False
                        logger.error("ERROR: %s %s" % (sg['GroupId'], str(e)))
    filters = [{'Name': 'group-id', 'Values': [sg_id]}]
    for eni in c.describe_network_interfaces(Filters=filters)['NetworkInterfaces']:
        try:
            attachment_id = get_attachment_id_for_eni(eni)
            if attachment_id:
                c.detach_network_interface(AttachmentId=attachment_id, Force=True)
                sleep(5)
            c.delete_network_interface(NetworkInterfaceId=eni['NetworkInterfaceId'])
        except Exception as e:
            complete = False
            logger.error("ERROR: %s %s" % (eni['NetworkInterfaceId'], str(e)))
    return complete