【问题标题】:Trying to understand how describe_instances() work试图了解 describe_instances() 的工作原理
【发布时间】:2022-01-14 15:58:55
【问题描述】:

试图了解 describe_instances() 的工作原理 这是一个代码,它为我提供了我目前拥有的所有实例的实例 ID 3 所以我得到了 3 个实例 ID

    import boto3 
    from pprint import pprint

    ec2=boto3.client('ec2') 
    response=ec2.describe_instances()
    instancelist = [] 
   for reservation in (response["Reservations"]):
        for instance in reservation["Instances"]:
            instancelist.append(instance["InstanceId"]) print (instancelist)

给我输出

['i-03e7f6391a0f523ee', 'i-0e12c8dad5fb6d8c5', 'i-002adcd0913e4d673']

但是如果我写如下

import boto3
from pprint import pprint
ec2=boto3.client('ec2')
response=ec2.describe_instances()
for x in response:
    print (x)
    print ("in for loop")

我只是得到以下输出

Reservations
in for loop
ResponseMetadata
in for loop

我期待的是实例的实例 ID。 现在我写了以下

import boto3
from pprint import pprint

ec2=boto3.client('ec2')
response=ec2.describe_instances()

print (response["Reservations"][0]["Instances"][0]["InstanceId"])
print (response["Reservations"][1]["Instances"][0]["InstanceId"])
print (response["Reservations"][1]["Instances"][1]["InstanceId"])

我得到输出

i-03e7f6391a0f523ee i-0e12c8dad5fb6d8c5 i-002adcd0913e4d673

上面的打印语句如果写成下面这样是行不通的

print (response["Reservations"][2]["Instances"][0]["InstanceId"])

报错

    print (response["Reservations"][2]["Instances"][1]["InstanceId"])
IndexError: list index out of range

我无法理解的是语句中的 describe_instances 方法返回的值是怎样的

response=ec2.describe_instances()

为什么上面我使用 x 的 for 循环没有给出输出。我在这里阅读了文档 https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.describe_instances 据我了解 ec2.describe_instances() 正在返回一个 dictionary() 包含 DescribeInstances 的输出。 • 预订(列表)-- 零个或多个预订。因此,有了这种理解,我认为我应该能够通过

遍历列表成员
response["Reservations"][0]
response["Reservations"][1]
response["Reservations"][2]

但这给了我错误

print(response["Reservations"][2])
IndexError: list index out of range

我无法理解来自 ec2.describe_instances() 的响应

