From 80c3f6b2c55bc7567656a5b885217d21fffa4038 Mon Sep 17 00:00:00 2001 From: TangBin Date: Tue, 15 Dec 2020 11:48:09 +0800 Subject: [PATCH] fix(region): aws detach igw before delete vpc --- pkg/multicloud/aws/vpc.go | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/pkg/multicloud/aws/vpc.go b/pkg/multicloud/aws/vpc.go index d78c3af4df..51fc55a26f 100644 --- a/pkg/multicloud/aws/vpc.go +++ b/pkg/multicloud/aws/vpc.go @@ -155,7 +155,17 @@ func (self *SVpc) GetIRouteTableById(routeTableId string) (cloudprovider.ICloudR return routeTable, nil } +/* +Deletes the specified VPC. You must detach or delete all gateways and resources that are associated with +the VPC before you can delete it. For example, you must terminate all instances running in the VPC, +delete all security groups associated with the VPC (except the default one), +delete all route tables associated with the VPC (except the default one), and so on. +*/ func (self *SVpc) Delete() error { + err := self.DetachInternetGateway() + if err != nil { + return errors.Wrap(err, "DetachInternetGateway") + } // 删除vpc会同步删除关联的安全组 return self.region.DeleteVpc(self.VpcId) } @@ -415,6 +425,28 @@ func (self *SVpc) AttachInternetGateway(igwId string) error { return nil } +func (self *SVpc) DetachInternetGateway() error { + igws, err := self.region.GetInternetGateways(self.GetId()) + if err != nil { + return errors.Wrap(err, "GetInternetGateways") + } + + if len(igws) > 0 { + for i := range igws { + input := ec2.DetachInternetGatewayInput{} + input.SetInternetGatewayId(igws[i].InternetGatewayID) + input.SetVpcId(self.GetId()) + + _, err := self.region.ec2Client.DetachInternetGateway(&input) + if err != nil { + return errors.Wrap(err, "DetachInternetGateway") + } + } + } + + return nil +} + func (self *SRegion) getVpc(vpcId string) (*SVpc, error) { if len(vpcId) == 0 { return nil, fmt.Errorf("GetVpc vpc id should not be empty.")