-
Notifications
You must be signed in to change notification settings - Fork 0
/
instance.go
52 lines (45 loc) · 1.15 KB
/
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
package instance
import (
"fmt"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/psanford/aws-buddy/config"
)
func InstancesFromDesc(desc *ec2.DescribeInstancesOutput) []ec2.Instance {
out := make([]ec2.Instance, 0)
for _, res := range desc.Reservations {
for _, instPtr := range res.Instances {
inst := *instPtr
out = append(out, inst)
}
}
return out
}
func Get(instanceID string) (*ec2.Instance, error) {
svc := ec2.New(config.Session())
input := ec2.DescribeInstancesInput{
Filters: []*ec2.Filter{
{
Name: aws.String("instance-id"),
Values: []*string{&instanceID},
},
},
}
output, err := svc.DescribeInstances(&input)
if err != nil {
return nil, fmt.Errorf("DescribeInstances err: %w", err)
}
instances := InstancesFromDesc(output)
if len(instances) < 1 {
return nil, fmt.Errorf("No instance found")
}
if len(instances) > 1 {
ids := make([]string, 0, len(instances))
for _, inst := range instances {
ids = append(ids, *inst.InstanceId)
}
return nil, fmt.Errorf("Multiple instances found found: %s", strings.Join(ids, ","))
}
return &instances[0], nil
}