-
Notifications
You must be signed in to change notification settings - Fork 0
/
instances.go
113 lines (96 loc) · 2.65 KB
/
instances.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package main
import (
"encoding/json"
"fmt"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
)
type instance struct {
Number int
IP string
Name string
Zone string
}
func parseInstance(element string) (instance, error) {
var instanceParsed instance
if err := json.Unmarshal([]byte(element), &instanceParsed); err != nil {
return instanceParsed, err
}
return instanceParsed, nil
}
func getSliceOfInstances(tags string, displayName string, publicIP bool) ([]string, error) {
var (
i int = 1
sliceOfInstances []string
instanceName string
filterMapsList []*ec2.Filter
)
// Generating a list of instances filters
if tags != "" {
tagsList := strings.Split(tags, ";")
for _, tag := range tagsList {
keyValue := strings.Split(tag, ":")
if len(keyValue) != 2 {
return sliceOfInstances, fmt.Errorf("WrongTagDefinition")
}
values := strings.Split(keyValue[1], ",")
var valuesList []*string
for _, value := range values {
valuesList = append(valuesList, aws.String(value))
}
filterMap := ec2.Filter{
Name: aws.String("tag:" + keyValue[0]),
Values: valuesList,
}
filterMapsList = append(filterMapsList, &filterMap)
}
}
filterMapsList = append(filterMapsList, &ec2.Filter{
Name: aws.String("instance-state-name"),
Values: []*string{aws.String("running")},
})
// Getting instances
awsSession := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
ec2Service := ec2.New(awsSession)
filterParams := &ec2.DescribeInstancesInput{
Filters: filterMapsList,
}
describeInstancesResponce, err := ec2Service.DescribeInstances(filterParams)
if err != nil {
return sliceOfInstances, err
}
// Appending instances to sliceOfInstances
for idx := range describeInstancesResponce.Reservations {
for _, inst := range describeInstancesResponce.Reservations[idx].Instances {
// Getting instance name from Name tag
for _, tag := range inst.Tags {
if *tag.Key == displayName {
instanceName = *tag.Value
}
}
var instanceIP string
if publicIP {
instanceIP = *inst.PublicIpAddress
} else {
instanceIP = *inst.PrivateIpAddress
}
currentInstance := instance{
Number: i,
IP: instanceIP,
Name: instanceName,
Zone: *inst.Placement.AvailabilityZone,
}
currentInstanceString, err := json.Marshal(currentInstance)
if err != nil {
return sliceOfInstances, err
}
sliceOfInstances = append(sliceOfInstances, string(currentInstanceString))
i++
}
}
return sliceOfInstances, nil
}