2016-06-30 198 views
3

我剛開始使用boto3並試圖獲取特定的值來描述實例調用。例如,如果我想從輸出中獲取'Hypervisor'值或者Ebs具有'DeleteOnTermintation'值。以下是我當前用來進行調用並迭代字典輸出的當前代碼。迭代通過ec2描述實例boto3

import boto3 
import pprint 
from datetime import datetime 
import json 

client = boto3.client('ec2') 

filters = [{ 
'Name': 'tag:Name', 
'Values': ['*'] 
}] 


class DatetimeEncoder(json.JSONEncoder): 
    def default(self, obj): 
    if isinstance(obj, datetime): 
     return obj.strftime('%Y-%m-%dT%H:%M:%SZ') 
    elif isinstance(obj, date): 
     return obj.strftime('%Y-%m-%d') 
    # Let the base class default method raise the TypeError 
    return json.JSONEncoder.default(self, obj)  


output = json.dumps((client.describe_instances(Filters=filters)), cls=DatetimeEncoder) 

pprint.pprint(output) 

for v in output: 
    print v['Hypervisor'] 

收到此錯誤:

類型錯誤:字符串索引必須是整數,而不是str的

使用pprint看到所有可從輸出的值。

謝謝..

回答

7

這裏是你如何可以顯示通過AWS Command-Line Interface (CLI)的信息:

aws ec2 describe-instances --query 'Reservations[*].Instances[*].[InstanceId, Hypervisor, NetworkInterfaces[0].Attachment.DeleteOnTermination]' 

下面是一些Python:

import boto3 

client = boto3.client('ec2') 

response = client.describe_instances() 

for r in response['Reservations']: 
    for i in r['Instances']: 
    print i['InstanceId'], i['Hypervisor'] 
    for b in i['BlockDeviceMappings']: 
     print b['Ebs']['DeleteOnTermination'] 
+1

感謝約翰..現在我可以建立在你的榜樣並進一步自定義腳本.. – user2040074