def get_all_ec2()

in Back-End/lambdas/receive_sqs_message.py [0:0]


def get_all_ec2(account_number, region, cross_account_role):

    # Init
    var_list = []

    # Use boto3 on source account
    client_ec2 = create_boto_client(
        account_number, region, 'ec2', cross_account_role)

    # Page all ec2
    paginator = client_ec2.get_paginator('describe_instances')

    for page in paginator.paginate():
        for i in page['Reservations']:

            # Check for IAM Role
            checkIAMrole = i['Instances'][0].get('IamInstanceProfile', ' ')

            # Convert from string to dict if not empty
            if checkIAMrole != ' ':
                python_dict = literal_eval(f'{checkIAMrole}')
                full_role_name = python_dict['Arn']

                # clean role name out of arn
                iam_role = full_role_name.split(':')[5].split('/')[1]
            else:
                iam_role = ' '

            # Get vCPU count
            vcpu_core = i['Instances'][0]['CpuOptions']['CoreCount']
            vcpu_thread = i['Instances'][0]['CpuOptions']['ThreadsPerCore']

            # Cores x thread = vCPU count
            vCPU = int(vcpu_core) * int(vcpu_thread)

            # Turn Tags into Strings for Table format on front end
            ec2_tags = i['Instances'][0].get('Tags', 'No Tags Exist')

            var_list.append(
                {
                    'EntryType': 'ec2',
                    'Id': str(i['Instances'][0]['InstanceId']),
                    'State': str(i['Instances'][0]['State']['Name']),
                    'AccountNumber': str(account_number),
                    'Region': str(region),
                    'vCPU': int(vCPU),
                    'KeyName': str(i['Instances'][0].get('KeyName', ' ')),
                    'RoleName': str(iam_role),
                    'Link': str(f'https://{region}.console.aws.amazon.com/ec2/v2/home?region={region}#Instances:sort=instanceId'),
                    'PrivateIpAddress': str(i['Instances'][0].get('PrivateIpAddress', ' ')),
                    'PublicIpAddress': str(i['Instances'][0].get('PublicIpAddress', ' ')),
                    'InstancePlatform': str(i['Instances'][0].get('Platform', 'Linux/UNIX')),
                    'InstanceType': str(i['Instances'][0]['InstanceType']),
                    'Tags': str(ec2_tags)
                })

    return var_list