sigs.k8s.io/cluster-api-provider-aws@v1.5.5/pkg/cloud/services/gc/ec2.go (about)

     1  /*
     2  Copyright 2022 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8  	http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package gc
    18  
    19  import (
    20  	"context"
    21  	"fmt"
    22  	"strings"
    23  
    24  	"github.com/aws/aws-sdk-go/aws"
    25  	"github.com/aws/aws-sdk-go/service/ec2"
    26  )
    27  
    28  func (s *Service) deleteSecurityGroups(ctx context.Context, resources []*AWSResource) error {
    29  	for _, resource := range resources {
    30  		if !s.isSecurityGroupToDelete(resource) {
    31  			s.scope.V(5).Info("Resource not a security group for deletion", "arn", resource.ARN.String())
    32  			continue
    33  		}
    34  
    35  		groupID := strings.ReplaceAll(resource.ARN.Resource, "security-group/", "")
    36  		if err := s.deleteSecurityGroup(ctx, groupID); err != nil {
    37  			return fmt.Errorf("deleting security group %s: %w", groupID, err)
    38  		}
    39  	}
    40  	s.scope.V(2).Info("Finished processing resources for security group deletion")
    41  
    42  	return nil
    43  }
    44  
    45  func (s *Service) isSecurityGroupToDelete(resource *AWSResource) bool {
    46  	if !s.isMatchingResource(resource, ec2.ServiceName, "security-group") {
    47  		return false
    48  	}
    49  	if eksClusterName := resource.Tags[eksClusterNameTag]; eksClusterName != "" {
    50  		s.scope.V(5).Info("Security group was created by EKS directly", "arn", resource.ARN.String(), "check", "securitygroup", "cluster_name", eksClusterName)
    51  		return false
    52  	}
    53  	s.scope.V(5).Info("Resource is a security group to delete", "arn", resource.ARN.String(), "check", "securitygroup")
    54  
    55  	return true
    56  }
    57  
    58  func (s *Service) deleteSecurityGroup(ctx context.Context, securityGroupID string) error {
    59  	input := ec2.DeleteSecurityGroupInput{
    60  		GroupId: aws.String(securityGroupID),
    61  	}
    62  
    63  	s.scope.V(2).Info("Deleting security group", "group_id", securityGroupID)
    64  	if _, err := s.ec2Client.DeleteSecurityGroupWithContext(ctx, &input); err != nil {
    65  		return fmt.Errorf("deleting security group: %w", err)
    66  	}
    67  
    68  	return nil
    69  }