【发布时间】:2019-06-18 19:11:57
【问题描述】:
我正在使用 Lambda 运行我的 AWS 账户,返回所有实例的列表。我需要能够打印出 所有 'VolumeId' 值,但我不知道如何在它们嵌套时访问它们。我可以为每个实例打印出 first VolumeId,但是,有些实例有几个卷,而有些只有一个。我想我知道为什么我会得到这些结果,但我不知道该怎么做才能让所有这些结果都回来。
以下是一个实例的 JSON 的外观:
{
'Groups':[],
'Instances':[
{
'AmiLaunchIndex':0,
'ImageId':'ami-0',
'InstanceId':'i-0123',
'InstanceType':'big',
'KeyName':'nonprod',
'LaunchTime':'date',
'Monitoring':{
'State':'disabled'
},
'Placement':{
'AvailabilityZone':'world',
'GroupName':'',
'Tenancy':'default'
},
'PrivateDnsName':'secret',
'PrivateIpAddress':'1.2.3.4',
'ProductCodes':[
],
'PublicDnsName':'',
'State':{
'Code':80,
'Name':'stopped'
},
'StateTransitionReason':'User initiated',
'SubnetId':'subnet-1',
'VpcId':'vpc-1',
'Architecture':'yes',
'BlockDeviceMappings':[
{
'DeviceName':'/sda',
'Ebs':{
'AttachTime':'date',
'DeleteOnTermination':True,
'Status':'attached',
'VolumeId':'vol-1'
}
},
{
'DeviceName':'/sdb',
'Ebs':{
'AttachTime':'date'),
'DeleteOnTermination':False,
'Status':'attached',
'VolumeId':'vol-2'
}
}
],
这就是我为获得第一个 VolumeId 所做的:
ec2client = boto3.client('ec2')
ec2 = ec2client.describe_instances()
for reservation in ec2["Reservations"]:
for instance in reservation["Instances"]:
instanceid = instance["InstanceId"]
volumes = instance["BlockDeviceMappings"][0]["Ebs"]["VolumeId"]
print("The associated volume IDs for this instance are: ",(volumes))
我认为我只获得第一个 ID 的原因是因为我引用了“BlockDeviceMappings”中的第一个元素,但我不知道如何获得其他的。如果我在不指定 [0] 的情况下尝试它,我会收到 list indices must be integers or slices, not str 错误。我也尝试使用字典而不是列表,但感觉就像我用那棵树叫错了树。任何建议/帮助将不胜感激!
【问题讨论】:
标签: python json amazon-web-services