-
Notifications
You must be signed in to change notification settings - Fork 0
/
list.go
86 lines (68 loc) · 1.96 KB
/
list.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package main
import (
"fmt"
"os"
"slices"
"strings"
"text/tabwriter"
"github.com/ivoronin/ec2ssh/awsutil"
)
var (
allowedListColumns = [...]string{
"ID", "NAME", "STATE", "TYPE", "PRIVATE-IP",
"PUBLIC-IP", "IPV6", "PRIVATE-DNS", "PUBLIC-DNS",
}
defaultListColumns = "ID,NAME,STATE,PRIVATE-IP,PUBLIC-IP"
)
func parseRequestedColumns(requestedColumns string) ([]string, error) {
if requestedColumns == "" {
requestedColumns = defaultListColumns
}
requestedColumns = strings.ToUpper(requestedColumns)
requestedColumns = strings.ReplaceAll(requestedColumns, " ", "")
columns := strings.Split(requestedColumns, ",")
for _, column := range columns {
if !slices.Contains(allowedListColumns[:], column) {
return nil, fmt.Errorf("%w: invalid column %s", ErrArgParse, column)
}
}
return columns, nil
}
const listPadding = 2
func List(options Options) error {
columns, err := parseRequestedColumns(options.ListColumns)
if err != nil {
return err
}
instances, err := awsutil.ListInstances()
if err != nil {
return fmt.Errorf("unable to list instances: %w", err)
}
writer := tabwriter.NewWriter(os.Stdout, 0, 1, listPadding, ' ', 0)
fmt.Fprintln(writer, strings.Join(columns, "\t"))
for _, instance := range instances {
state := string(instance.State.Name)
typ := string(instance.InstanceType)
values := map[string]*string{
"ID": instance.InstanceId,
"NAME": GetInstanceName(instance),
"STATE": &state,
"TYPE": &typ,
"PRIVATE-IP": instance.PrivateIpAddress,
"PUBLIC-IP": instance.PublicIpAddress,
"IPV6": instance.Ipv6Address,
"PRIVATE-DNS": instance.PrivateDnsName,
"PUBLIC-DNS": instance.PublicDnsName,
}
var rows []string
for _, column := range columns {
value := "-"
if values[column] != nil && *(values[column]) != "" {
value = *values[column]
}
rows = append(rows, value)
}
fmt.Fprintln(writer, strings.Join(rows, "\t"))
}
return writer.Flush()
}