【问题标题】:Easiest way to match security groups to their instances in Boto 3?在 Boto 3 中将安全组与其实例匹配的最简单方法是什么?
【发布时间】:2019-06-22 21:41:05
【问题描述】:

我有一个安全组的 python 列表,我需要找到它们关联到哪个 EC2/RDS 实例或 ELB。在 Boto3 中最简单的方法是什么?

此外,据我所知,一个安全组可以附加到多个实例,一个 EC2 实例可以附加多个安全组,因此我需要找到一种方法来识别这些关系以更好地清理它。我正确的是安全组对象的 python 列表。

这是我当前的代码:

import boto3
import json

# regions = ["us-east-1","ap-southeast-1","ap-southeast-2","ap-northeast-1","eu-central-1","eu-west-1"]
regions = ["us-east-1"]

uncompliant_security_groups = []

for region in regions:
    ec2 = boto3.resource('ec2', region_name=region)

    sgs = list(ec2.security_groups.all())

    for sg in sgs:
        for rule in sg.ip_permissions:
            # Check if list of IpRanges is not empty, source ip meets conditions
            if len(rule.get('IpRanges')) > 0 and rule.get('IpRanges')[0]['CidrIp'] == '0.0.0.0/0':
                if rule.get('FromPort') == None:
                    uncompliant_security_groups.append(sg)

                if rule.get('FromPort') != None and rule.get('FromPort') < 1024 and rule.get('FromPort') != 80 and rule.get('FromPort') != 443:
                    uncompliant_security_groups.append(sg)


print(uncompliant_security_groups)
print(len(uncompliant_security_groups))

for sec_group in uncompliant_security_groups:

【问题讨论】:

  • 你目前有什么代码sn-ps吗?你在纠结什么?
  • 抱歉,我认为这无关紧要。正如我所说,我设法检索了安全组列表,但我不知道如何将这些不合规的安全组与 EC2/RDS 和 ELB 进行比较,以检查哪个资源正在使用哪个安全组。
  • SG 中没有关联信息。您需要查询您的资源以获取附加的 SG。然后将该列表与所有可用的 SG 进行比较,并确定未附加的 SG。不是很困难。

标签: python-3.x amazon-web-services boto3


【解决方案1】:

如果您在账户中启用 AWS Config Aggregator(如果您必须为此付费):

account_id = '0123456789'
region = 'us-east-2'
sg_id = 'sg-0123456789'
relationship_data = CONFIG_CLIENT.get_aggregate_resource_config(
    ConfigurationAggregatorName='agg_name',
    ResourceIdentifier={
        'SourceAccountId': account_id,
        'SourceRegion': region,
        'ResourceId': sg_id,
        'ResourceType': 'AWS::EC2::SecurityGroup'
        }
    )]
    relationship_data = relationship_data['ConfigurationItem']['relationships']
    print(relationship_data)

应该返回一些数据,例如:

[
{'resourceType': 'AWS::EC2::NetworkInterface', 'resourceId': 'eni-0123456789', 'relationshipName': 'Is associated with NetworkInterface'}, 
{'resourceType': 'AWS::EC2::Instance', 'resourceId': 'i-0123456789', 'relationshipName': 'Is associated with Instance'},
{'resourceType': 'AWS::EC2::VPC', 'resourceId': 'vpc-0123456789', 'relationshipName': 'Is contained in Vpc'}
]

注意:这似乎仅适用于 AWS CONFIG AGGREGATORS!我不知道为什么会这样,或者数据是否可以从 aws config 本身获得。但是,我的组织使用 aws config,因此这为我启用了这种类型的数据。 Boto3 配置文档: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/config.html

【讨论】:

    猜你喜欢
    • 2012-05-08
    • 1970-01-01
    • 1970-01-01
    • 2011-03-21
    • 2023-03-20
    • 1970-01-01
    • 2016-04-26
    • 1970-01-01
    相关资源
    最近更新 更多