带有boto3.client的aws lamda-读取dict和

时间:2019-02-07 13:09:48

标签: python amazon-web-services lambda boto3

我希望你能帮助我 从aws lambda收到200 ok的响应后,我想搜索Routes中的所有DestinationCidrBlock 但是当打印时,我只会得到第一个

u'Routes': [{u'Origin': 'CreateRoute', u'DestinationCidrBlock': '1.1.1.1/32', u'NetworkInterfaceId': 'eni-08b854f5bc83cefe4', u'State': 'blackhole'}, {u'Origin': 'CreateRoute', u'DestinationCidrBlock': '2.2.2.2/32', u'NetworkInterfaceId': 'eni-08b854f5bc83cefe4', u'State': 'blackhole'}, {u'GatewayId': 'local', u'DestinationCidrBlock': '172.31.0.0/16', u'State': 'active', u'Origin': 'CreateRouteTable'}, {u'GatewayId': 'igw-cec16ba6', u'DestinationCidrBlock': '0.0.0.0/0', u'State': 'active', u'Origin': 'CreateRoute'}]}]}

如果我以这种方式进行操作,我会得到值,但不是2.2.2.2/32:

print response["RouteTables"][0]['Routes'][0]['DestinationCidrBlock']

print response["RouteTables"][0]['RouteTableId']

1.1.1.1/32

rtb-08c31263

但是如果在其中进行for循环,我会得到这种格式的数字

for x in response["RouteTables"][0]['Routes'][0]['DestinationCidrBlock']:
print x

1

1

1

1

/

3

2

所以我的问题,希望能对我有所帮助,如何才能在其中获取所有IP地址并以某种方式存储 将ip和路由表ID关联到某种字典或列表中,以获取格式正确的所有数据

1 个答案:

答案 0 :(得分:0)

["RouteTables"][0]保留结果返回的第一个路由表,如果只有一个路由表,则可以这样做,但是如果您有更多路由表并且需要考虑每个路由表,则将还需要遍历["RouteTables"]的内容。

我将假设您只有一个路由表。

您已经从以下位置获取了路由表ID

["RouteTables"][0]["RouteTableId"]

如果要提取每个目标cidr块,则需要遍历

["RouteTables"][0]["Routes"]

并在循环时提取那些cidr块,即

cirdBlocks = [route["DestinationCidrBlock"] for route in response["RouteTables"][0]["Routes"]]

要创建一个字典,其关键字为路由表ID,值为上述cidr块,只需执行以下操作

routeTableId = response["RouteTables"][0]["RouteTableId"]
cirdBlocks = [route["DestinationCidrBlock"] for route in response["RouteTables"][0]["Routes"]]
routeTableCidrAssoc = { routeTableId: cirdBlocks }