-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
112 lines (94 loc) · 2.57 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package main
import (
"fmt"
"io/ioutil"
"os"
"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/lambda"
)
const AWS_ID = "<Your AWS ID>"
const AWS_SECRET = "<Your AWS Secret>"
const AWS_TOKEN = "<Your AWS Token>"
const AWS_REGION = "<Your AWS Region>"
func main() {
svc := createAwsSession()
fileName := "zippedFile.zip"
zipFileContents, err := getZipFileContents(fileName)
if err != nil {
return
}
functionName := "<Your function name>"
err = createLambdaFunction(svc, zipFileContents, functionName)
if err != nil {
fmt.Println("Failed to create lambda function")
}
response, err := invokeLambdaFunction(svc, functionName)
if err != nil {
fmt.Println("Failed to execute lambda function")
return
}
fmt.Println(response)
}
func createAwsSession() *lambda.Lambda {
creds := credentials.NewStaticCredentials(AWS_ID, AWS_SECRET, AWS_TOKEN)
svc := lambda.New(session.New(
&aws.Config{
Credentials: creds,
Region: aws.String(AWS_REGION),
}))
return svc
}
func getZipFileContents(zipFileName string) ([]byte, error) {
file, err := os.Open(zipFileName)
if err != nil {
return nil, err
}
fileContents, err := ioutil.ReadAll(file)
if err != nil {
return nil, err
}
return fileContents, nil
}
func invokeLambdaFunction(svc *lambda.Lambda, functionName string) ([]byte, error) {
input := &lambda.InvokeInput{
FunctionName: aws.String(functionName),
Payload: []byte("{}"), // Can modify the payload to your usecase.
}
result, err := svc.Invoke(input)
if err != nil {
return nil, err
}
return result.Payload, err
}
func createLambdaFunction(svc *lambda.Lambda, zipFileContents []byte, functionName string) error {
input := &lambda.CreateFunctionInput{
Code: &lambda.FunctionCode{
ZipFile: zipFileContents,
},
Description: aws.String("Your Code description"),
Environment: &lambda.Environment{
Variables: map[string]*string{
"BUCKET": aws.String("<Yout Bucket Name>"),
"PREFIX": aws.String("inbound"),
},
},
FunctionName: aws.String(functionName),
// The code file should export handler method from index file.
Handler: aws.String("index.handler"),
MemorySize: aws.Int64(256),
Publish: aws.Bool(true),
Role: aws.String("<Your AWS Role>"),
Runtime: aws.String("nodejs12.x"),
Tags: map[string]*string{
"DEPARTMENT": aws.String("Assets"),
},
Timeout: aws.Int64(15),
TracingConfig: &lambda.TracingConfig{
Mode: aws.String("Active"),
},
}
_, err := svc.CreateFunction(input)
return err
}