forked from aws-samples/aws-dynamodb-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenableAutoscaling.go
270 lines (226 loc) · 7.76 KB
/
enableAutoscaling.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
package main
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/aws/aws-sdk-go/service/applicationautoscaling"
"encoding/json"
"fmt"
)
// StatementEntry will dictate what this policy allows or doesn't allow.
type StatementEntry struct {
Action []string
Effect string
Resource string
}
// PrincipalEntry will dictate what this policy allows or doesn't allow.
type PrincipalEntry struct {
Service []string
}
// PrinciplaStatementEntry will dictate what this policy allows or doesn't allow.
type PrinciplaStatementEntry struct {
Action []string
Effect string
Principal PrincipalEntry
}
// AssumePolicyDocument is our definition of our policies to be uploaded to IAM.
type AssumePolicyDocument struct {
Statement []StatementEntry
Version string
}
// PolicyDocument is our definition of our policies to be uploaded to IAM.
type PolicyDocument struct {
Statement []PrinciplaStatementEntry
Version string
}
var awsRegion = "us-west-2"
var policyName = fmt.Sprintf("%s_%s", tableName, "TableScalingPolicy")
var resourceID = fmt.Sprintf("%s%s", "table/", tableName)
var readDimension = "dynamodb:table:ReadCapacityUnits"
var readMetric = "DynamoDBReadCapacityUtilization"
var roleName = fmt.Sprintf("%s_%s", tableName, "TableScalingRole")
var tableName = "Music"
var writeDimension = "dynamodb:table:WriteCapacityUnits"
var writeMetric = "DynamoDBWriteCapacityUtilization"
func getPolicyDocument() (string, error) {
policy := AssumePolicyDocument{
Version: "2012-10-17",
Statement: [] StatementEntry{
StatementEntry{
Effect: "Allow",
Action: []string{
"dynamodb:DescribeTable",
"dynamodb:UpdateTable",
},
Resource: "*",
},
StatementEntry{
Effect: "Allow",
Action: []string{
"cloudwatch:PutMetricAlarm",
"cloudwatch:DescribeAlarms",
"cloudwatch:GetMetricStatistics",
"cloudwatch:SetAlarmState",
"cloudwatch:DeleteAlarms",
},
Resource: "*",
},
},
}
marshalledPolicy, err := json.Marshal(&policy)
if err != nil {
return "", err
}
return string(marshalledPolicy), nil
}
func getAssumeRolePolicyDocument() (string, error) {
policy := PolicyDocument{
Version: "2012-10-17",
Statement: []PrinciplaStatementEntry {
PrinciplaStatementEntry{
Effect: "Allow",
Action: []string{
"sts:AssumeRole",
},
Principal: PrincipalEntry{
Service: []string{
"ec2.amazonaws.com",
},
},
},
},
}
marshalledPolicy, err := json.Marshal(&policy)
if err != nil {
return "", err
}
return string(marshalledPolicy), nil
}
func getSession() (*session.Session) {
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
// Provide SDK Config options, such as Region and Endpoint
Config: aws.Config{
Region: aws.String(awsRegion),
},
}))
return sess
}
func createRole(iamClient *iam.IAM) (*iam.CreateRoleOutput, error) {
policy, err := getAssumeRolePolicyDocument()
if err != nil {
fmt.Println("Error creating Assume Role Policy Document")
return nil, err
}
roleOutput, err := iamClient.CreateRole(&iam.CreateRoleInput{
AssumeRolePolicyDocument: aws.String(policy),
Path: aws.String("/"),
RoleName: &roleName,
})
if err != nil {
fmt.Println("Error creating IAM Role", err)
return nil, err
}
fmt.Println("Role created ...")
return roleOutput, nil
}
func createPolicy(iamClient *iam.IAM) (string, error) {
policyConfig, err := getPolicyDocument()
if err != nil {
fmt.Println("Error creating Policy Document", err)
return "", err
}
policy, err := iamClient.CreatePolicy(&iam.CreatePolicyInput{
PolicyDocument: aws.String(policyConfig),
PolicyName: aws.String(policyName),
})
if err != nil {
fmt.Println("Error creating Policy Document")
return "", err
}
policyArn := *policy.Policy.Arn
fmt.Println("Policy created ...")
return policyArn, nil
}
func attachPolicy(
iamClient *iam.IAM,
policyArn string,
roleName string,
) {
iamClient.AttachRolePolicy(&iam.AttachRolePolicyInput{
RoleName: aws.String(roleName),
PolicyArn: aws.String(policyArn),
})
fmt.Println("Policy attached to role ...")
}
func registerScalableTarget(
autoscalingClient *applicationautoscaling.ApplicationAutoScaling,
dimension string,
roleARN string,
) {
input := &applicationautoscaling.RegisterScalableTargetInput{
MaxCapacity: aws.Int64(100),
MinCapacity: aws.Int64(1),
ResourceId: aws.String(resourceID),
RoleARN: aws.String(roleARN),
ScalableDimension: aws.String(dimension),
ServiceNamespace: aws.String("dynamodb"),
}
autoscalingClient.RegisterScalableTarget(input)
}
func putScalingPolicy (
autoscalingClient *applicationautoscaling.ApplicationAutoScaling,
dimension string,
metricType string,
) {
policyInput := &applicationautoscaling.PutScalingPolicyInput{
PolicyName: aws.String(policyName),
PolicyType: aws.String("TargetTrackingScaling"),
ResourceId: aws.String(resourceID),
ScalableDimension: aws.String(dimension),
ServiceNamespace: aws.String("dynamodb"),
TargetTrackingScalingPolicyConfiguration: &applicationautoscaling.TargetTrackingScalingPolicyConfiguration{
DisableScaleIn: aws.Bool(true),
PredefinedMetricSpecification: &applicationautoscaling.PredefinedMetricSpecification{
PredefinedMetricType: aws.String(metricType),
},
ScaleOutCooldown: aws.Int64(150),
ScaleInCooldown: aws.Int64(150),
TargetValue: aws.Float64(50),
},
}
autoscalingClient.PutScalingPolicy(policyInput)
}
func registerAutoscaling(roleARN string) {
autoscalingClient := applicationautoscaling.New(getSession())
registerScalableTarget(autoscalingClient, readDimension, roleARN)
fmt.Println("Read scalable target registered ...")
registerScalableTarget(autoscalingClient, writeDimension, roleARN)
fmt.Println("Write scalable target registered ...")
putScalingPolicy(autoscalingClient, readDimension, readMetric)
fmt.Println("Read scaling policy updated ...")
putScalingPolicy(autoscalingClient, writeDimension, writeMetric)
fmt.Println("Write scaling policy updated ...")
}
func enableAutoscaling() error {
iamClient := iam.New(getSession())
// Perform IAM requirements before being able to alter the table
roleOutput, err := createRole(iamClient)
if err != nil {
fmt.Println("Error creating pre requisites", err)
return err
}
policyArn, err := createPolicy(iamClient)
if err != nil {
fmt.Println("Error creating pre requisites", err)
return err
}
attachPolicy(iamClient, policyArn, *roleOutput.Role.RoleName)
registerAutoscaling(*roleOutput.Role.Arn)
return nil
}
func main() {
fmt.Println("Updating table to enable autoscaling ...")
enableAutoscaling()
fmt.Println("Finished ...")
}