-
Notifications
You must be signed in to change notification settings - Fork 0
/
cf_template.yml
957 lines (877 loc) · 33 KB
/
cf_template.yml
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
AWSTemplateFormatVersion: '2010-09-09'
Parameters:
OpenSearchMasterUserName:
Description: Amazon OpenSearch Service - Username
Default: "aosadmin"
Type: String
AssetsBucketName:
Description: Assets bucket name
Type: String
KdaAppKey:
Description: Object key for Flink application file
Type: String
Default: "ClickstreamProcessor-1.0.jar"
LatestAmiId:
Type: 'AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>'
Default: '/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2'
Mappings:
SubnetConfig:
VPC:
CIDR: '10.0.0.0/16'
PublicOne:
CIDR: '10.0.0.0/24'
PrivateSubnetMSKOne:
CIDR: '10.0.1.0/24'
PrivateSubnetMSKTwo:
CIDR: '10.0.2.0/24'
PrivateSubnetMSKThree:
CIDR: '10.0.3.0/24'
AWSInstanceType2Arch:
t2.small:
Arch: HVM64
AWSRegionArch2AMI:
us-east-1:
HVM64: ami-03ededff12e34e59e
us-east-2:
HVM64: ami-0c7478fd229861c57
us-west-1:
HVM64: ami-06542a822d33e2e40
us-west-2:
HVM64: ami-0b36cd6786bcfe120
sa-east-1:
HVM64: ami-00d10ca79f70a302a
Resources:
VPC:
Type: AWS::EC2::VPC
Properties:
EnableDnsSupport: true
EnableDnsHostnames: true
CidrBlock: !FindInMap [ 'SubnetConfig', 'VPC', 'CIDR' ]
Tags:
- Key: 'Name'
Value: 'MMVPC'
PublicSubnetOne:
Type: AWS::EC2::Subnet
Properties:
AvailabilityZone:
Fn::Select:
- 0
- Fn::GetAZs: { Ref: 'AWS::Region' }
VpcId: !Ref 'VPC'
CidrBlock: !FindInMap [ 'SubnetConfig', 'PublicOne', 'CIDR' ]
MapPublicIpOnLaunch: true
Tags:
- Key: 'Name'
Value: 'MMPublicSubnet'
PrivateSubnetMSKOne:
Type: AWS::EC2::Subnet
Properties:
AvailabilityZone:
Fn::Select:
- 0
- Fn::GetAZs: { Ref: 'AWS::Region' }
VpcId: !Ref 'VPC'
CidrBlock: !FindInMap [ 'SubnetConfig', 'PrivateSubnetMSKOne', 'CIDR' ]
MapPublicIpOnLaunch: false
Tags:
- Key: 'Name'
Value: 'PrivateSubnetMSKOne'
PrivateSubnetMSKTwo:
Type: AWS::EC2::Subnet
Properties:
AvailabilityZone:
Fn::Select:
- 1
- Fn::GetAZs: { Ref: 'AWS::Region' }
VpcId: !Ref 'VPC'
CidrBlock: !FindInMap [ 'SubnetConfig', 'PrivateSubnetMSKTwo', 'CIDR' ]
MapPublicIpOnLaunch: false
Tags:
- Key: 'Name'
Value: 'PrivateSubnetMSKTwo'
PrivateSubnetMSKThree:
Type: AWS::EC2::Subnet
Properties:
AvailabilityZone:
Fn::Select:
- 2
- Fn::GetAZs: { Ref: 'AWS::Region' }
VpcId: !Ref 'VPC'
CidrBlock: !FindInMap [ 'SubnetConfig', 'PrivateSubnetMSKThree', 'CIDR' ]
MapPublicIpOnLaunch: false
Tags:
- Key: 'Name'
Value: 'PrivateSubnetMSKThree'
InternetGateway:
Type: AWS::EC2::InternetGateway
GatewayAttachement:
Type: AWS::EC2::VPCGatewayAttachment
Properties:
VpcId: !Ref VPC
InternetGatewayId: !Ref InternetGateway
NatGateway:
Type: AWS::EC2::NatGateway
DependsOn: NatPublicIP
Properties:
AllocationId: !GetAtt NatPublicIP.AllocationId
SubnetId: !Ref PublicSubnetOne
NatPublicIP:
Type: AWS::EC2::EIP
DependsOn: VPC
Properties:
Domain: VPC
PublicRouteTable:
Type: AWS::EC2::RouteTable
Properties:
VpcId: !Ref VPC
PublicRoute:
Type: AWS::EC2::Route
DependsOn: GatewayAttachement
Properties:
RouteTableId: !Ref 'PublicRouteTable'
DestinationCidrBlock: '0.0.0.0/0'
GatewayId: !Ref 'InternetGateway'
PublicSubnetOneRouteTableAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
SubnetId: !Ref PublicSubnetOne
RouteTableId: !Ref PublicRouteTable
PrivateRoute:
Type: AWS::EC2::Route
Properties:
RouteTableId: !Ref PrivateRouteTable
DestinationCidrBlock: 0.0.0.0/0
NatGatewayId: !Ref NatGateway
PrivateRouteTable:
Type: AWS::EC2::RouteTable
Properties:
VpcId: !Ref VPC
PrivateSubnetMSKOneRouteTableAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
RouteTableId: !Ref PrivateRouteTable
SubnetId: !Ref PrivateSubnetMSKOne
PrivateSubnetMSKTwoRouteTableAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
RouteTableId: !Ref PrivateRouteTable
SubnetId: !Ref PrivateSubnetMSKTwo
PrivateSubnetMSKThreeRouteTableAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
RouteTableId: !Ref PrivateRouteTable
SubnetId: !Ref PrivateSubnetMSKThree
KDASecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Enable KDA access
VpcId: !Ref VPC
OpenSearchSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Enable Amazon OpenSearch access
VpcId: !Ref 'VPC'
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 443
ToPort: 443
SourceSecurityGroupId: !GetAtt KDASecurityGroup.GroupId
- IpProtocol: tcp
FromPort: 443
ToPort: 443
SourceSecurityGroupId: !GetAtt NGINXPlusInstancesSecurityGroup.GroupId
- IpProtocol: tcp
FromPort: 443
ToPort: 443
SourceSecurityGroupId: !GetAtt KafkaClientInstanceSecurityGroup.GroupId
KafkaClientInstanceSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: KafkaClient Security Group
VpcId: !Ref 'VPC'
ProducerECSTaskSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Security Group for ECS task running producer application
VpcId: !Ref 'VPC'
MSKSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: MSK Security Group
VpcId: !Ref 'VPC'
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 9098
ToPort: 9098
SourceSecurityGroupId: !GetAtt KafkaClientInstanceSecurityGroup.GroupId
- IpProtocol: tcp
FromPort: 9098
ToPort: 9098
SourceSecurityGroupId: !GetAtt ProducerECSTaskSecurityGroup.GroupId
- IpProtocol: tcp
FromPort: 9098
ToPort: 9098
SourceSecurityGroupId: !GetAtt KDASecurityGroup.GroupId
- IpProtocol: -1
CidrIp: 0.0.0.0/0
KafkaClientEC2Instance:
Type: AWS::EC2::Instance
Properties:
InstanceType: t3.medium
IamInstanceProfile: !Ref EC2InstanceProfile
AvailabilityZone:
Fn::Select:
- 0
- Fn::GetAZs: { Ref: 'AWS::Region' }
SubnetId: !Ref 'PublicSubnetOne'
SecurityGroupIds: [ !GetAtt KafkaClientInstanceSecurityGroup.GroupId ]
ImageId: !Ref LatestAmiId
Tags:
- Key: 'Name'
Value: 'KafkaClientInstance'
BlockDeviceMappings:
- DeviceName: /dev/xvda
Ebs:
VolumeSize: 20
VolumeType: gp2
DeleteOnTermination: true
UserData:
Fn::Base64:
!Sub |
#!/bin/bash
yum update -y
yum install python3.7 -y
yum install java-1.8.0-openjdk-devel -y
yum install nmap-ncat -y
yum install git -y
yum erase awscli -y
yum install jq -y
yum install maven -y
amazon-linux-extras install docker -y
service docker start
usermod -a -G docker ec2-user
cd /home/ec2-user
wget https://bootstrap.pypa.io/get-pip.py
su -c "python3.7 get-pip.py --user" -s /bin/sh ec2-user
su -c "/home/ec2-user/.local/bin/pip3 install boto3 --user" -s /bin/sh ec2-user
su -c "/home/ec2-user/.local/bin/pip3 install awscli --user" -s /bin/sh ec2-user
# Install AWS CLI 2 - access with aws2
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
./aws/install -b /usr/local/bin/aws2
su -c "ln -s /usr/local/bin/aws2/aws ~/.local/bin/aws2" -s /bin/sh ec2-user
su -c "mkdir -p /tmp/kafka" -s /bin/sh ec2-user
su -c "aws s3 cp s3://aws-streaming-artifacts/msk-lab-resources/schema-registry.properties /tmp/kafka" -l ec2-user
su -c "aws s3 cp s3://aws-streaming-artifacts/msk-lab-resources/producer.properties_msk /tmp/kafka" -l ec2-user
# Pull & Build Clickstream producer
cd /home/ec2-user
git clone https://github.com/aws-samples/sasl-scram-secrets-manager-client-for-msk.git
cd sasl-scram-secrets-manager-client-for-msk
mvn clean install -f pom.xml
cd /home/ec2-user
git clone https://github.com/aws-samples/clickstream-producer-for-apache-kafka.git
cd clickstream-producer-for-apache-kafka
mvn clean package -f pom.xml
mv target/KafkaClickstreamClient-1.0-SNAPSHOT.jar /tmp/kafka
#Install kafka library
cd /home/ec2-user
mkdir -p kafka
cd kafka
wget https://archive.apache.org/dist/kafka/2.8.1/kafka_2.12-2.8.1.tgz
tar -xzf kafka_2.12-2.8.1.tgz --strip 1
#Install IAM Auth libraries
cd /home/ec2-user/kafka/libs
wget https://github.com/aws/aws-msk-iam-auth/releases/download/1.1.0/aws-msk-iam-auth-1.1.0-all.jar
cd /home/ec2-user
cat <<EOF > /home/ec2-user/kafka/config/client.properties
security.protocol = SASL_SSL
sasl.mechanism = AWS_MSK_IAM
sasl.jaas.config = software.amazon.msk.auth.iam.IAMLoginModule required;
sasl.client.callback.handler.class = software.amazon.msk.auth.iam.IAMClientCallbackHandler
EOF
export CLASSPATH=/home/ec2-user/iam-auth/aws-msk-iam-auth-1.1.0-all.jar
cat <<EOF > /home/ec2-user/create-topics.sh
/home/ec2-user/kafka/bin/kafka-topics.sh --bootstrap-server \$BS --command-config /home/ec2-user/kafka/config/client.properties --create --topic clickstream --replication-factor 3 --partitions 3
/home/ec2-user/kafka/bin/kafka-topics.sh --bootstrap-server \$BS --command-config /home/ec2-user/kafka/config/client.properties --list
EOF
chmod +x /home/ec2-user/create-topics.sh
# wait until CF stack was created successfully
aws --region ${AWS::Region} cloudformation wait stack-create-complete --stack-name '${AWS::StackName}'
curl -u '${OpenSearchMasterUserName}:${RetrieveOpenSearchPassword.OpenSearchMasterPassword}' -X PATCH https://${OpenSearchServiceDomain.DomainEndpoint}/_plugins/_security/api/rolesmapping/all_access -H "Content-Type: application/json" -d '[{"op": "add", "path": "/backend_roles", "value": ["${KDARole.Arn}"]}]'
# Create Amazon OpenSearch indices
curl -s https://raw.githubusercontent.com/aws-samples/msk-serverless-data-pipeline/main/amazon-opensearch/index_mapping/departments_count.json| curl -u '${OpenSearchMasterUserName}:${RetrieveOpenSearchPassword.OpenSearchMasterPassword}' -s -w "\n" -XPUT https://${OpenSearchServiceDomain.DomainEndpoint}/departments_count -H "Content-Type: application/json" -d @-
curl -s https://raw.githubusercontent.com/aws-samples/msk-serverless-data-pipeline/main/amazon-opensearch/index_mapping/user_session_counts.json| curl -u '${OpenSearchMasterUserName}:${RetrieveOpenSearchPassword.OpenSearchMasterPassword}' -s -w "\n" -XPUT https://${OpenSearchServiceDomain.DomainEndpoint}/user_session_counts -H "Content-Type: application/json" -d @-
curl -s https://raw.githubusercontent.com/aws-samples/msk-serverless-data-pipeline/main/amazon-opensearch/index_mapping/user_session_details.json| curl -u '${OpenSearchMasterUserName}:${RetrieveOpenSearchPassword.OpenSearchMasterPassword}' -s -w "\n" -XPUT https://${OpenSearchServiceDomain.DomainEndpoint}/user_session_details -H "Content-Type: application/json" -d @-
# Create OpenSearch Dashboard objects
cd /home/ec2-user
curl -s https://raw.githubusercontent.com/aws-samples/msk-serverless-data-pipeline/main/amazon-opensearch/dashboard/clickstream_dashboard.ndjson -o clickstream_dashboard.ndjson
curl -XPOST https://${OpenSearchServiceDomain.DomainEndpoint}/_dashboards/auth/login -H "osd-xsrf: true" -H "content-type:application/json" -d '{"username":"${OpenSearchMasterUserName}", "password" : "${RetrieveOpenSearchPassword.OpenSearchMasterPassword}"} ' -c auth.txt
curl -XPOST https://${OpenSearchServiceDomain.DomainEndpoint}/_dashboards/api/saved_objects/_import -H "osd-xsrf:true" -b auth.txt --form file=@clickstream_dashboard.ndjson
EC2Role:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Sid: ''
Effect: Allow
Principal:
Service: ec2.amazonaws.com
Action: 'sts:AssumeRole'
Path: "/"
Policies:
- PolicyName: glue-schema-registry-access
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- glue:RegisterSchemaVersion
- glue:GetSchemaVersion
- glue:CreateSchema
- glue:GetSchemaByDefinition
Resource: '*'
- PolicyName: msk-serverless-access
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- kafka-cluster:Connect
Resource: !Sub 'arn:aws:kafka:${AWS::Region}:${AWS::AccountId}:cluster/*/*'
- Effect: Allow
Action:
- kafka-cluster:DescribeTopic
- kafka-cluster:CreateTopic
- kafka-cluster:WriteData
- kafka-cluster:ReadData
Resource: !Sub 'arn:aws:kafka:${AWS::Region}:${AWS::AccountId}:topic/*/*'
- Effect: Allow
Action:
- kafka-cluster:AlterGroup
- kafka-cluster:DescribeGroup
Resource: !Sub 'arn:aws:kafka:${AWS::Region}:${AWS::AccountId}:group/*/*'
ManagedPolicyArns:
- arn:aws:iam::aws:policy/AWSCloudFormationReadOnlyAccess
- arn:aws:iam::aws:policy/AmazonS3FullAccess
- arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore
- arn:aws:iam::aws:policy/AmazonSSMPatchAssociation
EC2InstanceProfile:
Type: AWS::IAM::InstanceProfile
Properties:
InstanceProfileName: !Join
- '-'
- - 'EC2FlinkMSKCFProfile'
- !Ref 'AWS::StackName'
Roles:
- !Ref EC2Role
NGINXPlusInstancesSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Enables access to NGINX Plus instances.
VpcId: !Ref VPC
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: '443'
ToPort: '443'
CidrIp: '0.0.0.0/0'
NGINXProxy:
Type: AWS::EC2::Instance
Properties:
Tags:
- Key: 'Name'
Value: 'NGinxProxy'
Metadata:
AWS::CloudFormation::Init:
configSets:
bootstrap_install:
- prepare_system
- create_self_signed_cert
- configure_nginx
prepare_system:
commands:
install_nginx:
command: amazon-linux-extras install -y nginx1
create_self_signed_cert:
commands:
create_self_signed_cert:
command: sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/nginx/cert.key -out /etc/nginx/cert.crt -subj "/C=DE"
configure_nginx:
files:
/etc/nginx/conf.d/default.conf:
content: !Sub |
server {
listen 443 ssl;
server_name $host;
rewrite ^/$ https://$host/_dashboards redirect;
# openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/nginx/cert.key -out /etc/nginx/cert.crt -subj /C=US/ST=./L=./O=./CN=.\n
ssl_certificate /etc/nginx/cert.crt;
ssl_certificate_key /etc/nginx/cert.key;
ssl_session_cache builtin:1000 shared:SSL:10m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers HIGH:!aNULL:!eNULL:!EXPORT:!CAMELLIA:!D:!MD5:!PSK:!RC4;
ssl_prefer_server_ciphers on;
location /_dashboards {
# Forward requests to OpenSearch Dashboards
proxy_pass https://${OpenSearchServiceDomain.DomainEndpoint}/_dashboards;
# Handle redirects to OpenSearch Dashboards
proxy_redirect https://${OpenSearchServiceDomain.DomainEndpoint} https://$host;
# Update cookie domain and path
proxy_cookie_domain ${OpenSearchServiceDomain.DomainEndpoint} $host;
proxy_cookie_path / /_dashboards/;
# Response buffer settings
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
}
location ~ \/(log|sign|fav|forgot|change|saml|oauth2) {
# Forward requests to OpenSearch
proxy_pass https://${OpenSearchServiceDomain.DomainEndpoint};
# Handle redirects to Opensearch Dashboards
proxy_redirect https://${OpenSearchServiceDomain.DomainEndpoint} https://$host;
# Update cookie domain
proxy_cookie_domain ${OpenSearchServiceDomain.DomainEndpoint} $host;
}
}
services:
sysvinit:
nginx:
enabled: 'true'
ensureRunning: 'true'
files:
- /etc/nginx/conf.d/default.conf
- /etc/nginx/conf.d/healthcheck.conf
Properties:
SubnetId: !Ref PublicSubnetOne
ImageId: !Ref LatestAmiId
InstanceType: t3.small
SecurityGroupIds:
- !Ref NGINXPlusInstancesSecurityGroup
UserData: !Base64
Fn::Join:
- ''
- - "#!/bin/bash\n"
- yum update -y
- "\n"
- !Sub '/opt/aws/bin/cfn-init -v --stack ${AWS::StackName} --resource
NGINXProxy --configsets bootstrap_install --region
${AWS::Region}'
- "\n"
- !Sub '/opt/aws/bin/cfn-signal -e $? --stack ${AWS::StackName} --resource
NGINXProxy --region ${AWS::Region}'
- "\n"
KDARole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Sid: ''
Effect: Allow
Principal:
Service: kinesisanalytics.amazonaws.com
Action: 'sts:AssumeRole'
Path: "/"
Policies:
- PolicyName: glue-schema-registry-access
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- glue:RegisterSchemaVersion
- glue:GetSchemaVersion
- glue:CreateSchema
- glue:GetSchemaByDefinition
Resource: '*'
- PolicyName: vpc-read-only-permissions
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- ec2:DescribeVpcs
- ec2:DescribeSubnets
- ec2:DescribeSecurityGroups
- ec2:DescribeDhcpOptions
Resource: '*'
- PolicyName: read-code
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- s3:GetObject
- s3:GetObjectVersion
Resource: !Sub 'arn:aws:s3:::${AssetsBucketName}/*'
- PolicyName: msk-serverless-access
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- kafka-cluster:Connect
Resource: !Sub 'arn:aws:kafka:${AWS::Region}:${AWS::AccountId}:cluster/*/*'
- Effect: Allow
Action:
- kafka-cluster:DescribeTopic
- kafka-cluster:CreateTopic
- kafka-cluster:WriteData
- kafka-cluster:ReadData
Resource: !Sub 'arn:aws:kafka:${AWS::Region}:${AWS::AccountId}:topic/*/*'
- Effect: Allow
Action:
- kafka-cluster:AlterGroup
- kafka-cluster:DescribeGroup
Resource: !Sub 'arn:aws:kafka:${AWS::Region}:${AWS::AccountId}:group/*/*'
ManagedPolicyArns:
- arn:aws:iam::aws:policy/AmazonVPCFullAccess
- arn:aws:iam::aws:policy/CloudWatchFullAccess
OpenSearchMasterPasswordSecret:
Type: AWS::SecretsManager::Secret
Properties:
Description: This secret has a dynamically generated secret password.
GenerateSecretString:
SecretStringTemplate: !Join [ '', [ '{"username": "', !Ref OpenSearchMasterUserName, '"}' ] ]
GenerateStringKey: "password"
PasswordLength: 10
ExcludeCharacters: "\" ' ( ) * + , - . / : ; < = > ! # ? @ [ \\ ] ^ _ ` { | } ~"
RetrieveOpenSearchPasswordLambdaPolicy:
Type: AWS::IAM::ManagedPolicy
Properties:
PolicyDocument:
Version: 2012-10-17
Statement:
- Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Effect: Allow
Resource: arn:aws:logs:*:*:*
Sid: AllowCWLogsWrite
- Action:
- secretsmanager:GetSecretValue
Effect: Allow
Resource: !Ref OpenSearchMasterPasswordSecret
RetrieveOpenSearchPasswordLambdaExecutionRole:
Type: AWS::IAM::Role
DependsOn: RetrieveOpenSearchPasswordLambdaPolicy
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Action:
- sts:AssumeRole
Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
ManagedPolicyArns:
- !Ref RetrieveOpenSearchPasswordLambdaPolicy
Path: /
RetrieveOpenSearchPasswordLambdaFunction:
Type: AWS::Lambda::Function
DependsOn: OpenSearchMasterPasswordSecret
Properties:
Handler: index.lambda_handler
Role: !GetAtt RetrieveOpenSearchPasswordLambdaExecutionRole.Arn
Runtime: python3.9
Timeout: 120
Code:
ZipFile: |
import json
import boto3
import base64
import os
import cfnresponse
from botocore.exceptions import ClientError
SECRET_ARN = os.getenv('SECRET_ARN')
REGION = os.getenv('REGION')
def lambda_handler(event, context):
# Create a Secrets Manager client
session = boto3.session.Session()
client = session.client(
service_name='secretsmanager',
region_name=REGION
)
secret = ""
try:
get_secret_value_response = client.get_secret_value(
SecretId=SECRET_ARN
)
except ClientError as err:
print(err)
cfnresponse.send(event, context, cfnresponse.FAILED, err)
else:
# Decrypts secret using the associated KMS key.
# Depending on whether the secret is a string or binary, one of these fields will be populated.
if 'SecretString' in get_secret_value_response:
secret = get_secret_value_response['SecretString']
else:
decoded_binary_secret = base64.b64decode(get_secret_value_response['SecretBinary'])
password_secret = json.loads(secret)
responseData = {"OpenSearchMasterPassword": password_secret["password"]}
print(responseData)
if responseData:
cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData)
else:
cfnresponse.send(event, context, cfnresponse.FAILED, "Internal Error")
Environment:
Variables:
SECRET_ARN: !Ref OpenSearchMasterPasswordSecret
REGION: !Ref AWS::Region
RetrieveOpenSearchPassword:
Type: Custom::RetrieveOpenSearchPassword
DependsOn: RetrieveOpenSearchPasswordLambdaFunction
Properties:
ServiceToken:
Fn::GetAtt: RetrieveOpenSearchPasswordLambdaFunction.Arn
AWSServiceRoleForAmazonOpenSearchService:
Type: 'AWS::IAM::ServiceLinkedRole'
Properties:
AWSServiceName: es.amazonaws.com
OpenSearchServiceDomain:
Type: 'AWS::OpenSearchService::Domain'
DependsOn:
- OpenSearchSecurityGroup
- AWSServiceRoleForAmazonOpenSearchService
Properties:
AccessPolicies:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": "*"
},
"Action": "es:*",
"Resource": {
"Fn::Join": [
":", [
"arn:aws:es",
{
"Ref": "AWS::Region"
},
{
"Ref": "AWS::AccountId"
},
"domain/*"
]
]
}
}
]
}
DomainName: !Join
- '-'
- - 'aos-clickstream'
- !Ref 'AWS::Region'
EngineVersion: OpenSearch_1.3
ClusterConfig:
InstanceCount: '1'
InstanceType: r6g.large.search
DomainEndpointOptions:
EnforceHTTPS: true
NodeToNodeEncryptionOptions:
Enabled: true
EncryptionAtRestOptions:
Enabled: true
EBSOptions:
EBSEnabled: true
Iops: '0'
VolumeSize: '100'
VolumeType: 'gp2'
AccessPolicies:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
AWS: '*'
Action: 'es:*'
Resource: '*'
AdvancedOptions:
rest.action.multi.allow_explicit_index: true
AdvancedSecurityOptions:
Enabled: true
InternalUserDatabaseEnabled: true
MasterUserOptions:
MasterUserName: !Ref OpenSearchMasterUserName
MasterUserPassword: !Join
- ""
- - "{{resolve:secretsmanager:"
- !Ref OpenSearchMasterPasswordSecret
- ":SecretString:password}}"
VPCOptions:
SubnetIds:
- !Ref PrivateSubnetMSKOne
SecurityGroupIds:
- !Ref OpenSearchSecurityGroup
UpdatePolicy:
EnableVersionUpgrade: true
GlueSchemaRegistry:
Type: AWS::Glue::Registry
Properties:
Description: Glue Schema Registry to store all origanisation schemas
Name: serverless
ContainerCluster:
Type: AWS::ECS::Cluster
Properties:
ClusterName: !Sub "${AWS::StackName}-msk-producer-cluster"
CwLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub "${AWS::StackName}-producer-log-group"
ExecutionRole:
Type: AWS::IAM::Role
Properties:
RoleName: !Sub "${AWS::StackName}-ecs-task-execution-role"
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service: ecs-tasks.amazonaws.com
Action: 'sts:AssumeRole'
ManagedPolicyArns:
- 'arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy'
- 'arn:aws:iam::aws:policy/AmazonElasticContainerRegistryPublicReadOnly'
TaskRole:
Type: AWS::IAM::Role
Properties:
RoleName: !Sub "${AWS::StackName}-ecs-task-role"
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service: ecs-tasks.amazonaws.com
Action: 'sts:AssumeRole'
ManagedPolicyArns:
- 'arn:aws:iam::aws:policy/AWSGlueSchemaRegistryFullAccess'
- 'arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy'
Policies:
- PolicyName: !Sub "${AWS::StackName}-msk-producer-policy"
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- kafka-cluster:Connect
- kafka-cluster:AlterCluster
- kafka-cluster:DescribeCluster
- kafka-cluster:*Topic*
- kafka-cluster:WriteData
- kafka-cluster:ReadData
- kafka-cluster:AlterGroup
- kafka-cluster:DescribeGroup
Resource: '*'
ProducerTaskDefinition:
Type: AWS::ECS::TaskDefinition
DependsOn: CwLogGroup
Properties:
cpu: 1024
memory: 2048
NetworkMode: awsvpc
RequiresCompatibilities:
- FARGATE
TaskRoleArn: !Ref TaskRole
ExecutionRoleArn: !Ref ExecutionRole
ContainerDefinitions:
- Name: clickstream-producer
Image: public.ecr.aws/l2e5u6w9/sample-clickstream-producer:latest
Environment:
- Name: BOOTSTRAP_STRING
Value: ''
- Name: REGION
Value: !Ref "AWS::Region"
- Name: TOPIC_NAME
Value: clickstream
LogConfiguration:
LogDriver: awslogs
Options:
awslogs-region: !Ref AWS::Region
awslogs-group: !Ref CwLogGroup
awslogs-stream-prefix: ecs
LambdaSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: MskLambda-SG
GroupName: MskLambda-SG
SecurityGroupEgress:
- CidrIp: 0.0.0.0/0
Description: Allow all outbound traffic by default
IpProtocol: "-1"
VpcId:
!Ref VPC
KDAClickstream:
Type: AWS::KinesisAnalyticsV2::Application
DependsOn: KDARole
Properties:
ApplicationConfiguration:
ApplicationCodeConfiguration:
CodeContent:
S3ContentLocation:
BucketARN: !Sub 'arn:aws:s3:::${AssetsBucketName}'
FileKey: !Ref KdaAppKey
CodeContentType: ZIPFILE
VpcConfigurations:
- SecurityGroupIds:
- !Ref KDASecurityGroup
SubnetIds:
- !Ref PrivateSubnetMSKOne
- !Ref PrivateSubnetMSKTwo
- !Ref PrivateSubnetMSKThree
ApplicationSnapshotConfiguration:
SnapshotsEnabled: false
FlinkApplicationConfiguration:
ParallelismConfiguration:
Parallelism: 8
ConfigurationType: CUSTOM
MonitoringConfiguration:
ConfigurationType: CUSTOM
LogLevel: WARN
MetricsLevel: OPERATOR
EnvironmentProperties:
PropertyGroups:
- PropertyGroupId: FlinkApplicationProperties
PropertyMap: {
"OpenSearchEndpoint": !Sub 'https://${OpenSearchServiceDomain.DomainEndpoint}',
"Region": !Ref 'AWS::Region',
"BootstrapServers": "xxxxxxx:9098",
"GroupId": "flink-clickstream-processor",
"Topic": "clickstream"
}
ApplicationDescription: KDA Flink App to analyze Clicktream data from MSK Serverless
ApplicationName: !Join
- '-'
- - 'KDAFlinkClickstream'
- !Ref 'AWS::StackName'
RuntimeEnvironment: FLINK-1_13
ServiceExecutionRole: !GetAtt KDARole.Arn
Outputs:
MSKVPC:
Description: VPC where MSK Serverless cluster needs to be created
Value: !Ref VPC
MSKPrivateSubnetOne:
Description: Private Subnet to be used with MSK Serverless cluster
Value: !Ref PrivateSubnetMSKOne
MSKPrivateSubnetTwo:
Description: Private Subnet to be used with MSK Serverless cluster
Value: !Ref PrivateSubnetMSKTwo
MSKPrivateSubnetThree:
Description: Private Subnet to be used with MSK Serverless cluster
Value: !Ref PrivateSubnetMSKThree
MSKSecurityGroupName:
Description: Security Group Name of MSK Serverless cluster
Value: !Ref MSKSecurityGroup
MSKClientEC2InstanceSsh:
Description: The SSH for the EC2 instance
Value: !Sub ssh -A ec2-user@${KafkaClientEC2Instance.PublicDnsName}
OpenSearchMasterUserName:
Description: Username used to login to Amazon OpenSearch Service
Value: !Ref OpenSearchMasterUserName
OpenSearchMasterPassword:
Description: OpenSearch password retrieved from AWS Secret Manager
Value: !GetAtt RetrieveOpenSearchPassword.OpenSearchMasterPassword
OpenSearchDashboardEndpoint:
Description: Url to open OpenSearch Dashboard
Value: !Sub 'https://${NGINXProxy.PublicDnsName}/'