diff --git a/cmd/osbuild-service-maintenance/aws.go b/cmd/osbuild-service-maintenance/aws.go index 17f64db88a..ea88033e10 100644 --- a/cmd/osbuild-service-maintenance/aws.go +++ b/cmd/osbuild-service-maintenance/aws.go @@ -6,6 +6,7 @@ import ( "sync" "time" + ec2types "github.com/aws/aws-sdk-go-v2/service/ec2/types" "github.com/sirupsen/logrus" "golang.org/x/sync/semaphore" @@ -88,6 +89,16 @@ func AWSCleanup(maxConcurrentRequests int, dryRun bool, accessKeyID, accessKey s if err != nil { return fmt.Errorf("Unable to describe instances by tag %w", err) } + + instanceIDs := filterReservations(reservations) + err = a.TerminateInstances(instanceIDs) + if err != nil { + return fmt.Errorf("Unable to terminate secure instances: %w", err) + } + return nil +} + +func filterReservations(reservations []ec2types.Reservation) []string { var instanceIDs []string for _, res := range reservations { for _, i := range res.Instances { @@ -96,9 +107,5 @@ func AWSCleanup(maxConcurrentRequests int, dryRun bool, accessKeyID, accessKey s } } } - err = a.TerminateInstances(instanceIDs) - if err != nil { - return fmt.Errorf("Unable to terminate secure instances: %w", err) - } - return nil + return instanceIDs } diff --git a/cmd/osbuild-service-maintenance/aws_test.go b/cmd/osbuild-service-maintenance/aws_test.go new file mode 100644 index 0000000000..32ced52aea --- /dev/null +++ b/cmd/osbuild-service-maintenance/aws_test.go @@ -0,0 +1,52 @@ +package main_test + +import ( + "testing" + "time" + + ec2types "github.com/aws/aws-sdk-go-v2/service/ec2/types" + "github.com/stretchr/testify/require" + + main "github.com/osbuild/osbuild-composer/cmd/osbuild-service-maintenance" + "github.com/osbuild/osbuild-composer/internal/common" +) + +func TestFilterReservations(t *testing.T) { + reservations := []ec2types.Reservation{ + { + Instances: []ec2types.Instance{ + { + LaunchTime: common.ToPtr(time.Now().Add(-time.Hour * 24)), + InstanceId: common.ToPtr("not filtered"), + }, + }, + }, + { + Instances: []ec2types.Instance{ + { + LaunchTime: common.ToPtr(time.Now().Add(-time.Minute * 121)), + InstanceId: common.ToPtr("not filtered"), + }, + }, + }, + { + Instances: []ec2types.Instance{ + { + LaunchTime: common.ToPtr(time.Now().Add(-time.Minute * 119)), + InstanceId: common.ToPtr("filtered"), + }, + }, + }, + { + Instances: []ec2types.Instance{ + { + LaunchTime: common.ToPtr(time.Now()), + InstanceId: common.ToPtr("filtered"), + }, + }, + }, + } + + instanceIDs := main.FilterReservations(reservations) + require.Equal(t, []string{"not filtered", "not filtered"}, instanceIDs) +} diff --git a/cmd/osbuild-service-maintenance/export_test.go b/cmd/osbuild-service-maintenance/export_test.go new file mode 100644 index 0000000000..bf813e47af --- /dev/null +++ b/cmd/osbuild-service-maintenance/export_test.go @@ -0,0 +1,3 @@ +package main + +var FilterReservations = filterReservations