/
hosts_list.go
79 lines (66 loc) · 1.83 KB
/
hosts_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
package main
import (
"fmt"
"sort"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awsutil"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/dynport/gocli"
)
type hostsList struct {
//Query string `cli:"opt"`
}
func (r *hostsList) Run() error {
// Create an EC2 service object in the "eu-west-1" region
// Note that you can also configure your region globally by
// exporting the AWS_REGION environment variable
svc := ec2.New(session.New(), &aws.Config{})
// we are only concerned with running instances
filterChain := &ec2.DescribeInstancesInput{
Filters: []*ec2.Filter{
&ec2.Filter{
Name: aws.String("instance-state-name"),
Values: aws.StringSlice([]string{"running"}),
},
//&ec2.Filter{
// Name: aws.String("tag:Env"),
// Values: aws.StringSlice([]string{"staging"}),
//},
},
}
// filter by environment
//Query string `cli:"arg"`
// Call the DescribeInstances Operation
resp, err := svc.DescribeInstances(filterChain)
if err != nil {
panic(err)
}
// id launch_time ami name ip type role
t := gocli.NewTable()
t.Header("id", "launch_time", "ami", "name", "ip", "public_ip", "type", "role")
instances, _ := awsutil.ValuesAtPath(resp, "Reservations[].Instances[]")
for _, instance := range instances {
h := instance.(*ec2.Instance)
tags := aggregateTags(h.Tags)
// TODO - calculate role from tags
role := gocli.Red("NONE")
t.Add(h.InstanceId, h.LaunchTime.Format("2006-01-02T15:04"), h.ImageId, tags["Name"], h.PrivateIpAddress, h.PublicIpAddress, h.InstanceType, role)
}
t.SortBy = 1
sort.Sort(sort.Reverse(t))
fmt.Println(t)
return nil
}
func truncate(s string, length int) string {
if len(s) > length {
return s[0:length]
}
return s
}
func p2s(in *string) string {
if in == nil {
return ""
}
return *in
}