如何通过 CLI 获取基于 Nitro 系统的 EC2 实例类型列表?

How to get the list of Nitro system based EC2 instance type by CLI?

我知道 this page 列出了基于 Nitro 系统的实例类型,但我想通过 CLI 以动态方式了解该列表。 (例如,使用 aws ec2 describe-instances)。除了解析静态页面之外,是否有可能获得基于 Nitro 的实例类型?如果是这样,你能告诉我怎么做吗?

您必须编写一些额外的代码才能获取该信息。 aws ec2 describe-instances会给你InstanceType属性。您应该使用编程语言来解析 JSON,提取 InstanceType,然后像这样调用 describe-instanceshttps://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instance-types.html?highlight=nitro

从您返回的 JSON 中提取 hypervisor。如果实例是 Nitro,那会给你 Nitro。

这是一个可能有效的 Python 代码。我还没有完全测试它,但你可以调整它以获得你想要的结果。

"""List all EC2 instances"""
import boto3

def ec2_connection():
    """Connect to AWS using API"""

    region = 'us-east-2'

    aws_key = 'xxx'
    aws_secret = 'xxx'

    session = boto3.Session(
        aws_access_key_id = aws_key,
        aws_secret_access_key = aws_secret
    )

    ec2 = session.client('ec2', region_name = region)

    return ec2


def get_reservations(ec2):
    """Get a list of instances as a dictionary"""

    response = ec2.describe_instances()

    return response['Reservations']


def process_instances(reservations, ec2):
    """Print a colorful list of IPs and instances"""

    if len(reservations) == 0:
        print('No instance found. Quitting')
        return

    for reservation in reservations:
        for instance in reservation['Instances']:

            # get friendly name of the server
            # only try this for mysql1.local server
            friendly_name = get_friendly_name(instance)
            if friendly_name.lower() != 'mysql1.local':
                continue

            # get the hypervisor based on the instance type
            instance_type = get_instance_info(instance['InstanceType'], ec2)

            # print findings
            print(f'{friendly_name} // {instance["InstanceType"]} is {instance_type}')
            break


def get_instance_info(instance_type, ec2):
    """Get hypervisor from the instance type"""

    response = ec2.describe_instance_types(
        InstanceTypes=[instance_type]
    )

    return response['InstanceTypes'][0]['Hypervisor']


def get_friendly_name(instance):
    """Get friendly name of the instance"""

    tags = instance['Tags']
    for tag in tags:
        if tag['Key'] == 'Name':
            return tag['Value']

    return 'Unknown'


def run():
    """Main method to call"""

    ec2 = ec2_connection()
    reservations = get_reservations(ec2)
    process_instances(reservations, ec2)


if __name__ == '__main__':

    run()
    print('Done')