Search code examples
python-3.xamazon-web-servicesboto3aws-security-group

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


I am trying to delete security groups that has 0 interfaces and is not being referred in the ingress rule of any other security group using boto3. But I am getting error: An error occurred (DependencyViolation) when calling the DeleteSecurityGroup operation: resource sg-XXYYZZ has a dependent object

I want a code to list down the ingress rules that is referring to security group sg-XXYYZZ and delete those ingress rule using boto3 before I delete the security group: response = ec2.delete_security_group( GroupId=sg, DryRun=False )

I am listing the ingress rules using:

    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" )

Can someone guide me how can I list security that is referring to sg-XXYYZZ in its ingress rule or help me solve the error


Solution

  • The security groups can be found listed under 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'] )