[英]using python + boto to delete AWS security groups that are unused, throwing vpc error
The problem: I wrote a python script using boto to retrieve all unused security groups by their name.问题:我使用 boto 编写了一个 python 脚本,以按名称检索所有未使用的安全组。 I also have tried by id because the documentation reads我也试过 id 因为文档读
delete_security_group(name=None, group_id=None, dry_run=False)
Delete a security group from your account.
Parameters:
name (string) – The name of the security group to delete.
group_id (string) – The ID of the security group to delete within a VPC.
dry_run (bool) – Set to True if the operation should not actually run.
Return type:
bool
Returns:
True if successful.
so technically deletion by name should make it vpc ambivalent, either way i have tried both.所以从技术上讲,按名称删除应该使它成为 vpc 矛盾的,无论哪种方式我都尝试过。 However, boto returns an error about deleting the security group from the wrong vpc.但是,boto 返回有关从错误的 vpc 中删除安全组的错误。 I'm a little confused here.我在这里有点困惑。
Here is the error这是错误
group for delete elb
EC2ResponseError: 400 Bad Request
<?xml version="1.0" encoding="UTF-8"?>
<Response><Errors><Error><Code>InvalidGroup.NotFound</Code><Message>The security group 'elb' does not exist in default VPC 'vpc-4fb'</Message></Error></Errors><RequestID>5c72aeb6-e841-4f3b-b976-4aa02b806a77</RequestID></Response>
this was ran against scratch.这是从头开始的。 You can see the error message is for the default vpc and not the vpc that my groups live in. I try to solve this by filtering by vpc_id but still same error.您可以看到错误消息是针对默认 vpc 而不是我的组所在的 vpc。我尝试通过 vpc_id 过滤来解决这个问题,但仍然是同样的错误。
#!/usr/bin/env python
import argparse
from boto import ec2
import os
import pprint
import sys
def main(profile=None, region='us-west-2', del_flag=None):
if profile =='production':
vpc = "vpc-efe"
if profile =='dev':
vpc = "vpc-139"
if profile =='test':
vpc = "vpc-ecd"
if profile =='scratch':
vpc = "vpc-475"
pp = pprint.PrettyPrinter(indent=4)
conn = ec2.connect_to_region(region, profile_name=profile)
allgroups = []
# Get ALL security groups names
vpc_filter = {'vpc_id':vpc}
groups = conn.get_all_security_groups(filters=vpc_filter)
for groupobj in groups:
allgroups.append(groupobj.name)
# Get [running|stopped] instances security groups
groups_in_use = []
for state in ['running','stopped']:
reservations = conn.get_all_instances(filters={'instance-state-name': state})
for r in reservations:
for inst in r.instances:
if inst.groups[0].name not in groups_in_use:
groups_in_use.append(inst.groups[0].name)
delete_candidates = []
for group in allgroups:
if group not in groups_in_use:
delete_candidates.append(group)
if del_flag == 'yes':
print "We will now delete security groups identified to not be in use."
for group in delete_candidates:
print 'group for delete', group
try:
conn.delete_security_group(group)
except Exception as e:
print e
print "We have deleted %d groups." % (len(delete_candidates))
print "The list of security groups that are in use."
pp.pprint(sorted(groups_in_use))
print "Total of %d groups targeted for being in use." % (len(groups_in_use))
else:
print "The list of security groups to be removed is below."
print "Run this again with `--delete` to remove them"
pp.pprint(sorted(delete_candidates))
print "Total of %d groups targeted for removal." % (len(delete_candidates))
print "The list of security groups that are in use."
pp.pprint(sorted(groups_in_use))
print "Total of %d groups targeted for being in use." % (len(groups_in_use))
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--profile', help='profile name in your ~/.boto config', required=True)
parser.add_argument('--delete', help='delete yes or no', required=True)
parser.add_argument('--region', help='', required=True)
args = parser.parse_args()
main(profile=args.profile, region=args.region, del_flag=args.delete)
You must pass the security group as a keyword argument. 您必须将安全组作为关键字参数传递。 I've created a dummy group named 'delete_me_test_from_boto'. 我创建了一个名为“ delete_me_test_from_boto”的虚拟组。
When I run: 当我跑步时:
conn.delete_security_group('delete_me_test_from_boto')
I get the following error: 我收到以下错误:
EC2ResponseError: EC2ResponseError: 400 Bad Request
InvalidGroup.NotFound
The security group 'delete_me_test_from_boto' does not exist in default VPC 'vpc-9efe64fb'c89e06e8-2d39-4365-b326-84f5a4896980 InvalidGroup.NotFound
默认VPC'vpc-9efe64fb'c89e06e8-2d39-4365-b326-84f5a4896980中不存在安全组'delete_me_test_from_boto'
However, this works: 但是,这可行:
conn.delete_security_group(group_id='sg-e1085f85')
With Boto3 you can use the SecurityGroup resource to do this:使用 Boto3,您可以使用 SecurityGroup 资源来执行此操作:
import boto3
ec2 = boto3.resource('ec2')
def delete_security_group(group_id):
try:
ec2.SecurityGroup(group_id).delete()
logger.info("Deleted security group %s.", group_id)
except ClientError:
logger.exception("Couldn't delete security group %s.", group_id)
raise
This is part of a larger example on GitHub awsdocs/aws-doc-sdk-examples这是GitHub awsdocs/aws-doc-sdk-examples上更大示例的一部分
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.