-
Notifications
You must be signed in to change notification settings - Fork 0
/
aws.go
99 lines (88 loc) · 2.15 KB
/
aws.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
87
88
89
90
91
92
93
94
95
96
97
98
99
package main
import (
"fmt"
"os"
"time"
//"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"strings"
)
var imageMap = make(map[string]string)
var ec2Svc = ec2.New(getSession())
// InstanceData is used to figure out
// where to SSH to
type InstanceData struct {
PrivateIP string
InstanceID string
Name string
Az string
Os string
LaunchTime time.Time
}
func getSession() *session.Session {
return session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
}
func tagValue(tags []*ec2.Tag, name string) string {
for _, v := range tags {
if *v.Key == name {
return *v.Value
}
}
return ""
}
func getInstanceData() []*InstanceData {
var instances []*InstanceData
result, err := ec2Svc.DescribeInstances(nil)
if err != nil {
fmt.Println("Error getting data from AWS:", err)
os.Exit(1)
}
for _, reservation := range result.Reservations {
awsData := reservation.Instances[0]
instanceState := *awsData.State.Name
if instanceState == "running" {
data := InstanceData{
PrivateIP: *awsData.NetworkInterfaces[0].PrivateIpAddress,
Name: tagValue(awsData.Tags, "Name"),
InstanceID: *awsData.InstanceId,
Az: *awsData.Placement.AvailabilityZone,
Os: getAmiOS(awsData.ImageId),
LaunchTime: *awsData.LaunchTime,
}
instances = append(instances, &data)
}
}
return instances
}
func getAmiOS(amiID *string) string {
cachedImage, ok := imageMap[*amiID]
if ok {
return cachedImage
}
imageFilter := "image-id"
filter := &ec2.Filter{
Name: &imageFilter,
Values: []*string{amiID},
}
opts := &ec2.DescribeImagesInput{
Filters: []*ec2.Filter{filter},
}
response, err := ec2Svc.DescribeImages(opts)
if err != nil {
fmt.Println("AWS ERROR: ", err)
}
imageMap[*amiID] = *response.Images[0].Name
return *response.Images[0].Name
}
// Looks at the AMI id and figures out the default User
func getDefaultUser(amiName string) string {
switch {
case strings.Contains(amiName, "ubuntu"): // Ubuntu
return "ubuntu"
default: // The rest?
return "ec2-user"
}
}