/
main.go
92 lines (78 loc) · 2.41 KB
/
main.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
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ssm"
"github.com/elastic/go-elasticsearch/v8"
"log"
"strings"
"time"
)
type spotEventRecord struct {
EventVersion string `json:"version"`
EventId string `json:"id"`
EventDetailType string `json:"detail-type"`
EventSource string `json:"source"`
Account string `json:"account"`
EventTime time.Time `json:"time"`
AwsRegion string `json:"region"`
Resources []string `json:"resources"`
EventDetails eventDetails `json:"detail"`
}
type eventDetails struct {
InstanceID string `json:"instance-id"`
InstanceAction string `json:"instance-action"`
}
var secopsEsUrl = "http://secopsEsUrl:80"
var day = time.Now().Local().Format("2006-01-02")
var esIndex = fmt.Sprintf("spot-events-%s", day)
func main() {
lambda.Start(HandleLambdaEvent)
}
func HandleLambdaEvent(ctx context.Context, eventInfo spotEventRecord) {
// get credential from ssm
mySession := session.Must(session.NewSession())
svc := ssm.New(mySession, aws.NewConfig().WithRegion("us-east-1"))
var username, password string
params := []string{"tf-spotevictioneventLambda-username", "tf-spotevictioneventLambda-password"}
for _, param := range params {
sessionInput := ssm.GetParameterInput{}
sessionInput.SetName(param)
paramOutput, err := svc.GetParameter(&sessionInput)
if err != nil {
log.Fatalf("Error getting %s from SSM: %s", param, err)
}
switch param {
case "tf-spotevictioneventLambda-username":
username = *(paramOutput.Parameter).Value
case "tf-spotevictioneventLambda-password":
password = *(paramOutput.Parameter).Value
}
}
cfg := elasticsearch.Config{
Username: username,
Password: password,
Addresses: []string{
secopsEsUrl,
},
}
es, err := elasticsearch.NewClient(cfg)
if err != nil {
log.Fatalf("Error creating the client: %s", err)
}
// create index content
dataJSON, err := json.Marshal(eventInfo)
if err != nil {
log.Fatalf("Error from converting event info to JSON: %s", err)
}
js := string(dataJSON)
index, err := es.Index(esIndex, strings.NewReader(js), es.Index.WithPretty(), es.Index.WithContext(ctx))
if err != nil {
log.Fatalf("Error occurs when creating index: %s", err)
}
fmt.Printf(index.String())
}