diff --git a/ec2id.go b/ec2id.go index 6a9ec98..486f8fb 100644 --- a/ec2id.go +++ b/ec2id.go @@ -5,6 +5,7 @@ import ( "context" "fmt" "os" + "sort" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/config" @@ -40,19 +41,21 @@ func Ec2id(name string, client EC2DescribeInstancesAPI) ([]string, error) { return nil, nil } - // TODO jmespath.Searchで書き換えるとシンプルになる? - var filteredInstance = result.Reservations[0].Instances[0] + var filteredInstance = []types.Instance{} for _, v := range result.Reservations { - for _, instance := range v.Instances { - if filteredInstance.LaunchTime.After(*instance.LaunchTime) { - continue - } + filteredInstance = append(filteredInstance, v.Instances...) + } + + sort.Slice(filteredInstance, func(i, j int) bool { + return filteredInstance[i].LaunchTime.After(*filteredInstance[j].LaunchTime) + }) - filteredInstance = instance - } + var instanceIds = []string{} + for _, v := range filteredInstance { + instanceIds = append(instanceIds, *v.InstanceId) } - return []string{*filteredInstance.InstanceId}, nil + return instanceIds, nil } func buildDescribeInstancesInput(name string) *ec2.DescribeInstancesInput { diff --git a/ec2id_test.go b/ec2id_test.go index 6228f67..33b8229 100644 --- a/ec2id_test.go +++ b/ec2id_test.go @@ -15,6 +15,11 @@ import ( func TestEc2id(t *testing.T) { ctrl := gomock.NewController(t) mockClient := NewMockEC2DescribeInstancesAPI(ctrl) + // reservation-id, instance-id, launch-time, tag:Name + // r-03803cf1200d61cf7,i-0123456789abcdef0, 2023-01-05-12:00:00.00, sample + // r-03803cf1200d61cf7,i-0123456789abcdef1, 2023-01-05-12:00:00.01, sample + // r-03803cf1200d61cf7,i-0123456789abcdef2, 2023-01-05-12:00:00.02, sample2 + // r-03803cf1200d61cf7,i-00000000000abcdef, 2023-01-04-12:00:00.00, test mockClient.EXPECT(). DescribeInstances(context.TODO(), &ec2.DescribeInstancesInput{ Filters: []types.Filter{ @@ -114,10 +119,10 @@ func TestEc2id(t *testing.T) { expectErr: "", }, { - name: "return latest instance-id by no input", + name: "return instance-ids sorted by LaunchTime descending with no input", client: mockClient, instanceName: "", - expect: []string{"i-0123456789abcdef2"}, + expect: []string{"i-0123456789abcdef2", "i-0123456789abcdef1", "i-0123456789abcdef0", "i-00000000000abcdef"}, wantErr: false, expectErr: "", }, @@ -148,7 +153,7 @@ func TestEc2id(t *testing.T) { } for k, v := range ids { if v != tt.expect[k] { - t.Errorf("expect %s, got id: %s", tt.expect, ids) + t.Errorf("expect %s, got id: %s at index %d", tt.expect, ids, k) } } })