-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimple.go
452 lines (385 loc) · 16.1 KB
/
simple.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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
package main
import (
"fmt"
"github.com/aws/aws-cdk-go/awscdk/v2"
"github.com/aws/constructs-go/constructs/v10"
"github.com/aws/jsii-runtime-go"
beanstalk "github.com/aws/aws-cdk-go/awscdk/v2/awselasticbeanstalk"
"github.com/aws/aws-cdk-go/awscdk/v2/awss3assets"
ec2 "github.com/aws/aws-cdk-go/awscdk/v2/awsec2"
iam "github.com/aws/aws-cdk-go/awscdk/v2/awsiam"
lambda "github.com/aws/aws-cdk-go/awscdk/v2/awslambda"
lambdaes "github.com/aws/aws-cdk-go/awscdk/v2/awslambdaeventsources"
rds "github.com/aws/aws-cdk-go/awscdk/v2/awsrds"
route53 "github.com/aws/aws-cdk-go/awscdk/v2/awsroute53"
targets "github.com/aws/aws-cdk-go/awscdk/v2/awsroute53targets"
s3 "github.com/aws/aws-cdk-go/awscdk/v2/awss3"
s3deployment "github.com/aws/aws-cdk-go/awscdk/v2/awss3deployment"
scheduler "github.com/aws/aws-cdk-go/awscdk/v2/awsscheduler"
secrets "github.com/aws/aws-cdk-go/awscdk/v2/awssecretsmanager"
sqs "github.com/aws/aws-cdk-go/awscdk/v2/awssqs"
cloudfront "github.com/aws/aws-cdk-go/awscdk/v2/awscloudfront"
origins "github.com/aws/aws-cdk-go/awscdk/v2/awscloudfrontorigins"
elbv2 "github.com/aws/aws-cdk-go/awscdk/v2/awselasticloadbalancingv2"
)
type SimpleStackProps struct {
awscdk.StackProps
}
func NewSimpleStack(scope constructs.Construct, id string, props *SimpleStackProps) awscdk.Stack {
var sprops awscdk.StackProps
if props != nil {
sprops = props.StackProps
}
stack := awscdk.NewStack(scope, &id, &sprops)
appName := "MyBackend"
backendDeployBucket := s3.NewBucket(stack, jsii.String("EBDeployBucket"), &s3.BucketProps{
BucketName: jsii.Sprintf("elasticbeanstalk-%s-%s", *env().Region, *env().Account),
ServerAccessLogsPrefix: jsii.String("server_access_log"),
EnforceSSL: jsii.Bool(true),
})
vpc := ec2.NewVpc(stack, jsii.String("VPC-for-SIMPLE"),
&ec2.VpcProps{
MaxAzs: jsii.Number(2),
NatGatewayProvider: ec2.NatInstanceProvider_Instance(&ec2.NatInstanceProps{
InstanceType: ec2.NewInstanceType(jsii.String("t3.small")),
}),
Cidr: jsii.String("10.0.0.0/16"),
SubnetConfiguration: &[]*ec2.SubnetConfiguration{
{
Name: jsii.String("private-with-nat"),
SubnetType: ec2.SubnetType_PRIVATE_WITH_NAT,
},
{
Name: jsii.String("public"),
SubnetType: ec2.SubnetType_PUBLIC,
},
},
},
)
backendDeployment := s3deployment.NewBucketDeployment(stack, jsii.String("DeployZippedBackend"), &s3deployment.BucketDeploymentProps{
Sources: &[]s3deployment.ISource{
s3deployment.Source_Asset(jsii.String("./backend/deployment.zip"), &awss3assets.AssetOptions{}),
},
DestinationBucket: backendDeployBucket,
})
lbSecurityGroup := ec2.NewSecurityGroup(stack, jsii.String("LbSecurityGroup"), &ec2.SecurityGroupProps{
Vpc: vpc,
AllowAllOutbound: jsii.Bool(false),
})
lbPort := 443
lbSecurityGroup.AddEgressRule(
ec2.Peer_Ipv4(jsii.String("0.0.0.0/0")),
ec2.NewPort(&ec2.PortProps{Protocol: ec2.Protocol_TCP, FromPort: jsii.Number(lbPort), ToPort: jsii.Number(lbPort)}),
jsii.String(""),
jsii.Bool(true),
)
lbSecurityGroup.AddIngressRule(
ec2.Peer_Ipv4(jsii.String("0.0.0.0/0")),
ec2.NewPort(&ec2.PortProps{Protocol: ec2.Protocol_TCP, FromPort: jsii.Number(lbPort), ToPort: jsii.Number(lbPort)}),
jsii.String(""),
jsii.Bool(true),
)
backendSecurityGroup := ec2.NewSecurityGroup(stack, jsii.String("BackendSecurityGroup"), &ec2.SecurityGroupProps{
Vpc: vpc,
AllowAllOutbound: jsii.Bool(false),
})
backendSecurityGroup.AddEgressRule(
ec2.Peer_Ipv4(jsii.String("0.0.0.0/0")),
ec2.NewPort(&ec2.PortProps{Protocol: ec2.Protocol_TCP, FromPort: jsii.Number(8000), ToPort: jsii.Number(8000)}),
jsii.String("Allow outgoing traffic over port 8000"),
jsii.Bool(true),
)
backendSecurityGroup.Connections().
AllowFrom(
ec2.NewConnections(&ec2.ConnectionsProps{SecurityGroups: &[]ec2.ISecurityGroup{lbSecurityGroup}}),
ec2.NewPort(&ec2.PortProps{Protocol: ec2.Protocol_TCP, ToPort: jsii.Number(8000)}),
jsii.String(""),
)
databaseSecurityGroup := ec2.NewSecurityGroup(stack, jsii.String("DBSecurityGroup"), &ec2.SecurityGroupProps{
Vpc: vpc,
AllowAllOutbound: jsii.Bool(false),
})
databaseSecurityGroup.Connections().
AllowFrom(
ec2.NewConnections(&ec2.ConnectionsProps{SecurityGroups: &[]ec2.ISecurityGroup{lbSecurityGroup}}),
ec2.NewPort(&ec2.PortProps{Protocol: ec2.Protocol_TCP, ToPort: jsii.Number(5432)}),
jsii.String(""),
)
// CREATING POSTGRES (RDS) DATABASE
dbCredentialsName := fmt.Sprintf("%s-database-credentials", "my-backend")
/*
si potrebbe utilizzare uno strumento come mozilla sops,
per gestire i secrets a partire dai sorgenti
*/
secrets.NewSecret(stack, jsii.Sprintf("%s-DBCredentialsSecret", "my-backend"), &secrets.SecretProps{
SecretName: jsii.String(dbCredentialsName),
GenerateSecretString: &secrets.SecretStringGenerator{
GenerateStringKey: jsii.String("password"),
ExcludePunctuation: jsii.Bool(true),
IncludeSpace: jsii.Bool(false),
SecretStringTemplate: jsii.String(`
{
"username": "admin",
}`),
},
})
// engine := rds.DatabaseInstanceEngine_POSTGRES()
// instanceType := ec2.NewInstanceType(jsii.String("t3.small"))
// dbPort := 5432
zones := *(vpc.AvailabilityZones())
firstAZ := zones[0]
secondAZ := zones[1]
masterDB := rds.NewDatabaseInstance(stack, jsii.String("MyMasterDB"), &rds.DatabaseInstanceProps{
Vpc: vpc,
SecurityGroups: &[]ec2.ISecurityGroup{databaseSecurityGroup},
AvailabilityZone: firstAZ,
})
_ = rds.NewDatabaseInstanceReadReplica(stack, jsii.String("MyReplicaDB"), &rds.DatabaseInstanceReadReplicaProps{
Vpc: vpc,
SourceDatabaseInstance: masterDB,
AvailabilityZone: secondAZ,
})
// CREATING THE ELASTIC BEANSTALK APPLICATION
backend := beanstalk.NewCfnApplication(stack, jsii.String(appName), &beanstalk.CfnApplicationProps{
ApplicationName: jsii.String(appName),
})
/*
Nel caso servisse usare le variabili d'ambiente per connettersi al database
*/
// ['aws:elasticbeanstalk:hostmanager', 'LogPublicationControl', 'true'], // Enable Logging to be stored in S3
// ['aws:elasticbeanstalk:application:environment', 'RDS_HOSTNAME', rdsInstance.dbInstanceEndpointAddress], // Define Env Variable for HOSTNAME
// ['aws:elasticbeanstalk:application:environment', 'RDS_PORT', rdsInstance.dbInstanceEndpointPort], // Define Env Variable for PORT
// ['aws:elasticbeanstalk:application:environment', 'RDS_USERNAME', props.databaseSettings.dbWebUsername], // Define Env Variable for DB username to connect (web tier)
// ['aws:elasticbeanstalk:application:environment', 'RDS_DATABASE', props.databaseSettings.dbName], // Define Env Variable for DB name (defined when RDS db created)
// ['aws:elasticbeanstalk:application:environment', 'REGION', this.region],
publicSubnets := vpc.SelectSubnets(&ec2.SubnetSelection{SubnetType: ec2.SubnetType_PUBLIC}).Subnets
privateBackendSubnets := vpc.SelectSubnets(&ec2.SubnetSelection{SubnetType: ec2.SubnetType_PRIVATE_WITH_NAT}).Subnets
backendSubnets := createCommaSeparatedList(privateBackendSubnets)
lbSubnets := createCommaSeparatedList(publicSubnets)
optionSetting := []beanstalk.CfnEnvironment_OptionSettingProperty{
// Beanstalk crea autonomamente il load balancer
{
Namespace: jsii.String("aws:elasticbeanstalk:environment"),
OptionName: jsii.String("LoadBalancerType"),
Value: jsii.String("application"),
},
{
Namespace: jsii.String("aws:autoscaling:launchconfiguration"),
OptionName: jsii.String("InstanceType"),
Value: jsii.String("t2.small"),
},
{
Namespace: jsii.String("aws:autoscaling:launchconfiguration"),
OptionName: jsii.String("IamInstanceProfile"),
// https://stackoverflow.com/a/55033663/6894670
Value: jsii.String("aws-elasticbeanstalk-ec2-role"),
},
{
Namespace: jsii.String("aws:autoscaling:launchconfiguration"),
OptionName: jsii.String("SecurityGroups"),
Value: backendSecurityGroup.SecurityGroupId(),
},
{
Namespace: jsii.String("aws:ec2:vpc"),
OptionName: jsii.String("VPCId"),
Value: vpc.VpcId(),
},
{
Namespace: jsii.String("aws:ec2:vpc"),
OptionName: jsii.String("Subnets"),
Value: jsii.String(backendSubnets),
},
{
Namespace: jsii.String("aws:ec2:vpc"),
OptionName: jsii.String("ELBSubnets"),
Value: jsii.String(lbSubnets),
},
// Https settings
{
Namespace: jsii.String("aws:elbv2:listener:default"),
OptionName: jsii.String("ListenerEnabled"),
Value: jsii.String("false"),
},
{
Namespace: jsii.String("aws:elbv2:listener:443"),
OptionName: jsii.String("ListenerEnabled"),
Value: jsii.String("true"),
},
{
Namespace: jsii.String("aws:elbv2:listener:443"),
OptionName: jsii.String("SSLCertificateArns"),
Value: nil,
},
{
Namespace: jsii.String("aws:elbv2:listener:443"),
OptionName: jsii.String("SSLPolicy"),
Value: nil,
},
{
Namespace: jsii.String("aws:elbv2:listener:443"),
OptionName: jsii.String("Protocol"),
Value: jsii.String("HTTPS"),
},
}
backendVersion := beanstalk.NewCfnApplicationVersion(stack, backend.ApplicationName(), &beanstalk.CfnApplicationVersionProps{
ApplicationName: jsii.String(appName),
SourceBundle: beanstalk.CfnApplicationVersion_SourceBundleProperty{
S3Bucket: backendDeployBucket.BucketName(),
S3Key: jsii.Sprintf("deployment.zip"),
},
})
btEnv := beanstalk.NewCfnEnvironment(stack, jsii.String("my-environment"), &beanstalk.CfnEnvironmentProps{
ApplicationName: backend.ApplicationName(),
OptionSettings: optionSetting,
VersionLabel: backendVersion.Ref(),
})
// Frontend
frontendDeployBucket := s3.NewBucket(stack, jsii.String("FrontendDeployBucket"), &s3.BucketProps{
BucketName: jsii.Sprintf("elasticbeanstalk-frontend-%s-%s", *env().Region, *env().Account),
ServerAccessLogsPrefix: jsii.String("server_access_log"),
EnforceSSL: jsii.Bool(true),
})
frontendDeployment := s3deployment.NewBucketDeployment(stack, jsii.String("DeployZippedBackend"), &s3deployment.BucketDeploymentProps{
Sources: &[]s3deployment.ISource{
s3deployment.Source_Asset(jsii.String("./frontend/*"), &awss3assets.AssetOptions{}),
},
DestinationBucket: frontendDeployBucket,
})
// retrive beanstalk application load balancer
alb := elbv2.ApplicationLoadBalancer_FromLookup(stack, jsii.String("ALB"), &elbv2.ApplicationLoadBalancerLookupOptions{
LoadBalancerTags: &map[string]*string{
"elasticbeanstalk:environment-name": btEnv.EnvironmentName(),
},
})
dist := cloudfront.NewDistribution(stack, jsii.String("SimpleFrontend"), &cloudfront.DistributionProps{
DefaultBehavior: &cloudfront.BehaviorOptions{
Origin: origins.NewS3Origin(frontendDeployBucket, &origins.S3OriginProps{}),
AllowedMethods: cloudfront.AllowedMethods_ALLOW_ALL(),
ViewerProtocolPolicy: cloudfront.ViewerProtocolPolicy_REDIRECT_TO_HTTPS,
},
AdditionalBehaviors: &map[string]*cloudfront.BehaviorOptions{
"/api/": {
Origin: origins.NewLoadBalancerV2Origin(alb, &origins.LoadBalancerV2OriginProps{}),
AllowedMethods: cloudfront.AllowedMethods_ALLOW_ALL(),
ViewerProtocolPolicy: cloudfront.ViewerProtocolPolicy_REDIRECT_TO_HTTPS,
},
},
})
zone := route53.HostedZone_FromHostedZoneAttributes(stack, jsii.String("SimpleStack"), &route53.HostedZoneAttributes{
ZoneName: jsii.String("my-zone.simple.stack.com"),
HostedZoneId: jsii.String("MyHostedZoneId"),
})
_ = route53.NewARecord(stack, jsii.String("CDNARecord"), &route53.ARecordProps{
Zone: zone,
Target: route53.RecordTarget_FromAlias(targets.NewCloudFrontTarget(dist)),
})
// FIXME: add certificate management
// async tasks
type functionSpec struct {
src string
runtime lambda.Runtime
}
dlq := sqs.NewQueue(stack, jsii.String("MyDLQ"), &sqs.QueueProps{RetentionPeriod: awscdk.Duration_Days(jsii.Number(4))})
triggers := sqs.NewQueue(stack, jsii.String("MyAsyncTrigger"), &sqs.QueueProps{
DeadLetterQueue: &sqs.DeadLetterQueue{
Queue: dlq,
},
})
functions := map[string]functionSpec{
"lambda1": {src: "lambda1", runtime: lambda.Runtime_PYTHON_3_11()},
}
dlqLambda := lambda.NewFunction(stack, jsii.String("MyDLQLambda"), &lambda.FunctionProps{
Code: lambda.AssetCode_FromAsset(jsii.String("./dlqlambda"), &awss3assets.AssetOptions{}),
Runtime: lambda.Runtime_PYTHON_3_11(),
})
dlqLambda.AddEnvironment(jsii.String("SQS_ARN"), triggers.QueueArn(), &lambda.EnvironmentOptions{})
dlqLambda.AddEnvironment(jsii.String("DLQ_ARN"), triggers.QueueArn(), &lambda.EnvironmentOptions{})
for name, spec := range functions {
f := lambda.NewFunction(stack, jsii.Sprintf("MyFunction%s", name), &lambda.FunctionProps{
Code: lambda.AssetCode_FromAsset(jsii.Sprintf("./tasks/%s", spec.src), &awss3assets.AssetOptions{}),
Runtime: spec.runtime,
})
es := lambdaes.NewSqsEventSource(triggers, &lambdaes.SqsEventSourceProps{
// aggiungere gestione filtri per guidare la funzione da richiamare
Filters: &[]*map[string]interface{}{},
})
f.AddEventSource(es)
}
// aggiungo gestione della dead letter queue con uno scheduler
// creazione iam role
schedulerRole := iam.NewRole(stack, jsii.String("EventBridgeToSQSRole"), &iam.RoleProps{
AssumedBy: iam.NewServicePrincipal(jsii.String("scheduler.amazonaws.com"), &iam.ServicePrincipalOpts{}),
InlinePolicies: &map[string]iam.PolicyDocument{
"invoke_target": iam.NewPolicyDocument(&iam.PolicyDocumentProps{
Statements: &[]iam.PolicyStatement{
iam.NewPolicyStatement(&iam.PolicyStatementProps{
Actions: &[]*string{jsii.String("lambda:InvokeFunction")},
Resources: &[]*string{dlqLambda.FunctionArn()},
Effect: iam.Effect_ALLOW,
}),
},
}),
},
})
scheduler.NewCfnSchedule(stack, jsii.String("MyScheduler"), &scheduler.CfnScheduleProps{
FlexibleTimeWindow: &scheduler.CfnSchedule_FlexibleTimeWindowProperty{
Mode: jsii.String("OFF"),
},
Description: jsii.String("Invoke the DLQ lambda between Sunday to Thursday at 23:00 Rome (Italy) time"),
ScheduleExpression: jsii.String("cron(0 23 ? * SUN-THU *)"),
ScheduleExpressionTimezone: jsii.String("Europe/Rome"),
Target: &scheduler.CfnSchedule_TargetProperty{
Arn: dlqLambda.FunctionArn(),
RoleArn: schedulerRole.RoleArn(),
Input: jsii.String("This message was published using EventBridge Scheduler!"),
},
})
backendVersion.Node().AddDependency(backendDeployment)
backendVersion.Node().AddDependency(frontendDeployment)
backendVersion.AddDependsOn(backend)
return stack
}
func main() {
defer jsii.Close()
app := awscdk.NewApp(nil)
NewSimpleStack(app, "SimpleStack", &SimpleStackProps{
awscdk.StackProps{
Env: env(),
},
})
app.Synth(nil)
}
// env determines the AWS environment (account+region) in which our stack is to
// be deployed. For more information see: https://docs.aws.amazon.com/cdk/latest/guide/environments.html
func env() *awscdk.Environment {
// If unspecified, this stack will be "environment-agnostic".
// Account/Region-dependent features and context lookups will not work, but a
// single synthesized template can be deployed anywhere.
//---------------------------------------------------------------------------
return nil
// Uncomment if you know exactly what account and region you want to deploy
// the stack to. This is the recommendation for production stacks.
//---------------------------------------------------------------------------
// return &awscdk.Environment{
// Account: jsii.String("123456789012"),
// Region: jsii.String("us-east-1"),
// }
// Uncomment to specialize this stack for the AWS Account and Region that are
// implied by the current CLI configuration. This is recommended for dev
// stacks.
//---------------------------------------------------------------------------
// return &awscdk.Environment{
// Account: jsii.String(os.Getenv("CDK_DEFAULT_ACCOUNT")),
// Region: jsii.String(os.Getenv("CDK_DEFAULT_REGION")),
// }
}
func createCommaSeparatedList(subnets *[]ec2.ISubnet) string {
result := ""
for index, subnet := range *subnets {
if index > 0 {
result += ", "
}
result += *subnet.SubnetId()
}
return result
}