【问题标题】:aws python boto3 is not returning the right number of security groupsaws python boto3 未返回正确数量的安全组
【发布时间】:2017-04-29 19:49:30
【问题描述】:

我正在使用 Python SDK boto3 将所有安全组放入该区域,但我得到了错误的号码。有我的代码:

## Client connection
ec2 = boto3.client(
    'ec2',
    aws_access_key_id=aws_access_key,
    aws_secret_access_key=aws_secret_key,
    region_name = ec2_region_name
)


def lambda_handler(event, context):
    count = 0
    for sg in ec2.describe_security_groups():
        count = count + 1
    print(count)

当有数百个安全组时,结果为 2。

我做错了什么?

【问题讨论】:

    标签: python aws-sdk aws-cli boto3 aws-security-group


    【解决方案1】:

    请再次检查describe_security_groups文档返回值。

    你需要从返回字典键["SecurityGroups"]中读取列表

     for sg in ec2.describe_security_groups()["SecurityGroups"]:
            count = count + 1
        print(count)
    

    【讨论】:

    • 哦,是这样吗?谢谢@mootmoot。您知道如何获取与安全组关联的所有实例吗?使用 boto2 您可以执行 sg.instances() 然后与零进行比较,在这种情况下,该安全组未被使用。但是对于 boto3,我也愿意这样做。
    猜你喜欢
    • 2017-03-08
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    • 2016-04-11
    • 2018-10-13
    • 2017-11-26
    • 2017-04-29
    • 1970-01-01
    相关资源
    最近更新 更多