def security_group(function, credentials, unused_resource_count, region_list):
    print('Scanning Security Groups')
    sg_count = 0
    unused_sg_detail = []
    for region in region_list:
        try:
            ec2 = boto3.resource('ec2', aws_access_key_id=credentials['access_key'], aws_secret_access_key=credentials['secret_key'], region_name=region)
            sgs = list(ec2.security_groups.all())
            network_interfaces = list(ec2.network_interfaces.all())
            all_sgs = set([sg.group_id for sg in sgs])
            all_inst_sgs = set([sg['GroupId'] for ni in network_interfaces for sg in ni.groups])
            unused_sgs = (all_sgs - all_inst_sgs)
            for sgid in unused_sgs:
                unused_sg_detail.append({'ResourceType': 'AWS::EC2::SecurityGroup', 'ResourceId': sgid, 'Region': region})
            sg_count += len(unused_sgs)
        except:
            pass
    if sg_count:
        unused_sg_detail = json.loads(json.dumps(unused_sg_detail))
        f = csv.writer(open('./aws_logs/security_group.csv', 'w', newline=''))
        f.writerow(['ResourceType', 'ResourceId', 'Region'])
        for unused_sg_detail in unused_sg_detail:
            f.writerow([unused_sg_detail['ResourceType'], unused_sg_detail['ResourceId'], unused_sg_detail['Region']])
    unused_resource_count[function] = sg_count
def security_group(function, credentials, unused_resource_count, region_list):
    print('Scanning Security Groups')
    sg_count = 0
    unused_sg_detail = []
    for region in region_list:
        try:
            ec2 = boto3.resource('ec2', aws_access_key_id=credentials['access_key'], aws_secret_access_key=credentials['secret_key'], region_name=region)
            sgs = list(ec2.security_groups.all())
            network_interfaces = list(ec2.network_interfaces.all())
            all_sgs = set([sg.group_id for sg in sgs])
            all_inst_sgs = set([sg['GroupId'] for ni in network_interfaces for sg in ni.groups])
            unused_sgs = (all_sgs - all_inst_sgs)
            for sgid in unused_sgs:
                unused_sg_detail.append({'ResourceType': 'AWS::EC2::SecurityGroup', 'ResourceId': sgid, 'Region': region})
            sg_count += len(unused_sgs)
        except:
            pass
    if sg_count:
        unused_sg_detail = json.loads(json.dumps(unused_sg_detail))
        f = csv.writer(open('./aws_logs/security_group.csv', 'w', newline=))
        f.writerow(['ResourceType', 'ResourceId', 'Region'])
        for unused_sg_detail in unused_sg_detail:
            f.writerow([unused_sg_detail['ResourceType'], unused_sg_detail['ResourceId'], unused_sg_detail['Region']])
    unused_resource_count[function] = sg_count