boto3搜索未使用的安全组



我正在使用AWS Python SDK boto3,我试图知道哪些安全组未使用。使用boto2,我做到了,但我不知道该如何使用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())

使用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', '...

首先,我建议您重新boto3如何处理凭据。更好地使用Genereic 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

注意:未测试代码。请根据需要调试。

注意:如果您的ASG(自动添加组)处于null状态(count = 0),当ASG开始添加添加安全组时,则将采用孤儿安全组。请记住,您需要检查ASG安全组

我使用了另一种方法。如果我们跳过凭据讨论,然后返回主要问题," boto3搜索未使用的安全组"。这是一个选择:您去枚举资源,在我的情况下是网络接口,因为如果考虑到它,必须与资源关联以使用安全组才能使用。我的示例:

client = boto3.client('ec2', region_name=region, aws_access_key_id=newsession_id, aws_secret_access_key=newsession_key, aws_session_token=newsession_token)
response = client.describe_network_interfaces()
for i in response["NetworkInterfaces"]:
    #Check if the security group is attached
    if 'Attachment' in i and i['Attachment']['Status'] == 'attached':
        #Create a list with the attached SGs
        groups = [g['GroupId'] for g in i['Groups']]

ii使用了网络接口资源,因为我需要为帐户提供公共IP。

最新更新