-
Notifications
You must be signed in to change notification settings - Fork 0
/
ec2.go
97 lines (80 loc) · 2.02 KB
/
ec2.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
package goqueryaws
import (
"fmt"
"strings"
"encoding/json"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
)
/*
GetInstancesByTag queries AWS EC2 by tags and returns a slice of JSON
encoded service.ec2.Instance.
*/
func GetInstancesByTag(tagKey string, tagValue string) ([][]byte, error) {
// see https://github.com/aws/aws-sdk-go/blob/master/aws/session/session.go#L30-L33
// for session struct
sess := session.Must(session.NewSession())
ec2Svc := ec2.New(sess)
params := &ec2.DescribeInstancesInput{
Filters: []*ec2.Filter{
{
Name: aws.String(strings.Join([]string{"tag", tagKey}, ":")),
Values: []*string{
aws.String(tagValue),
},
},
},
}
result, err := ec2Svc.DescribeInstances(params)
if err != nil {
return nil, fmt.Errorf("failed to describe instances with %s: %v",
params, err)
}
// instances: slice of JSON encoded service.ec2.Instance
var instances [][]byte
for _, rsv := range result.Reservations {
for _, inst := range rsv.Instances {
instance, err := json.Marshal(inst)
if err != nil {
// Todo: count the errors then return it as an error.
}
instances = append(instances, instance)
}
}
return instances, nil
}
/*
GetAllTags retrieves all tags for the specified resource type.
*/
func GetAllTags(resource_type string) ([]*ec2.TagDescription, error) {
sess := session.Must(session.NewSession())
ec2Svc := ec2.New(sess)
params := &ec2.DescribeTagsInput{
Filters: []*ec2.Filter{
{
Name: aws.String("resource-type"),
Values: []*string{
aws.String(resource_type),
},
},
},
}
var tags []*ec2.TagDescription
err := ec2Svc.DescribeTagsPages(params,
func(page *ec2.DescribeTagsOutput, lastPage bool) bool {
for _, tag := range page.Tags {
tags = append(tags, tag)
}
if lastPage {
return false
} else {
return true
}
})
if err != nil {
return nil, fmt.Errorf("failed to describe tags pages with %s: %v",
params, err)
}
return tags, nil
}