Проблема: Я написал скрипт python с помощью boto для извлечения всех неиспользуемых групп безопасности по их имени. Я также пытался по идентификатору, поскольку документация читаетс помощью python + boto для удаления групп безопасности AWS, которые не используются, throwing vpc error
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.
так технически удаление по имени должны сделать его VPC двойственным, в любом случае я бы попробовал оба. Однако boto возвращает ошибку об удалении группы безопасности из-за неправильного vpc. Я немного смущен.
Здесь ошибка
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>
это пробежалась против нуля. Вы можете увидеть сообщение об ошибке для 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)