2017-06-20 71 views
2

我想獲得下面的輸出的SnapshotId沒有成功。我可以獲取AMI描述的值和AMI_ID的值。得到字典響應 - Boto3

{ 
    'Images': [ 
     { 
      'Architecture': 'i386'|'x86_64', 
      'CreationDate': 'string', 
      'ImageId': 'string', 
      'ImageLocation': 'string', 
      'ImageType': 'machine'|'kernel'|'ramdisk', 
      'Public': True|False, 
      'KernelId': 'string', 
      'OwnerId': 'string', 
      'Platform': 'Windows', 
      'ProductCodes': [ 
       { 
        'ProductCodeId': 'string', 
        'ProductCodeType': 'devpay'|'marketplace' 
       }, 
      ], 
      'RamdiskId': 'string', 
      'State': 'pending'|'available'|'invalid'|'deregistered'|'transient'|'failed'|'error', 
      'BlockDeviceMappings': [ 
       { 
        'DeviceName': 'string', 
        'VirtualName': 'string', 
        'Ebs': { 
         'Encrypted': True|False, 
         'DeleteOnTermination': True|False, 
         'Iops': 123, 
         'SnapshotId': 'string', 
         'VolumeSize': 123, 
         'VolumeType': 'standard'|'io1'|'gp2'|'sc1'|'st1' 
        }, 
        'NoDevice': 'string' 
       }, 
      ], 
      'Description': 'string', 
      'EnaSupport': True|False, 
      'Hypervisor': 'ovm'|'xen', 
      'ImageOwnerAlias': 'string', 
      'Name': 'string', 
      'RootDeviceName': 'string', 
      'RootDeviceType': 'ebs'|'instance-store', 
      'SriovNetSupport': 'string', 
      'StateReason': { 
       'Code': 'string', 
       'Message': 'string' 
      }, 
      'Tags': [ 
       { 
        'Key': 'string', 
        'Value': 'string' 
       }, 
      ], 
      'VirtualizationType': 'hvm'|'paravirtual' 
     }, 
    ] 
} 

使用下面的代碼:

import boto3 

client = boto3.client('ec2', region_name='us-east-1') 

def verifica_imagem(imagem): 
    amiresponse = client.describe_images(
     Filters=[ 
      { 
       'Name': 'description', 
       'Values': [ 
        imagem, 
       ] 
      }, 
     ], 
     DryRun=False 
    ) 

    try: 
     data = str(amiresponse['Images'][0]['Description']) 
     ami_id = str(amiresponse['Images'][0]['ImageId']) 
     snapshot_id = str(amiresponse['Images'][0]['SnapshotId']) 
    except: 
     print "AMI not exists! Exiting...." 
     return 1 

verifica_imagem('IMAGE_XXXXXXX') 

我不明白如何使用SnapshotId的關鍵。我曾嘗試過:

snapshot_id = str(amiresponse['Images']['BlockDeviceMappings']['Ebs'][0]['SnapshotId'])但是不工作。

回答

1

ImagesBlockDeviceMappings的值是arrayEbsdict
使用該獲取的SnapshotId值,

snapshot_id = amiresponse['Images'][0]['BlockDeviceMappings'][0]['Ebs']['SnapshotId'] 
+0

謝謝大家。現在它正在工作。 –