简体   繁体   English

试图了解 describe_instances() 的工作原理

[英]Trying to understand how describe_instances() work

Trying to understand how describe_instances() work Here is a code which gives me instances ids of all the instances I have currently 3 so 3 instance id I get试图了解 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)

gives me output给我输出

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

But if I write following但是如果我写以下

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

I just get following output我只是得到以下输出

Reservations
in for loop
ResponseMetadata
in for loop

What I was expecting was instance id's of instance.我所期待的是实例的实例 ID。 Now I wrote following现在我写了以下

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 get output我得到输出

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

the above print statement does not work if written as below如果写成如下,上面的打印语句不起作用

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

It gives error它给出了错误

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

What I am not able to understand is how are the values being returned by describe_instances method in the statement我无法理解的是语句中 describe_instances 方法返回的值如何

response=ec2.describe_instances()

Why the above for loop where I used x does not give output.为什么上面我使用 x 的 for 循环没有给出输出。 I read the documentation here https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.describe_instances and as far as I understand ec2.describe_instances() is returning a dictionary() Contains the output of DescribeInstances.我在这里阅读了文档https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.describe_instances并且据我了解 ec2.describe_instances() 正在返回一个 dictionary() 包含描述实例的输出。 • Reservations (list) -- Zero or more reservations. • 预订(列表)- 零个或多个预订。 So with that understanding I thought I should be able to iterate over list members via因此,有了这种理解,我认为我应该能够通过以下方式遍历列表成员

response["Reservations"][0]
response["Reservations"][1]
response["Reservations"][2]

But this is giving me error但这给了我错误

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

I am unable to understand the response which is coming via ec2.describe_instances()我无法理解来自 ec2.describe_instances() 的响应

Output of print (response) as asked in below answer打印输出(响应)如下面的回答

    {'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}}

You can note {'Groups': [], 'Instances': [{'AmiLaunchIndex': 0, line 2 times in above output and line 'AmiLaunchIndex': 1, 'ImageId': 'ami-00b6a8a2bd28daf19' two times while for the first instance it is 'AmiLaunchIndex': 0, 'ImageId': 'ami-d783a9b8', I had created these instances via run_instance method() as you can see in the print (response) output has come only but this is not giving a clear picture or I am unable to understand where are three instances in this this is what is not clear to me.您可以注意{'Groups': [], 'Instances': [{'AmiLaunchIndex': 0, line 2 times in above output and line 'AmiLaunchIndex': 1, 'ImageId': 'ami-00b6a8a2bd28daf19'两次,而对于第一个实例是'AmiLaunchIndex': 0, 'ImageId': 'ami-d783a9b8',我已经通过run_instance方法()创建了这些实例,正如您在打印(响应)输出中看到的那样,但这并没有给出一张清晰的图片,或者我无法理解这三个实例在哪里,这对我来说是不清楚的。

Basically, the response object will return one or many Reservation objects.基本上,响应对象将返回一个或多个 Reservation 对象。

response=ec2.describe_instances()

You don't really have to worry about Reservations, other than for the purpose of iterating them.除了迭代它们之外,您实际上不必担心保留。 To delve into more detail, you could have a look at this past question,要深入研究更多细节,你可以看看这个过去的问题,

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

So your first block of code is an appropriate way of listing the instance ID's of all EC2 instances.因此,您的第一个代码块是列出所有 EC2 实例的实例 ID 的适当方式。

The second block of code is iterating through the keys in the response object, which is a dictionary,第二个代码块是遍历响应对象中的键,这是一个字典,

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

Here's the Boto documentation for the EC2 service, where you can find more info on the response object,这是 EC2 服务的 Boto 文档,您可以在其中找到有关响应对象的更多信息,

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

As you can see the followinig error:如您所见,出现以下错误:

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

It states that you're trying to get the 2nd Instance of the Element Reservations whihch is not present in the given return.它表明您正在尝试获取给定返回中不存在的元素Reservations的第二个实例。 I would ask you to check the return of the function response=ec2.describe_instances() by printing it out on the terminal by using print(response) to get familiar with the data_type/return of that function.我会要求您检查函数response=ec2.describe_instances()的返回,方法是使用print(response)在终端上打印出来以熟悉该函数的 data_type/return。 This will help you get a good grasp of what to expect the next time this function is called.这将帮助您很好地掌握下次调用此函数时会发生什么。

Also, when you know the kind of return that you're going to get, it will be easy for you to later iterate through the response using something like a for loop for lists like elements(which your function, response=ec2.describe_instances() returns according to it's documentation.) and then further use the response for whatever that you're trying to achieve.此外,当您知道您将获得的返回类型时,您以后可以很容易地使用类似for loop的方式迭代响应,用于列表等元素(您的函数, response=ec2.describe_instances()根据它的文档返回。) 然后进一步将response用于您想要实现的任何目标。

Hope it helps.希望能帮助到你。 Happy Coding :)快乐编码:)

You can also use list comprehension to get this data.您还可以使用列表推导来获取此数据。 Example:例子:

  #!/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']]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM