-
Notifications
You must be signed in to change notification settings - Fork 742
/
ec2wrapper.go
77 lines (65 loc) · 2.12 KB
/
ec2wrapper.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
// package ec2wrapper is used to wrap around the ec2 service APIs
package ec2wrapper
import (
"github.com/aws/amazon-vpc-cni-k8s/pkg/ec2metadatawrapper"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/ec2metadata"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/ec2/ec2iface"
"github.com/golang/glog"
"github.com/pkg/errors"
)
const (
maxRetries = 5
resourceID = "resource-id"
resourceKey = "key"
clusterIDTag = "CLUSTER_ID"
)
// EC2Wrapper is used to wrap around EC2 service APIs to obtain ClusterID from
// the ec2 instance tags
type EC2Wrapper struct {
ec2ServiceClient ec2iface.EC2API
instanceIdentityDocument ec2metadata.EC2InstanceIdentityDocument
}
// New returns an instance of the EC2 wrapper
func NewMetricsClient() (*EC2Wrapper, error) {
metricsSession := session.Must(session.NewSession())
ec2MetadataClient := ec2metadatawrapper.New(nil)
instanceIdentityDocument, err := ec2MetadataClient.GetInstanceIdentityDocument()
if err != nil {
return &EC2Wrapper{}, err
}
ec2ServiceClient := ec2.New(metricsSession, aws.NewConfig().WithMaxRetries(maxRetries).WithRegion(instanceIdentityDocument.Region))
return &EC2Wrapper{
ec2ServiceClient: ec2ServiceClient,
instanceIdentityDocument: instanceIdentityDocument,
}, nil
}
// GetClusterTag is used to retrieve a tag from the ec2 instance
func (e *EC2Wrapper) GetClusterTag(tagKey string) (string, error) {
input := ec2.DescribeTagsInput{
Filters: []*ec2.Filter{
{
Name: aws.String(resourceID),
Values: []*string{
aws.String(e.instanceIdentityDocument.InstanceID),
},
}, {
Name: aws.String(resourceKey),
Values: []*string{
aws.String(tagKey),
},
},
},
}
glog.Info("Calling DescribeTags with key ", tagKey)
results, err := e.ec2ServiceClient.DescribeTags(&input)
if err != nil {
return "", errors.Wrap(err, "GetClusterTag: Unable to obtain EC2 instance tags")
}
if len(results.Tags) < 1 {
return "", errors.Errorf("GetClusterTag: No tag matching key: %s", tagKey)
}
return aws.StringValue(results.Tags[0].Value), nil
}