@@ -19,14 +19,16 @@ package subnets
1919import (
2020 "context"
2121
22+ infrav1 "sigs.k8s.io/cluster-api-provider-gcp/api/v1beta1"
23+
2224 "github.com/GoogleCloudPlatform/k8s-cloud-provider/pkg/cloud/meta"
2325 "google.golang.org/api/compute/v1"
2426
2527 "sigs.k8s.io/cluster-api-provider-gcp/cloud/gcperrors"
2628 "sigs.k8s.io/controller-runtime/pkg/log"
2729)
2830
29- // Reconcile reconcile cluster network components.
31+ // Reconcile reconciles cluster network components.
3032func (s * Service ) Reconcile (ctx context.Context ) error {
3133 logger := log .FromContext (ctx )
3234 logger .Info ("Reconciling subnetwork resources" )
@@ -43,13 +45,31 @@ func (s *Service) Reconcile(ctx context.Context) error {
4345func (s * Service ) Delete (ctx context.Context ) error {
4446 logger := log .FromContext (ctx )
4547 for _ , subnetSpec := range s .scope .SubnetSpecs () {
46- logger .V (2 ).Info ("Deleting a subnet" , "name" , subnetSpec .Name )
4748 subnetKey := meta .RegionalKey (subnetSpec .Name , s .getSubnetRegion (subnetSpec ))
48- err := s .subnets .Delete (ctx , subnetKey )
49- if err != nil && ! gcperrors .IsNotFound (err ) {
50- logger .Error (err , "Error deleting subnet" , "name" , subnetSpec .Name )
49+ logger .V (2 ).Info ("Looking for subnet before deleting it" , "name" , subnetSpec .Name )
50+ subnet , err := s .subnets .Get (ctx , subnetKey )
51+ if err != nil {
52+ if gcperrors .IsNotFound (err ) {
53+ continue
54+ }
55+ logger .Error (err , "Error getting subnet" , "name" , subnetSpec .Name )
5156 return err
5257 }
58+
59+ // Skip delete if subnet was not created by CAPG.
60+ // If subnet description is not set by the Spec, or by our default value, then assume it was created externally.
61+ if subnet .Description != infrav1 .ClusterTagKey (s .scope .Name ()) && (subnetSpec .Description == "" || subnet .Description != subnetSpec .Description ) {
62+ logger .V (2 ).Info ("Skipping subnet deletion as it was created outside of Cluster API" , "name" , subnetSpec .Name )
63+ return nil
64+ }
65+
66+ logger .V (2 ).Info ("Deleting a subnet" , "name" , subnetSpec .Name )
67+ if err := s .subnets .Delete (ctx , subnetKey ); err != nil {
68+ if ! gcperrors .IsNotFound (err ) {
69+ logger .Error (err , "Error deleting subnet" , "name" , subnetSpec .Name )
70+ return err
71+ }
72+ }
5373 }
5474
5575 return nil
0 commit comments