@@ -28,6 +28,45 @@ import (
2828 "sigs.k8s.io/cluster-api-provider-aws/v2/pkg/cloud/filter"
2929)
3030
31+ func (s * Service ) deleteEC2Instances (ctx context.Context , resources []* AWSResource ) error {
32+ for _ , resource := range resources {
33+ if ! s .isEC2InstanceToDelete (resource ) {
34+ s .scope .Debug ("Resource not an EC2 instance for deletion" , "arn" , resource .ARN .String ())
35+ continue
36+ }
37+
38+ instanceID := strings .ReplaceAll (resource .ARN .Resource , "instance/" , "" )
39+ if err := s .deleteEC2Instance (ctx , instanceID ); err != nil {
40+ return fmt .Errorf ("deleting EC2 instance %s: %w" , instanceID , err )
41+ }
42+ }
43+ s .scope .Debug ("Finished processing resources for EC2 instance deletion" )
44+
45+ return nil
46+ }
47+
48+ func (s * Service ) isEC2InstanceToDelete (resource * AWSResource ) bool {
49+ if ! s .isMatchingResource (resource , ec2 .ServiceName , "instance" ) {
50+ return false
51+ }
52+ if eksClusterName := resource .Tags [eksClusterNameTag ]; eksClusterName != "" {
53+ s .scope .Debug ("EC2 instance was created by EKS directly" , "arn" , resource .ARN .String (), "check" , "instance" , "cluster_name" , eksClusterName )
54+ return false
55+ }
56+ s .scope .Debug ("Resource is an EC2 instance to delete" , "arn" , resource .ARN .String (), "check" , "instance" )
57+ return true
58+ }
59+
60+ func (s * Service ) deleteEC2Instance (ctx context.Context , instanceID string ) error {
61+ input := ec2.TerminateInstancesInput {
62+ InstanceIds : []* string {aws .String (instanceID )},
63+ }
64+ if _ , err := s .ec2Client .TerminateInstancesWithContext (ctx , & input ); err != nil {
65+ return fmt .Errorf ("terminating EC2 instance: %w" , err )
66+ }
67+ return nil
68+ }
69+
3170func (s * Service ) deleteSecurityGroups (ctx context.Context , resources []* AWSResource ) error {
3271 for _ , resource := range resources {
3372 if ! s .isSecurityGroupToDelete (resource ) {
0 commit comments