簡體   English   中英

使用python + boto刪除未使用的AWS安全組,拋出vpc錯誤

[英]using python + boto to delete AWS security groups that are unused, throwing vpc error

問題:我使用 boto 編寫了一個 python 腳本,以按名稱檢索所有未使用的安全組。 我也試過 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.

所以從技術上講,按名稱刪除應該使它成為 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)

您必須將安全組作為關鍵字參數傳遞。 我創建了一個名為“ delete_me_test_from_boto”的虛擬組。

當我跑步時:

conn.delete_security_group('delete_me_test_from_boto')

我收到以下錯誤:

EC2ResponseError: EC2ResponseError: 400 Bad Request

InvalidGroup.NotFound默認VPC'vpc-9efe64fb'c89e06e8-2d39-4365-b326-84f5a4896980中不存在安全組'delete_me_test_from_boto'

但是,這可行:

conn.delete_security_group(group_id='sg-e1085f85')

使用 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

這是GitHub awsdocs/aws-doc-sdk-examples上更大示例的一部分

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM