小编ben*_*ben的帖子

aws boto3抓取子网信息

我试图从aws中获取一个子网列表,我有一个我修改过的VPC工作版本:

ec2 = boto3.resource('ec2')
client = boto3.client('ec2')

filters = [{'Name':'tag:Name', 'Values':['*']}]
subnets = list(ec2.Subnet.filter(Filters=filters))

for subnet in subnets:
    response = client.describe_subnets(
        VpcIds=[
            vpc.id,
        ]
    )
    print(response['Subnets'])
Run Code Online (Sandbox Code Playgroud)

我一直在:

subnets = list(ec2.Subnet.filters(Filters = filters))AttributeError:'function'对象没有属性'filters'

从阅读的所有内容和其他示例来看,这应该有效

有任何想法吗?

python amazon-ec2 python-3.x aws-sdk boto3

5
推荐指数
1
解决办法
5670
查看次数

从嵌套字典 aws 响应中获取键和值

我正在努力了解嵌套字典以及如何从中获取键和值。

我有一个很好的脚本,可以从我的 AWS 账户获取 VPC 信息:

import boto3
from pprint import pprint

#Declaring some resources for the below scripts. 
ec2 = boto3.resource('ec2')
client = boto3.client('ec2')

#Grabing the VPC information and printing to console. 
filters = [{'Name':'tag:Name', 'Values':['*']}]
vpcs = list(ec2.vpcs.filter(Filters=filters))

for vpc in vpcs:
    response = client.describe_vpcs(
        VpcIds=[
            vpc.id,
        ]
    )
    pprint(response['Vpcs'])
    print('-------')
Run Code Online (Sandbox Code Playgroud)

输出如下:

[{'CidrBlock': '666.666.0.0/66', 'DhcpOptionsId': '55555', 'InstanceTenancy': '默认', 'IsDefault': False,'状态': '可用', '标签': [{ 'Key': '环境', 'Value': 'dev.aws'}, {'Key': '名称', 'Value': 'dev.aws.co.uk'}], 'VpcId': 'vpc -755555'}]

现在我想要的是仅获取 VpcId 和标签,我尝试了 pprint(response['Vpcs']["VpcId"]) …

python amazon-web-services aws-sdk boto3

5
推荐指数
1
解决办法
5463
查看次数

可以忽略KeyError?

我有一些简单的代码进入aws并抓取一些数据然后将其打印到控制台

mycode的:

import boto3
from pprint import pprint

ec2 = boto3.resource('ec2')
client = boto3.client('ec2')

#This is the VPC ID and Linked Tags
for vpctags in client.describe_vpcs()['Vpcs']: 
    print("VPC ID: ", vpctags['VpcId']) 
    print("Tags: ", vpctags['Tags'])
    for subnet in client.describe_subnets()['Subnets']:
        print("Subnet ID: ", subnet['SubnetId'])
        print("Subnet ID: ", subnet['Tags'])

###############################################
Run Code Online (Sandbox Code Playgroud)

我收到错误,因为我的一个或多个子网没有标记:

print("子网ID:",子网['Tags'])KeyError:'Tags'

我不希望每个子网都有标签,所以有没有办法简单地忽略标签的缺失,只打印空或只是继续?

对不起,如果这听起来像一个愚蠢的问题,我搜索谷歌并找到了一些想法,但他们看起来有点先进我所拥有的.

python amazon-web-services aws-sdk boto3

5
推荐指数
1
解决办法
3060
查看次数