diff --git a/ec2id.go b/ec2id.go index 30de0ef..44dbf14 100644 --- a/ec2id.go +++ b/ec2id.go @@ -29,7 +29,7 @@ func NewAwsClient() (EC2DescribeInstancesAPI, error){ return ec2.NewFromConfig(cfg), nil } -func Ec2id(name string, client EC2DescribeInstancesAPI) error { +func Ec2id(name string, client EC2DescribeInstancesAPI) (string, error) { var params *ec2.DescribeInstancesInput = nil if len(name) != 0 { params = &ec2.DescribeInstancesInput{ @@ -45,11 +45,11 @@ func Ec2id(name string, client EC2DescribeInstancesAPI) error { result, err := GetInstances(context.TODO(), client, params) if err != nil { fmt.Fprintln(os.Stderr, "Got an error retrieving information about your Amazon EC2 instance") - return err + return "", err } if len(result.Reservations) == 0 { - return nil + return "", nil } // TODO jmespath.Searchで書き換えるとシンプルになる? @@ -67,7 +67,5 @@ func Ec2id(name string, client EC2DescribeInstancesAPI) error { } } - fmt.Println(*filteredInstance.InstanceId) - - return nil + return *filteredInstance.InstanceId, nil } diff --git a/ec2id_test.go b/ec2id_test.go index c9916f4..655d6c0 100644 --- a/ec2id_test.go +++ b/ec2id_test.go @@ -19,7 +19,7 @@ func TestEc2id(t *testing.T) { Filters: []types.Filter{ { Name: aws.String("tag:Name"), - Values: []string{"test"}, + Values: []string{"noexist"}, }, }, }). @@ -29,12 +29,16 @@ func TestEc2id(t *testing.T) { cases := []struct { name string client EC2DescribeInstancesAPI + instanceName string + expect string wantErr bool expectErr string }{ { - name: "", + name: "return no instance-id", client: mockClient, + instanceName: "noexist", + expect: "", wantErr: false, expectErr: "", }, @@ -42,7 +46,7 @@ func TestEc2id(t *testing.T) { for _, tt := range cases { t.Run(tt.name, func(t *testing.T) { - err := Ec2id("test", tt.client) + id, err := Ec2id(tt.instanceName, tt.client) if tt.wantErr { if (!strings.Contains(err.Error(), tt.expectErr)) { t.Errorf("expect NoSuchKey error, got %T", err) @@ -52,6 +56,9 @@ func TestEc2id(t *testing.T) { if err != nil { t.Errorf("expect no error, got error: %v", err) } + if expected := tt.expect; id != expected { + t.Errorf("expect no output, got id: %s", id) + } }) } } diff --git a/main.go b/main.go index 2fb6d01..f7443cd 100644 --- a/main.go +++ b/main.go @@ -40,7 +40,11 @@ func main() { fmt.Fprintf(os.Stderr, "initialized failed:%v\n", err) os.Exit(1) } - return Ec2id(name, client) + id, err := Ec2id(name, client) + if err == nil { + fmt.Println(id) + } + return err }, HideHelpCommand: true, Version: getVersion(),