获取ec2实例的块设备的卷ID

时间:2017-01-20 13:54:26

标签: python amazon-web-services amazon-ec2

我想获取名为“application”的实例的块设备(不是根设备)的卷ID:

ec2client = session.client('ec2')
response = ec2client.describe_instances(Filters=[{'Name': 'tag-key', 'Values': ['application'] },])

如何从回复中检索身份证明?我知道卷id在响应语法中:

'BlockDeviceMappings': [
                        {
                            'DeviceName': 'string',
                            'Ebs': {
                                'VolumeId': 'string',
                                'Status': 'attaching'|'attached'|'detaching'|'detached',
                                'AttachTime': datetime(2015, 1, 1),
                                'DeleteOnTermination': True|False
                            }
                        },
                    ],

我试过了:

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

但我一无所获......没有什么是打印的。

1 个答案:

答案 0 :(得分:1)

如果您只是询问如何访问字典,请按以下步骤操作:

from datetime import datetime
response = {'Reservations': [{'Instances':[{'BlockDeviceMappings': [
                        {
                            'DeviceName': 'Dev1',
                            'Ebs': {
                                'VolumeId': 'Vol1',
                                'Status': 'attaching',
                                'AttachTime': datetime(2015, 1, 1),
                                'DeleteOnTermination': True|False
                            }
                        },
                        {
                            'DeviceName': 'Dev2',
                            'Ebs': {
                                'VolumeId': 'Vol2',
                                'Status': 'attaching',
                                'AttachTime': datetime(2015, 1, 1),
                                'DeleteOnTermination': True|False
                            }
                        },
                    ],
           'other_key': 'other data'}]}]}


out = []
for reservation in response['Reservations']:
    for instance in reservation['Instances']:
        out += [device['Ebs']['VolumeId'] for device in instance['BlockDeviceMappings']]
print out

# outputs ['Vol1', 'Vol2']

我稍微概括了你的问题,以处理返回多个设备的情况。如果您知道自己只有一台设备,则可以使用response['BlockDeviceMappings'][0]['Ebs']['VolumeId']

另一种方法是使用AWS CLIjq

$ aws ec2 describe-instances | jq -c ".Reservations|.[0]|.Instances|.[0]|.BlockDeviceMappings|.[0]|.Ebs|.VolumeId"`