/
ec2info.go
97 lines (82 loc) · 2.1 KB
/
ec2info.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 awsec2
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/golang/glog"
"github.com/cloudstax/firecamp/common"
)
const (
regionFilterName = "region-name"
)
// Ec2Info implements server.Info
type Ec2Info struct {
instanceID string
privateIP string
vpcID string
az string
region string
regionAZs []string
}
// NewEc2Info creates a Ec2Info instance
func NewEc2Info(sess *session.Session) (*Ec2Info, error) {
instanceID, err := GetLocalEc2InstanceID()
if err != nil {
glog.Errorln("GetLocalEc2InstanceID error", err)
return nil, err
}
svc := ec2.New(sess)
params := &ec2.DescribeInstancesInput{
InstanceIds: []*string{
aws.String(instanceID),
},
}
resp, err := svc.DescribeInstances(params)
if err != nil {
glog.Errorln("DescribeInstances error", err, "instanceID", instanceID)
return nil, err
}
if len(resp.Reservations) != 1 {
glog.Errorln("DescribeInstances expect 1 Reservations, but got", len(resp.Reservations), resp)
return nil, common.ErrInternal
}
if len(resp.Reservations[0].Instances) != 1 {
glog.Errorln("DescribeInstances expect 1 instance, but got", len(resp.Reservations[0].Instances), resp)
return nil, common.ErrInternal
}
instance := resp.Reservations[0].Instances[0]
az := *(instance.Placement.AvailabilityZone)
// az must be like us-west-1c, get region from it
region := az[:len(az)-1]
azs, err := GetRegionAZs(region, sess)
if err != nil {
return nil, err
}
s := &Ec2Info{
instanceID: instanceID,
privateIP: *(instance.PrivateIpAddress),
vpcID: *(instance.VpcId),
az: az,
region: region,
regionAZs: azs,
}
return s, nil
}
func (s *Ec2Info) GetPrivateIP() string {
return s.privateIP
}
func (s *Ec2Info) GetLocalAvailabilityZone() string {
return s.az
}
func (s *Ec2Info) GetLocalRegion() string {
return s.region
}
func (s *Ec2Info) GetLocalInstanceID() string {
return s.instanceID
}
func (s *Ec2Info) GetLocalVpcID() string {
return s.vpcID
}
func (s *Ec2Info) GetLocalRegionAZs() []string {
return s.regionAZs
}