Boto3 获取 EC2 CPUOptions 时出现问题

0

【以下的问题经过翻译处理】 我在获取EC2实例的某些值方面遇到了问题。例如,要获取CPU选项。 ''' import json import boto3

def lambda_handler(event, context): s_region = "us-east-1" instance_ids = [] ec2 = boto3.client('ec2', region_name=s_region) print(boto3.version) print(" ") response = ec2.describe_instances() instances_full_details = response['Reservations'] for instance_detail in instances_full_details: group_instances = instance_detail['Instances'] for instance in group_instances: instance_id = instance['InstanceId'] print("ID: " + instance_id) s_temp = instance.get("InstanceType") print('InstanceType=' + s_temp) temp = instance.get("cpu_options") s_temp = str(temp.keys()) ''' 这个给了我一个错误。 "'NoneType' object has no attribute 'keys'"

基本上,我想获取所有EC2实例属性。一些工作正常,而其他一些则有问题。这里是另一个尝试获取标签值的示例。

    s_temp = instance.get("tags")
    if s_temp == "NoneType":
        s_print = "N/A"
    elif s_temp == "None":
        s_print = "N/A"
    else:
        s_print = str(s_temp)
    print("Tags: " + s_print)

它总是返回"None"。

对我来说,Boto3如何返回数据非常令人困惑。谢谢...

profile picture
EXPERTE
gefragt vor 6 Monaten21 Aufrufe
1 Antwort
0

【以下的回答经过翻译处理】 您可以通过以下代码检查“InstanceType”和“cpu_options”。

https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2/client/describe_instances.html

另外,“instance.get()”函数不存在,会导致错误。

如果实例标签未设置,则不会输出任何内容。

import json
import boto3

def lambda_handler(event, context): 
    s_region = "ap-northeast-1" 
    instance_ids = [] 
    ec2 = boto3.client('ec2', region_name=s_region) 
    print(boto3.__version__) 
    print(" ") 
    response = ec2.describe_instances(InstanceIds=instance_ids) 
    instances_full_details = response['Reservations'] 
    for instance_detail in instances_full_details: 
        group_instances = instance_detail['Instances'] 
        for instance in group_instances: 
            instance_id = instance['InstanceId'] 
            print("ID: " + instance_id) 
            print(instance['InstanceType'])
            print(instance['CpuOptions'])
#            s_temp = instance.get("InstanceType") 
#            print('InstanceType=' + s_temp) 
#            temp = instance.get("cpu_options") 
#            s_temp = str(temp.keys())

profile picture
EXPERTE
beantwortet vor 6 Monaten

Du bist nicht angemeldet. Anmelden um eine Antwort zu veröffentlichen.

Eine gute Antwort beantwortet die Frage klar, gibt konstruktives Feedback und fördert die berufliche Weiterentwicklung des Fragenstellers.

Richtlinien für die Beantwortung von Fragen