无法删除安全组:调用 DeleteSecurityGroup 操作时发生错误(DependencyViolation)

Unable to delete security group: An error occurred (DependencyViolation) when calling the DeleteSecurityGroup operation

我正在尝试删除具有 0 个接口且未在使用 boto3 的任何其他安全组的入口规则中引用的安全组。 但我收到错误: 调用 DeleteSecurityGroup 操作时发生错误(DependencyViolation):资源 sg-XXYYZZ 有依赖对象

我想要一个代码来列出引用安全组 sg-XXYYZZ 的入口规则,并在删除安全组之前使用 boto3 删除这些入口规则: response = ec2.delete_security_group( GroupId=sg, DryRun=False )

我列出入口规则使用:

    for sg in final_del_list:
        response = ec2.describe_security_groups( GroupIds=[sg] )
        print( "\n\n Security Group:", sg )
        for res in response['SecurityGroups']:
            msg = "The Ingress rules are as follows: " if len(res['IpPermissions']) > 0 else "No ingress rules"
            print( msg )
            for ip in res['IpPermissions']:
                print( "IP Protocol: ", ip['IpProtocol'] )
                try:
                    print( "PORT: ", str( ip['FromPort'] ) )
                    for range in ip['IpRanges']:
                        print( "IP Ranges: ", range['CidrIp'] )
                except Exception:
                    print( "No value for ports and ip ranges available for this security group" )

谁能指导我如何在其入口规则中列出引用 sg-XXYYZZ 的安全性或帮助我解决错误

通过查看您的错误:An error occurred (DependencyViolation) when calling the DeleteSecurityGroup operation: resource sg-XXYYZZ has a dependent object

我现在可以在这里提出一些建议,而不是编写代码。 1.你不能安全组,如果它与任何其他实例相关联,即使实例处于停止状态。 2. 这可能看起来是一个孤立的安全组,但它可能与另一个与实例相关联的安全组相关联。因此,您需要先编辑该安全组,然后才能删除您指定的安全组。

我写了一个这样的 script in github 可能对你有帮助

可以在 UserIdGroupPairs

下找到安全组
   response = ec2.describe_security_groups( GroupIds=[sg] )
    for res in response['SecurityGroups']:
        if len( res['IpPermissions'] ) > 0:
            for item in res['IpPermissions']:
                for sg in item['UserIdGroupPairs']:
                    sg_list.append( sg['GroupId'] )