有什么方法可以从实例中获取平台和操作系统



我正在尝试从我的AWS EC2实例中获取一些信息。我想知道是否有一种方法来吸引以下信息:

| Platform  | Version        |
|-----------|---------------:|
| CentOS    |  6.0 or 7.0    |
| Ubuntu    | 10.04 or 12.04 |
| Windows   |                |

我想知道使用SDK是否可以。我尝试了Python SDK boto3,但没有结果。

除非将这些信息存储为tags,否则SDK或CLI不可能。AWS SDK和CLI可以帮助您获取在管理程序级别上可用的信息。但是您要问的内容在VM内而不是在Hyprovisor中。

虽然以下CLI命令可以为您提供一些帮助,但是不能保证您将在所有情况下获得平台信息。

aws ec2 describe-instances --query 'Reservations[*].Instances[*].[InstanceId,Platform]' --output text
i-07843115f653771c8 windows
i-e34364c87d4cebd12 None
i-0493b6a67b31df018 None

我们可以按照@hellov已经回答的平台,但是没有手段直接获得操作系统。但是我们可以使用图像ID使用一些字符串操作来确定OS名称。使用以下命令,我们可以获取图像名称,其中我们在某种程度上具有操作系统名称。

AWS EC2描述图像 - 图像IDS $(AWS EC2 dictif-Instances -query'poservations [*]。实例[*]。imageId' - 输出文本) -  Query'image'images [*]。名称'命令的输出如下:[    " RHEL-7.6_HVM_GA-GA-20190128-X86_64-0-HOURLY2-GP2",    " Centos_7.5_private",    " AMZN2-AMI-HVM-2.0.0.20191024.3-X86_64-GP2",    " AMZN-AMI-HVM-2018.03.03.0.20190826-X86_64-GP2",    " Windows_server-2016-英语-Full-Base-2019.11.13",    " Windows_server-2019-英语 - 富于2019年10月109日"这是给出的

此外,如果您在实例上安装了SSM代理,则可以运行以下命令以获取确切的操作系统名称。

AWS ssm descrip-instance信息 -  Query'instanceInformationList [*]。种类该命令的输出如下:I-xxxxxxxxxxxxx Linux Amazon Linux AMII-XXXXXXXXXXXXX Linux Centos LinuxI-XXXXXXXXXXXX Linux Amazon Linuxi-xxxxxxxxxxxxxx Windows Microsoft Windows Server 2016 Datacenter

希望这会有所帮助!

如果您使用的是boto3 sdk,则文档指出,除非 Platform='Windows',否则Reservations[].Instances[].Platform将不存在。此函数将用InstanceId构建您的键和Platform作为值:

from boto3 import client
from botocore.exceptions import ClientError
def get_instance_platform(instance_ids:list) -> dict:
    ec2 = client('ec2')
    paginator = ec2.get_paginator('describe_instances')
    try:
        # paginator in case you have a lot of instances in account
        pages = paginator.paginate(
            InstanceIds=instance_ids
        )
        instances_with_platform = {}
        for page in pages:
            for reservation in page['Reservations']:
                for instance in reservation['Instances']:
                    instances_with_platform[instance['InstanceId'] = instance.get('Platform','Linux/UNIX')
    except ClientError as err:
        print('BIG OOF')
        # handle this in your own way, I just raise original exception
        raise err
    return instances_with_platform

我决定使用内置的Paginator,这意味着即使帐户中有很多实例(> 50)。

最新更新