如下回答中要求的打印输出(响应)

    {'Reservations': [

    {'Groups': [], 'Instances': [{'AmiLaunchIndex': 0, 'ImageId': 'ami-d783a9b8', 

    'InstanceId': 'i-03e7f6391a0f523ee', 'InstanceType': 't2.micro', 'KeyName': 'datastructutre key', 

    'LaunchTime': datetime.datetime(2018, 8, 25, 10, 3, 53, tzinfo=tzutc()), 'Monitoring': {'State': 

    'disabled'}, 'Placement': {'AvailabilityZone': 'ap-south-1a', 'GroupName': '', 'Tenancy': 

    'default'}, 'PrivateDnsName': 'ip-172-31-20-16.ap-south-1.compute.internal', 'PrivateIpAddress': 

    '172.31.20.16', 'ProductCodes': [], 'PublicDnsName': '', 'State': {'Code': 80, 'Name': 

    'stopped'}, 'StateTransitionReason': 'User initiated (2018-08-25 10:07:17 GMT)', 'SubnetId': 

    'subnet-d3fdbabb', 'VpcId': 'vpc-08356c60', 'Architecture': 'x86_64', 'BlockDeviceMappings': 

    [{'DeviceName': '/dev/xvda', 'Ebs': {'AttachTime': datetime.datetime(2018, 8, 1, 4, 28, 52, 

    tzinfo=tzutc()), 'DeleteOnTermination': True, 'Status': 'attached', 'VolumeId': 'vol-

    09716d3308f44c63f'}}], 'ClientToken': '', 'EbsOptimized': False, 'EnaSupport': True, 

    'Hypervisor': 'xen', 'NetworkInterfaces': [{'Attachment': {'AttachTime': datetime.datetime(2018, 

    8, 1, 4, 28, 52, tzinfo=tzutc()), 'AttachmentId': 'eni-attach-08d060230b617ca70', 

    'DeleteOnTermination': True, 'DeviceIndex': 0, 'Status': 'attached'}, 'Description': '', 

    'Groups': [{'GroupName': 'launch-wizard-1', 'GroupId': 'sg-0e81c2a33e1039f58'}, {'GroupName': 

    'default', 'GroupId': 'sg-40e5492a'}], 'Ipv6Addresses': [], 'MacAddress': '02:5a:17:52:69:a6', 

    'NetworkInterfaceId': 'eni-0146aab6d9503bf47', 'OwnerId': '11000101010', 'PrivateDnsName': 'ip-

    172-31-20-16.ap-south-1.compute.internal', 'PrivateIpAddress': '172.31.20.16', 

    'PrivateIpAddresses': [{'Primary': True, 'PrivateDnsName': 'ip-172-31-20-16.ap-south-

    1.compute.internal', 'PrivateIpAddress': '172.31.20.16'}], 'SourceDestCheck': True, 'Status': 

    'in-use', 'SubnetId': 'subnet-d3fdbabb', 'VpcId': 'vpc-08356c60'}], 'RootDeviceName': 

    '/dev/xvda', 'RootDeviceType': 'ebs', 'SecurityGroups': [{'GroupName': 'launch-wizard-1', 

    'GroupId': 'sg-0e81c2a33e1039f58'}, {'GroupName': 'default', 'GroupId': 'sg-40e5492a'}], 

    'SourceDestCheck': True, 'StateReason': {'Code': 'Client.UserInitiatedShutdown', 'Message': 

    'Client.UserInitiatedShutdown: User initiated shutdown'}, 'VirtualizationType': 'hvm', 

    'CpuOptions': {'CoreCount': 1, 'ThreadsPerCore': 1}}], 'OwnerId': '11000101010', 'ReservationId': 

    'r-0571937a9ea83fac4'}, 

  {'Groups': [], 'Instances': [

{'AmiLaunchIndex': 0, 'ImageId': 'ami-00b6a8a2bd28daf19', 'InstanceId': 'i-0e12c8dad5fb6d8c5', 'InstanceType': 't2.micro', 'KeyName': 'datastructutre key', 'LaunchTime': datetime.datetime(2018, 8, 25, 10, 3, 53, tzinfo=tzutc()), 'Monitoring': {'State': 'disabled'}, 'Placement': {'AvailabilityZone': 'ap-south-1a', 'GroupName': '', 'Tenancy': 'default'}, 'PrivateDnsName': 'ip-172-31-28-39.ap-south-1.compute.internal', 'PrivateIpAddress': '172.31.28.39', 'ProductCodes': [], 'PublicDnsName': '', 'State': {'Code': 80, 'Name': 'stopped'}, 'StateTransitionReason': 'User initiated (2018-08-25 10:07:17 GMT)', 'SubnetId': 'subnet-d3fdbabb', 'VpcId': 'vpc-08356c60', 'Architecture': 'x86_64', 'BlockDeviceMappings': [{'DeviceName': '/dev/xvda', 'Ebs': {'AttachTime': datetime.datetime(2018, 8, 22, 21, 33, 44, tzinfo=tzutc()), 'DeleteOnTermination': True, 'Status': 'attached', 'VolumeId': 'vol-01d5ce67c9f1b081e'}}], 'ClientToken': '', 'EbsOptimized': False, 'EnaSupport': True, 'Hypervisor': 'xen', 'NetworkInterfaces': [{'Attachment': {'AttachTime': datetime.datetime(2018, 8, 22, 21, 33, 44, tzinfo=tzutc()), 'AttachmentId': 'eni-attach-0cbdea888315049ae',  'DeleteOnTermination': True, 'DeviceIndex': 0, 'Status': 'attached'}, 'Description': '',  'Groups': [{'GroupName': 'default', 'GroupId': 'sg-40e5492a'}], 'Ipv6Addresses': [], 'MacAddress': '02:f4:b8:bd:84:26', 'NetworkInterfaceId': 'eni-0d99a7669a1e4b9db', 'OwnerId': '11000101010', 'PrivateDnsName': 'ip-172-31-28-39.ap-south-1.compute.internal', 'PrivateIpAddress': '172.31.28.39', 'PrivateIpAddresses': [{'Primary': True, 'PrivateDnsName': 'ip-172-31-28-39.ap-south-1.compute.internal', 'PrivateIpAddress': '172.31.28.39'}], 'SourceDestCheck': True, 'Status': 'in-use', 'SubnetId': 'subnet-d3fdbabb', 'VpcId': 'vpc-08356c60'}], 'RootDeviceName': '/dev/xvda', 'RootDeviceType': 'ebs', 'SecurityGroups': [{'GroupName': 'default', 'GroupId': 'sg-40e5492a'}], 'SourceDestCheck': True, 'StateReason': {'Code': 'Client.UserInitiatedShutdown', 'Message': 'Client.UserInitiatedShutdown: User initiated shutdown'}, 'VirtualizationType': 'hvm', 'CpuOptions': {'CoreCount': 1, 'ThreadsPerCore': 1}}, 

{'AmiLaunchIndex': 1, 'ImageId': 'ami-00b6a8a2bd28daf19', 'InstanceId': 'i-002adcd0913e4d673', 'InstanceType': 't2.micro', 'KeyName': 'datastructutre key', 'LaunchTime': datetime.datetime (2018, 8, 25, 10, 3, 53, tzinfo=tzutc()), 'Monitoring': {'State': 'disabled'}, 'Placement': {'AvailabilityZone': 'ap-south-1a', 'GroupName': '', 'Tenancy': 'default'}, 'PrivateDnsName': 'ip-172-31-30-108.ap-south-1.compute.internal', 'PrivateIpAddress': '172.31.30.108', 'ProductCodes': [], 'PublicDnsName': '', 'State': {'Code': 80, 'Name': 'stopped'}, 'StateTransitionReason': 'User initiated (2018-08-25 10:07:17 GMT)', 'SubnetId': 'subnet-d3fdbabb', 'VpcId': 'vpc-08356c60', 'Architecture': 'x86_64', 'BlockDeviceMappings': [{'DeviceName': '/dev/xvda', 'Ebs': {'AttachTime': datetime.datetime(2018, 8, 22, 21, 33, 44, tzinfo=tzutc()), 'DeleteOnTermination': True, 'Status': 'attached', 'VolumeId': 'vol-0f0c49cc912a083f3'}}], 'ClientToken': '', 'EbsOptimized': False, 'EnaSupport': True, 'Hypervisor': 'xen', 'NetworkInterfaces': [{'Attachment': {'AttachTime': datetime.datetime(2018, 8, 22, 21, 33, 44, tzinfo=tzutc()), 'AttachmentId': 'eni-attach-0f35d1842b76cff9a', 'DeleteOnTermination': True, 'DeviceIndex': 0, 'Status': 'attached'}, 'Description': '', 'Groups': [{'GroupName': 'default', 'GroupId': 'sg-40e5492a'}], 'Ipv6Addresses': [], 'MacAddress': '02:21:d4:20:22:c6', 'NetworkInterfaceId': 'eni-0e3797492dc4e3299', 'OwnerId': '11000101010', 'PrivateDnsName': 'ip-172-31-30-108.ap-south-1.compute.internal', 'PrivateIpAddress': '172.31.30.108', 'PrivateIpAddresses': [{'Primary': True, 'PrivateDnsName': 'ip-172-31-30-108.ap-south-1.compute.internal', 'PrivateIpAddress': '172.31.30.108'}], 'SourceDestCheck': True, 'Status': 'in-use', 'SubnetId': 'subnet-d3fdbabb', 'VpcId': 'vpc-08356c60'}], 'RootDeviceName': '/dev/xvda', 'RootDeviceType': 'ebs', 'SecurityGroups': [{'GroupName': 'default', 'GroupId': 'sg-40e5492a'}], 'SourceDestCheck': True, 'StateReason': {'Code': 'Client.UserInitiatedShutdown', 'Message': 'Client.UserInitiatedShutdown: User initiated shutdown'}, 'VirtualizationType': 'hvm', 'CpuOptions': {'CoreCount': 1, 'ThreadsPerCore': 1}}], 'OwnerId': 'ReservationId': 'r-05cff59b2524ed79c'}], 

'ResponseMetadata': {'RequestId': 'fc80ae94-dd46-4c71-93f5-a38d6ede800c', 'HTTPStatusCode': 200, 'HTTPHeaders': {'content-type':'text/xml;charset=UTF-8', 'transfer-encoding': 'chunked', 'vary': 'Accept-Encoding', 'date': 'Sat, 25 Aug 2018 17:13:51 GMT', 'server': 'AmazonEC2'}, 'RetryAttempts': 0}}

您可以在上面的输出中记下{'Groups': [], 'Instances': [{'AmiLaunchIndex': 0, 行2 次和'AmiLaunchIndex': 1, 'ImageId': 'ami-00b6a8a2bd28daf19' 行两次,而第一个实例是'AmiLaunchIndex': 0, 'ImageId': 'ami-d783a9b8', 我通过run_instance 方法()创建了这些实例 正如您在打印(响应)输出中看到的那样,这并没有给出清晰的画面,或者我无法理解这三个实例在哪里,这对我来说是不清楚的。

【问题讨论】:

    标签: python python-3.x amazon-web-services amazon-ec2 boto3


    【解决方案1】:

    基本上,响应对象会返回一个或多个 Reservation 对象。

    response=ec2.describe_instances()
    

    您实际上不必担心保留,除非是为了迭代它们。要深入了解更多细节,您可以查看这个过去的问题,

    https://serverfault.com/questions/749118/aws-ec2-what-is-a-reservation-id-exactly-and-what-does-it-represent

    因此,您的第一个代码块是列出所有 EC2 实例的实例 ID 的适当方式。

    第二个代码块是遍历响应对象中的键,这是一个字典,

    response=ec2.describe_instances()
    for x in response:
        print(x)
    

    这是 EC2 服务的 Boto 文档,您可以在其中找到有关响应对象的更多信息,

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

    【讨论】:

      【解决方案2】:

      如您所见,出现以下错误:

      print(response["Reservations"][2])
      IndexError: list index out of range
      

      它表明您正在尝试获取给定返回中不存在的元素 Reservations 的第二个实例。我会要求您检查函数response=ec2.describe_instances() 的返回,方法是使用print(response) 在终端上打印出来以熟悉该函数的data_type/return。这将帮助您很好地掌握下次调用此函数时会发生什么。

      此外,当您知道您将获得的返回类型时,您以后可以很容易地使用 for loop 之类的东西来迭代响应,用于类似元素的列表(您的函数,@987654326 @ 根据它的文档返回。)然后进一步使用 response 来实现您想要实现的任何目标。

      希望对您有所帮助。快乐编码:)

      【讨论】:

      • 我使用过 print (response) 但我无法理解为什么 Reservations[0] 有 Instance0 但 Response[1] 有两个成员 Instance[0] this 和 Instance[1] this thing让我很困惑。
      • 您能否发布您的print(response) 的输出以便我们更好地理解?
      • 我已经在问题的末尾发布了 print(response) 的输出
      • 如您在打印(响应)输出中所见,仅针对 1 个实例
      • 刚刚看到您的编辑,它似乎并没有那么可疑,是吗?您的输出实例具有不同数量的 AmiLaunchIndex 具有不同的值,但这不应该打扰您,因为您可以轻松地遍历它们而无需知道实例的数量。只需按照答案中的说明使用for loop 打开并遍历任何返回的列表
      【解决方案3】:

      您还可以使用列表推导来获取此数据。 示例:

        #!/usr/bin/env python3
        import boto3
      
        # Creating the boto client
        client = boto3.client('ec2')
      
        # Get the instance list
        instance_details = client.describe_instances(
          InstanceIds=[
            instance_id,
          ],
        )
        # Get all the Instance details from the Reservations
        # wrapping instances in [] prevents creating a outer list
        [instances] = [x['Instances']for x in instance_details['Reservations']]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-20
        • 2018-06-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多