/
main.go
82 lines (73 loc) · 2.05 KB
/
main.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
package instancefilter
import (
"fmt"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
)
// Filter is the default struct to hold all of the ec2.Filters that would be
// constructed based on the flags passed.
type Filter struct {
f []*ec2.Filter
}
// ByRunnin will add a filter to only gather instances that are running.
func (f *Filter) ByRunning() *Filter {
f.f = append(f.f, &ec2.Filter{
Name: aws.String("instance-state-name"),
Values: []*string{
aws.String("running"),
},
})
return f
}
// BySubnet will add a filter to the struct for searching within a given
// subnet. Multiple subnets would be given comma separated.
func (f *Filter) BySubnet(s []string) *Filter {
f.f = append(f.f, &ec2.Filter{
Name: aws.String("subnet-id"),
Values: aws.StringSlice(s),
})
return f
}
// ByAvailabilityZone will add a filter to the struct for searching
// within a given availability-zone. Multiple availability-zones would
// be comma separated.
func (f *Filter) ByAvailabilityZone(s []string) *Filter {
f.f = append(f.f, &ec2.Filter{
Name: aws.String("availability-zone"),
Values: aws.StringSlice(s),
})
return f
}
// ByInstance will add a filter to the struct for searching
// by instance-id.Multiple instance-id's would be comma separated.
func (f *Filter) ByInstance(s []string) *Filter {
f.f = append(f.f, &ec2.Filter{
Name: aws.String("instance-id"),
Values: aws.StringSlice(s),
})
return f
}
// ByTag will add a filter to the struct for searching by tag.
// Multiple tags are passed comma separated, each
// tag is represented key=value.
// example: team=devops
func (f *Filter) ByTag(s []string) *Filter {
for _, t := range s {
tag := strings.Split(t, "=")
tKey := fmt.Sprintf("tag:%s", tag[0])
f.f = append(f.f, &ec2.Filter{
Name: aws.String(tKey),
Values: []*string{
aws.String(tag[1]),
},
})
}
return f
}
// Build will construct the AWS ec2 Filter for gathering instances
// based on given flag.
// Returns a list of ec2 filters
func (f *Filter) Build() []*ec2.Filter {
return f.f
}