Add Makefile
[vaultmon/.git] / aws.go
1 package main
2
3 import (
4         "github.com/aws/aws-sdk-go/aws"
5         "github.com/aws/aws-sdk-go/aws/endpoints"
6         "github.com/aws/aws-sdk-go/aws/session"
7         "github.com/aws/aws-sdk-go/service/ec2"
8
9         "errors"
10
11         log "github.com/sirupsen/logrus"
12 )
13
14 var (
15         errInvalidFilter         = errors.New("invalid filter map input")
16         errMissingKeyNameFilter  = errors.New("filter doesn't have 'Name' key")
17         errMissingKeyValueFilter = errors.New("filter doesn't have 'Value' key")
18         errNoExistingInstances   = errors.New("no exisiting instances returned")
19 )
20
21 type Service interface {
22         DescribeInstances(*ec2.DescribeInstancesInput) (*ec2.DescribeInstancesOutput, error)
23 }
24
25 type AWSService struct {
26         service Service
27 }
28
29 func (a *AWSService) GetInstancesPrivateIps(filter map[string]string) ([]string, error) {
30         var name, value string
31         var ok bool
32
33         if filter == nil {
34                 return nil, errInvalidFilter
35         }
36
37         if name, ok = filter["Name"]; !ok {
38                 return nil, errMissingKeyNameFilter
39         }
40
41         if value, ok = filter["Value"]; !ok {
42                 return nil, errMissingKeyValueFilter
43         }
44
45         input := &ec2.DescribeInstancesInput{
46                 Filters: []*ec2.Filter{
47                         {
48                                 Name:   aws.String(name),
49                                 Values: []*string{aws.String(value)},
50                         },
51                 },
52         }
53
54         result, err := a.service.DescribeInstances(input)
55         if err != nil {
56                 log.Debugf("Unable to DescribeInstances using input: %+v", result)
57                 return nil, err
58         }
59
60         nodeIps := make([]string, 0, len(result.Reservations))
61         for _, r := range result.Reservations {
62                 if len(r.Instances) > 0 {
63                         nodeIps = append(nodeIps, *r.Instances[0].PrivateIpAddress)
64                 }
65         }
66
67         if len(nodeIps) == 0 {
68                 return nil, errNoExistingInstances
69         }
70
71         log.Debugf("Found %d private IPs: %v", len(nodeIps), nodeIps)
72
73         return nodeIps, nil
74 }
75
76 func newEC2Provider() *AWSService {
77         return &AWSService{
78                 service: ec2.New(session.Must(session.NewSession(&aws.Config{
79                         Region: aws.String(endpoints.EuCentral1RegionID),
80                 }))),
81         }
82 }