2016-12-14 51 views
4

我正在使用AWS Python SDK Boto3,并试图了解哪些安全组未被使用。随着boto2我做到了,但我不知道如何做到与boto3一样。boto3搜索未使用的安全组

from boto.ec2.connection import EC2Connection 
from boto.ec2.regioninfo import RegionInfo 
import boto.sns 
import sys 
import logging 
from security_groups_config import config 

# Get settings from config.py 
aws_access_key = config['aws_access_key'] 
aws_secret_key = config['aws_secret_key']  
ec2_region_name = config['ec2_region_name'] 
ec2_region_endpoint = config['ec2_region_endpoint'] 

region = RegionInfo(name=ec2_region_name, endpoint=ec2_region_endpoint) 

if aws_access_key: 
    conn = EC2Connection(aws_access_key, aws_secret_key, region=region) 
else: 
    conn = EC2Connection(region=region) 

sgs = conn.get_all_security_groups() 

## Searching unused SG if the instances number is 0 
def search_unused_sg(event, context): 
    for sg in sgs: 
     print sg.name, len(sg.instances()) 
+1

在boto3,您可以收集来自“describe_instances”和“describe_security_groups”的信息,存储安全组名称价值转化为各自的集合,然后进行扣除。 – mootmoot

+0

是的,当然,但我想知道是否有一个函数提供这些信息。在boto2中有'''get_all_security_groups()'''。 – Robert

+0

不幸的是,没有。 Boto3是一个重写API,与boto2相比,它有很好的文档记录和良好的维护,并且没有什么惊喜。 – mootmoot

回答

2

首先,我建议你再看看boto3如何处理凭证。更好地使用基础的AWS凭证文件,因此在将来需要时,您可以切换到IAM角色基础凭证或AWS STS,而无需更改代码。

import boto3 
# You should use the credential profile file 
ec2 = boto3.client("ec2") 

# In boto3, if you have more than 1000 entries, you need to handle the pagination 
# using the NextToken parameter, which is not shown here. 

all_instances = ec2.describe_instances() 
all_sg = ec2.describe_security_groups() 

instance_sg_set = set() 
sg_set = set() 

for reservation in all_instances["Reservations"] : 
    for instance in reservation["Instances"]: 
    for sg in instance["SecurityGroups"]: 
     instance_sg_set.add(sg["GroupName"]) 


for security_group in all_sg["SecurityGroups"] : 
    sg_set.add(security_group ["GroupName"]) 

idle_sg = sg_set - instance_sg_set 

注意:代码没有经过测试。请根据需要进行调试。

+0

为什么人们甚至会投票呢? AttributeError:'ec2.ServiceResource'对象没有属性'describe_instances' – buildmaestro

+0

@buildmaestro检查你自己的代码。以上代码使用'boto3.clent(“ec2”)',而不是'boto3.resource(“ec2”)'。 – mootmoot

+0

是的,我使用相同的代码;不使用.resource – buildmaestro

1

使用Boto3和Python的列表理解的能力,并设置让你在7行代码想要的东西:

import boto3 

ec2 = boto3.resource('ec2') #You have to change this line based on how you pass AWS credentials and AWS config 

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

all_sgs = set([sg.group_name for sg in sgs]) 
all_inst_sgs = set([sg['GroupName'] for inst in insts for sg in inst.security_groups]) 
unused_sgs = all_sgs - all_inst_sgs 

调试信息

print 'Total SGs:', len(all_sgs) 
print 'SGS attached to instances:', len(all_inst_sgs) 
print 'Orphaned SGs:', len(unused_sgs) 
print 'Unattached SG names:', unused_sgs 

输出

Total SGs: 289 
SGS attached to instances: 129 
Orphaned SGs: 160 
Unattached SG names: set(['mysg', '... 
+0

感谢你的解决方案,但它提出了一个错误,因为“stackTrace”:[ [ “/var/task/lambda_function.py”, 81, “unused_sg”, “SGS =列表(ec2.security_groups.all())” ] ], “ERRORTYPE”: “AttributeError的”, “的errorMessage”:“ 'EC2' 对象没有属性'security_groups'“ }''' – Robert

+0

@Robert,你确定你正在使用'ec2 = boto3.resource('ec2')'? – helloV

+0

我创建客户端:'''客户端= boto3.client( 'EC2', aws_access_key_id = AWS_ACCESS_KEY, aws_secret_access_key = AWS_SECRET_KEY, REGION_NAME = REGION_NAME)''' – Robert