diff --git a/moto/ec2/models.py b/moto/ec2/models.py index fd15a8ee2..bf0e9a89f 100644 --- a/moto/ec2/models.py +++ b/moto/ec2/models.py @@ -875,10 +875,21 @@ class VPCBackend(object): return self.vpcs.values() def delete_vpc(self, vpc_id): + # Delete route table if only main route table remains. + route_tables = ec2_backend.get_all_route_tables(filters={'vpc-id':vpc_id}) + if len(route_tables) > 1: + raise DependencyViolationError( + "The vpc {0} has dependencies and cannot be deleted." + .format(vpc_id) + ) + for route_table in route_tables: + ec2_backend.delete_route_table(route_table.id) + + # Now delete VPC. vpc = self.vpcs.pop(vpc_id, None) if not vpc: raise InvalidVPCIdError(vpc_id) - self.delete_route_table_for_vpc(vpc.id) + if vpc.dhcp_options: vpc.dhcp_options.vpc = None self.delete_dhcp_options_set(vpc.dhcp_options.id) @@ -1148,16 +1159,6 @@ class RouteTableBackend(object): raise InvalidRouteTableIdError(route_table_id) return deleted - def get_route_table_for_vpc(self, vpc_id): - for route_table in self.route_tables.values(): - if route_table.vpc_id == vpc_id: - return route_table - - def delete_route_table_for_vpc(self, vpc_id): - route_table = self.get_route_table_for_vpc(vpc_id) - if route_table: - self.delete_route_table(route_table.id) - class Route(object): def __init__(self, route_table, destination_cidr_block, local=False, diff --git a/tests/test_ec2/test_route_tables.py b/tests/test_ec2/test_route_tables.py index fbd85d70d..9df76be2f 100644 --- a/tests/test_ec2/test_route_tables.py +++ b/tests/test_ec2/test_route_tables.py @@ -58,6 +58,12 @@ def test_route_tables_additional(): local_route.state.should.equal('active') local_route.destination_cidr_block.should.equal(vpc.cidr_block) + with assert_raises(EC2ResponseError) as cm: + conn.delete_vpc(vpc.id) + cm.exception.code.should.equal('DependencyViolation') + cm.exception.status.should.equal(400) + cm.exception.request_id.should_not.be.none + conn.delete_route_table(route_table.id) all_route_tables = conn.get_all_route_tables()