/
find-instance.go
91 lines (70 loc) · 1.86 KB
/
find-instance.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
package client
import (
"errors"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
)
func (c *Client) FindInstancePrivateIP(instanceId string) (string, error) {
inst, err := c.FindInstance(instanceId)
if err != nil {
return "", err
}
ptr := inst.PrivateIpAddress
return *ptr, nil
}
func (c *Client) FindInstancePublicIP(instanceId string) (string, error) {
inst, err := c.FindInstance(instanceId)
if err != nil {
return "", err
}
ptr := inst.PublicIpAddress
return *ptr, nil
}
func (c *Client) FindInstanceAZ(instanceId string) (string, error) {
inst, err := c.FindInstance(instanceId)
if err != nil {
return "", err
}
ptr := inst.Placement.AvailabilityZone
return *ptr, nil
}
func (c *Client) FindInstance(instanceId string) (*ec2.Instance, error) {
ec2_svc := ec2.New(c.sess)
output_inst, err := ec2_svc.DescribeInstances(&ec2.DescribeInstancesInput{
InstanceIds: []*string{
aws.String(instanceId),
},
})
if err != nil {
handleAWSError(err)
return nil, err
}
instance := output_inst.Reservations[0].Instances[0]
return instance, nil
}
func (c *Client) FindInstanceIDByName(instanceName string) (string, error) {
ec2_svc := ec2.New(c.sess)
output_inst, err := ec2_svc.DescribeInstances(&ec2.DescribeInstancesInput{
Filters: []*ec2.Filter{
{
Name: aws.String("tag:Name"),
Values: []*string{aws.String(instanceName)},
},
{
Name: aws.String("instance-state-name"),
Values: []*string{aws.String("pending"), aws.String("running")},
},
},
})
if err != nil {
handleAWSError(err)
return "", err
}
instance_count := len(output_inst.Reservations)
if instance_count == 0 {
return "", errors.New("No Instances Matched")
} else if instance_count > 1 {
return "", errors.New("Multiple Instances Matched")
}
return *output_inst.Reservations[0].Instances[0].InstanceId, nil
}