-
Notifications
You must be signed in to change notification settings - Fork 2
/
aws.go
91 lines (75 loc) · 2.27 KB
/
aws.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 aws
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/sensu/sensu-plugins-go-library/sensu"
"log"
)
var (
describeInstanceStatusIncludeAllInstances = true
)
type Config struct {
sensu.PluginConfig
AwsAccessKeyId string
AwsSecretKey string
AwsRegion string
AwsInstanceId string
//AwsAccounts string
AllowedInstanceStates string
Timeout uint64
// Computed from the input
AwsAccountsMap map[string]bool
AllowedInstanceStatesMap map[string]bool
}
type Handler struct {
config *Config
awsSession *session.Session
ec2Service *ec2.EC2
}
func NewHandler(config *Config) (*Handler, error) {
handler := Handler{
config: config,
}
err := handler.initAws()
if err != nil {
return nil, fmt.Errorf("error initializing aws handler: %s", err)
}
return &handler, nil
}
func (awsHandler *Handler) initAws() error {
log.Println("Creating AWS session...")
var err error
creds := credentials.NewStaticCredentials(awsHandler.config.AwsAccessKeyId, awsHandler.config.AwsSecretKey, "")
awsHandler.awsSession, err = session.NewSession(&aws.Config{
Region: aws.String(awsHandler.config.AwsRegion),
Credentials: creds,
})
if err != nil {
return err
}
log.Println("Session created!")
awsHandler.ec2Service = ec2.New(awsHandler.awsSession)
return nil
}
func (awsHandler *Handler) GetInstanceState() (string, error) {
instanceId := awsHandler.config.AwsInstanceId
log.Printf("Retrieving AWS instance state for %s\n", instanceId)
request := &ec2.DescribeInstanceStatusInput{
InstanceIds: []*string{aws.String(instanceId)},
IncludeAllInstances: &describeInstanceStatusIncludeAllInstances,
}
response, err := awsHandler.ec2Service.DescribeInstanceStatus(request)
if err != nil {
return "", fmt.Errorf("error getting instance state for %s: %s", instanceId, err)
}
instanceStatuses := response.InstanceStatuses
if len(instanceStatuses) == 0 {
return "", fmt.Errorf("could not get status for %s", instanceId)
} else if len(instanceStatuses) > 1 {
return "", fmt.Errorf("more than one instance found for %s", instanceId)
}
return *instanceStatuses[0].InstanceState.Name, nil
}