Post

CloudFormation - Backend and Frontend Infrastructure

Create AWS Infrastructure for the backend services.

Backend template

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
#!/bin/bash

HZID="$1"
HZN="$2"
CERT="$3"

cat <<EOF >> backend.yml
---
AWSTemplateFormatVersion : 2010-09-09
Description: Backend infrastructure

### Set Parameters (values to pass to your template at runtime)
Parameters:
  ProjectName:
    Description: This name will be used for for resource names, keyname and tagging.
    Type: String
    Default: App
  Environment:
    Description: Deployment environment.
    Type: String
    AllowedValues:
      - dev
      - prod
    Default: dev
  VpcCidr:
    Description: What is the CIDR Block of IPv4 IP addresses for VPC?
    Type: String
    Default: 10.1.0.0/16
    AllowedPattern: "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(/([0-9]|[1-2][0-9]|3[0-2]))?\$"
  PublicSubnetAZaCidr:
    Description: Please enter the IP range (CIDR notation) for the public subnet in the Availability Zone "A"
    Type: String
    AllowedPattern: "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(/([0-9]|[1-2][0-9]|3[0-2]))?\$"
    Default: 10.1.10.0/24
  PublicSubnetAZbCidr:
    Description: Please enter the IP range (CIDR notation) for the public subnet in the Availability Zone "B"
    Type: String
    AllowedPattern: "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(/([0-9]|[1-2][0-9]|3[0-2]))?\$"
    Default: 10.1.20.0/24
  PrivateSubnetAZaCidr:
    Description: Please enter the IP range (CIDR notation) for the public subnet in the Availability Zone "A"
    Type: String
    AllowedPattern: "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(/([0-9]|[1-2][0-9]|3[0-2]))?\$"
    Default: 10.1.30.0/24
  Certificate:
    Description: What is the Certificate ID?
    Type: String
    Default: $CERT
  HostedZoneId:
    Description: What is the Hosted Zone Id?
    Type: String
    Default: $HZID
  HostedZoneName:
    Description: What is the Hosted Zone Name?
    Type: String
    Default: $HZN
  PrefixListId:
    Description: Prefix List Id for CloudFront IP
    Type: String
    Default: pl-4fa04526

### Metadata (provide additional information about the template)
Metadata:
  AWS::CloudFormation::Interface:
    ParameterGroups:
      - 
        Label:
          default: "VPC for Faregate"
        Parameters:
          - ProjectName
          - Environment
          - VpcCidr
          - PublicSubnetAZaCidr
          - PublicSubnetAZbCidr
          - PrivateSubnetAZaCidr
          - Certificate
          - HostedZoneName
          - HostedZoneId
          - PrefixListId
    
    ParameterLabels:
      ProjectName:
        default: "Project"
      Environment:
        default: "Name"
      VpcCidr:
        default: "VPC CIDR"
      PublicSubnetAZaCidr:
        default: "PublicSubnet A"
      PublicSubnetAZbCidr:
        default: "PublicSubnet B"
      PrivateSubnetAZaCidr:
        default: "PrivateSubnet A"
      Certificate:
        default: "Certificate ID"
      HostedZoneName:
        default: "Hosted Zone Name"
      HostedZoneId:
        default: "Hosted Zone Id"
      PrefixListId:
        default: "Prefix List Id"

Resources:
### VPC
  Vpc:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: !Ref VpcCidr
      InstanceTenancy: default
      EnableDnsSupport: true
      EnableDnsHostnames: true
      Tags:
      - {Key: Name, Value: !Sub '\${ProjectName}.\${Environment}.VPC'}
      - {Key: Project, Value: !Ref ProjectName}
      - {Key: Environment, Value: !Ref Environment}

### IGW
  InternetGateway: 
    Type: AWS::EC2::InternetGateway
    Properties:
      Tags:
      - {Key: Name, Value: !Sub '\${ProjectName}.\${Environment}.IGW'}
      - {Key: Project, Value: !Ref ProjectName}
      - {Key: Environment, Value: !Ref Environment}
    

  VpcInternetGatewayAttachment: 
    Type: AWS::EC2::VPCGatewayAttachment
    Properties: 
      VpcId: !Ref Vpc
      InternetGatewayId: !Ref InternetGateway

### Subnets
  PublicSubnetAZa:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref Vpc
      CidrBlock: !Ref PublicSubnetAZaCidr
      AvailabilityZone: !Select [0, !GetAZs ""]
      Tags:
      - {Key: Name, Value: !Sub '\${ProjectName}.\${Environment}.Public.Zone.A'}
      - {Key: Project, Value: !Ref ProjectName}
      - {Key: Environment, Value: !Ref Environment}

  PublicSubnetAZb:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref Vpc
      CidrBlock: !Ref PublicSubnetAZbCidr
      AvailabilityZone: !Select [1, !GetAZs ""]
      Tags:
      - {Key: Name, Value: !Sub '\${ProjectName}.\${Environment}.Public.Zone.B'}
      - {Key: Project, Value: !Ref ProjectName}
      - {Key: Environment, Value: !Ref Environment}

  PrivateSubnetAZa:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref Vpc
      CidrBlock: !Ref PrivateSubnetAZaCidr
      AvailabilityZone: !Select [0, !GetAZs ""]
      Tags:
      - {Key: Name, Value: !Sub '\${ProjectName}.\${Environment}.Private.Zone.A'}
      - {Key: Project, Value: !Ref ProjectName}
      - {Key: Environment, Value: !Ref Environment}
      
### RouteTables
  PublicRouteTable: 
    Type: AWS::EC2::RouteTable
    Properties: 
      VpcId: !Ref Vpc
      Tags:
      - {Key: Name, Value: !Sub '\${ProjectName}.\${Environment}.Public.RouteTable'}
      - {Key: Project, Value: !Ref ProjectName}
      - {Key: Environment, Value: !Ref Environment}
  
  PrivateRouteTableA: 
    Type: AWS::EC2::RouteTable
    Properties: 
      VpcId: !Ref Vpc
      Tags:
      - {Key: Name, Value: !Sub '\${ProjectName}.\${Environment}.Private.RouteTable'}
      - {Key: Project, Value: !Ref ProjectName}
      - {Key: Environment, Value: !Ref Environment}

  PublicSubnetAZaRouteTable:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      RouteTableId: !Ref PublicRouteTable  
      SubnetId:  !Ref PublicSubnetAZa

  PublicSubnetAZbRouteTable:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      RouteTableId: !Ref PublicRouteTable  
      SubnetId:  !Ref PublicSubnetAZb
  
  PrivateSubnetAZaRouteTable: 
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties: 
      RouteTableId: !Ref PrivateRouteTableA
      SubnetId: !Ref PrivateSubnetAZa

  RouteToNAT1: 
   Type: AWS::EC2::Route
   Properties: 
     DestinationCidrBlock: 0.0.0.0/0
     RouteTableId: !Ref PrivateRouteTableA
     NatGatewayId: !Ref NATGatewayA

  RouteToInternetGateway: 
    Type: AWS::EC2::Route
    DependsOn: VpcInternetGatewayAttachment
    Properties: 
      DestinationCidrBlock: 0.0.0.0/0
      RouteTableId: !Ref PublicRouteTable
      GatewayId: !Ref InternetGateway

### NatGateway
  ElasticIP1:
    Type: AWS::EC2::EIP
    Properties:
      Domain: vpc
      Tags:
      - {Key: Name, Value: !Sub '\${ProjectName}.\${Environment}.EIP1'}
      - {Key: Project, Value: !Ref ProjectName}
      - {Key: Environment, Value: !Ref Environment}

  NATGatewayA:
    Type: AWS::EC2::NatGateway
    DependsOn: VpcInternetGatewayAttachment
    Properties:
      AllocationId: !GetAtt ElasticIP1.AllocationId
      SubnetId: !Ref PublicSubnetAZa
      Tags:
      - {Key: Name, Value: !Sub '\${ProjectName}.\${Environment}.NAT1'}
      - {Key: Project, Value: !Ref ProjectName}
      - {Key: Environment, Value: !Ref Environment}

### Load Balancer
  ALB:
    Type: AWS::ElasticLoadBalancingV2::LoadBalancer
    Properties:
      Name: !Sub '\${ProjectName}-\${Environment}-\${AWS::Region}-ALB'
      Scheme: internet-facing
      IpAddressType: 'ipv4'
      Type: application
      SecurityGroups: 
        - !GetAtt ALBSecurityGroup.GroupId
      Subnets:
      - !Ref PublicSubnetAZa
      - !Ref PublicSubnetAZb
      Tags:
      - {Key: Project, Value: !Ref ProjectName}
      - {Key: Environment, Value: !Ref Environment}

  TargetGroup:
    Type: AWS::ElasticLoadBalancingV2::TargetGroup
    Properties:
      HealthCheckIntervalSeconds: 60
      HealthCheckPath: /
      HealthCheckProtocol: HTTP
      HealthCheckTimeoutSeconds: 5
      HealthyThresholdCount: 5
      TargetType: ip
      Matcher:
        HttpCode: 200-499
      Name: !Sub '\${Environment}-App-Fargate-TG'
      Port: 80
      Protocol: HTTP
      UnhealthyThresholdCount: 3
      VpcId: !Ref Vpc

  HTTPSListener:
    Type: AWS::ElasticLoadBalancingV2::Listener
    Properties:
      Certificates:
      - CertificateArn: !Ref Certificate
      DefaultActions:
      - TargetGroupArn: !Ref TargetGroup
        Type: forward
      LoadBalancerArn: !Ref ALB
      Port: 443
      Protocol: 'HTTPS'
      SslPolicy: 'ELBSecurityPolicy-2016-08'

  HTTPListener:
    Type: 'AWS::ElasticLoadBalancingV2::Listener'
    Properties:
      DefaultActions:
      - Type: redirect
        RedirectConfig:
          Port: '443'
          Protocol: HTTPS
          StatusCode: HTTP_301
      LoadBalancerArn: !Ref ALB
      Port: 80
      Protocol: HTTP

### DNS
  DnsRecords:
    Type: AWS::Route53::RecordSetGroup
    DependsOn: ALB
    Properties:
      HostedZoneId: !Ref HostedZoneId
      Comment: Zone apex alias targeted to myELB LoadBalancer.
      RecordSets:
      - Name: !Sub App-bck.\${HostedZoneName}
        Type: A
        AliasTarget:
          HostedZoneId: !GetAtt 'ALB.CanonicalHostedZoneID'
          DNSName: !GetAtt 'ALB.DNSName'
    
### ECS Cluster
  ECSCluster:
    Type: AWS::ECS::Cluster
    Properties:
      ClusterName: !Sub '\${ProjectName}-\${Environment}-ECS-cluster'
      ServiceConnectDefaults: 
        Namespace: !Sub '\${ProjectName}-\${Environment}-ECS-App'
      Tags:
      - {Key: Project, Value: !Ref ProjectName}
      - {Key: Environment, Value: !Ref Environment}

### EFS
  EFSMountTargetDB:
    Type: AWS::EFS::MountTarget
    Properties:
      FileSystemId: !ImportValue AppAppSystemFiles
      SubnetId: !Ref PrivateSubnetAZa
      SecurityGroups: [!Ref EFSTargetSecurityGroup]

### SecurityGroups
  ALBSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      VpcId: !Ref Vpc
      GroupDescription: !Sub '\${ProjectName} \${Environment} ALB Security Group'
      SecurityGroupIngress:
      - SourcePrefixListId: !Ref PrefixListId
        FromPort: 80
        ToPort: 80
        IpProtocol: 'tcp'
      - CidrIp: '0.0.0.0/0'
        FromPort: 443
        ToPort: 443
        IpProtocol: 'tcp'
      Tags:
      - {Key: Name, Value: !Sub '\${ProjectName}.\${Environment}.ALB.SG'}
      - {Key: Project, Value: !Ref ProjectName}
      - {Key: Environment, Value: !Ref Environment}

  AppSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    DependsOn: ALBSecurityGroup
    Properties:
      VpcId: !Ref Vpc
      GroupDescription: Access to the Fargate service and the tasks/containers that run on them
      SecurityGroupIngress:
      - CidrIp: !Ref VpcCidr
        FromPort: 3306
        ToPort: 3306
        IpProtocol: 'tcp'
      - SourceSecurityGroupId: !Ref ALBSecurityGroup
        FromPort: 80
        ToPort: 80
        IpProtocol: 'tcp'
      - SourceSecurityGroupId: !Ref ALBSecurityGroup
        FromPort: 443
        ToPort: 443
        IpProtocol: 'tcp'
      Tags:
      - {Key: Name, Value: !Sub '\${ProjectName}.\${Environment}.AppFargate.SG'}
      - {Key: Project, Value: !Ref ProjectName}
      - {Key: Environment, Value: !Ref Environment}

  EFSTargetSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: EFS Mount Access
      VpcId: !Ref Vpc
      SecurityGroupIngress:
      - CidrIp: !Ref VpcCidr
        IpProtocol: '-1'
      Tags:
      - {Key: Name, Value: !Sub '\${ProjectName}.\${Environment}.EFS.SG'}
      - {Key: Project, Value: !Ref ProjectName}
      - {Key: Environment, Value: !Ref Environment}
  
  DBSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    DependsOn: EFSTargetSecurityGroup
    Properties:
      VpcId: !Ref Vpc
      GroupDescription: Access to the Fargate service and the tasks/containers that run on them
      SecurityGroupIngress:
      - CidrIp: !Ref VpcCidr
        FromPort: 3306
        ToPort: 3306
        IpProtocol: 'tcp'
      - SourceSecurityGroupId: !Ref EFSTargetSecurityGroup
        IpProtocol: '-1'
      Tags:
      - {Key: Name, Value: !Sub '\${ProjectName}.\${Environment}.DBFargate.SG'}
      - {Key: Project, Value: !Ref ProjectName}
      - {Key: Environment, Value: !Ref Environment}
      
### Roles
  EcsTaskExecutionRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
        - Effect: Allow
          Principal:
            Service: [ecs-tasks.amazonaws.com]
          Action: ['sts:AssumeRole']
      Path: /
      Policies:
        - PolicyName: !Sub '\${ProjectName}.\${Environment}.EcsTaskExecutionRolePolicy'
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
            - Effect: Allow
              Action:
                - 'ecr:GetAuthorizationToken'
                - 'ecr:BatchCheckLayerAvailability'
                - 'ecr:GetDownloadUrlForLayer'
                - 'ecr:BatchGetImage'
                - 'logs:CreateLogStream'
                - 'logs:PutLogEvents'
                - 'logs:CreateLogGroup'
                - 'elasticfilesystem:ClientWrite'
                - 'elasticfilesystem:ClientMount'
              Resource: '*'
      Tags:
      - {Key: Name, Value: !Sub '\${ProjectName}.\${Environment}.EcsTaskExecutionRole'}
      - {Key: Project, Value: !Ref ProjectName}
      - {Key: Environment, Value: !Ref Environment}
  
  EcsTaskRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
        - Effect: Allow
          Principal:
            Service: [ecs-tasks.amazonaws.com]
          Action: ['sts:AssumeRole']
      Path: /
      Policies:              
        - PolicyName: !Sub '\${ProjectName}.\${Environment}.SESPolicy'
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
            - Effect: Allow
              Action:
              - ses:*
              Resource: '*'
        - PolicyName: !Sub '\${ProjectName}.\${Environment}.EXECintoAppPolicy'
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
            - Effect: Allow
              Action:
              - 'ssmmessages:CreateControlChannel'
              - 'ssmmessages:CreateDataChannel'
              - 'ssmmessages:OpenControlChannel'
              - 'ssmmessages:OpenDataChannel'
              Resource: '*'

  EcsDBTaskRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
        - Effect: Allow
          Principal:
            Service: [ecs-tasks.amazonaws.com]
          Action: ['sts:AssumeRole']
      Path: /
      Policies:              
        - PolicyName: !Sub '\${ProjectName}.\${Environment}.EFSDBPolicy'
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
            - Effect: Allow
              Action:
              - 'elasticfilesystem:ClientMount'
              - 'elasticfilesystem:ClientWrite'
              Resource: '*'
        - PolicyName: !Sub '\${ProjectName}.\${Environment}.EXECintoDBPolicy'
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
            - Effect: Allow
              Action:
              - 'ssmmessages:CreateControlChannel'
              - 'ssmmessages:CreateDataChannel'
              - 'ssmmessages:OpenControlChannel'
              - 'ssmmessages:OpenDataChannel'
              Resource: '*'
      Tags:
      - {Key: Name, Value: !Sub '\${ProjectName}.\${Environment}.EcsDBTaskRole'}
      - {Key: Project, Value: !Ref ProjectName}
      - {Key: Environment, Value: !Ref Environment}

### Parameters
  ALBSGParameter:
    Type: AWS::SSM::Parameter
    Properties:
      Name: !Sub '\${Environment}.ALB.SG.App'
      Type: String
      Value: !Ref ALBSecurityGroup
      Description: SSM Parameter for security group

  AppSGParameter:
    Type: AWS::SSM::Parameter
    Properties:
      Name: !Sub '\${Environment}.AppSG.App'
      Type: String
      Value: !Ref AppSecurityGroup
      Description: SSM Parameter for App security group

  DBSGParameter:
    Type: AWS::SSM::Parameter
    Properties:
      Name: !Sub '\${Environment}.SG.App.DataBase'
      Type: String
      Value: !Ref DBSecurityGroup
      Description: SSM Parameter for DataBase security group

  PublicSubnetAParameter:
    Type: AWS::SSM::Parameter
    Properties:
      Name: !Sub '\${Environment}.PublicSubnetA.App'
      Type: String
      Value: !Ref PublicSubnetAZa
      Description: SSM Parameter for subnet

  PublicSubnetBParameter:
    Type: AWS::SSM::Parameter
    Properties:
      Name: !Sub '\${Environment}.PublicSubnetB.App'
      Type: String
      Value: !Ref PublicSubnetAZb
      Description: SSM Parameter for subnet

  PrivateSubnetParameter:
    Type: AWS::SSM::Parameter
    Properties:
      Name: !Sub '\${Environment}.PrivateSubnet.App'
      Type: String
      Value: !Ref PrivateSubnetAZa
      Description: SSM Parameter for subnet

  EFSMountTargetDBParameterDB:
    Type: AWS::SSM::Parameter
    Properties:
      Name: !Sub '\${Environment}.EFSMountTargetDB.App'
      Type: String
      Value: !Ref EFSMountTargetDB
      Description: SSM Parameter for EFSMountPrivateTarget

  ECSClusterParameter:
    Type: AWS::SSM::Parameter
    Properties:
      Name: !Sub '\${Environment}.ECSCluster.App'
      Type: String
      Value: !Ref ECSCluster
      Description: SSM Parameter for ECSCluster

  EcsTaskExecutionRoleParameter:
    Type: AWS::SSM::Parameter
    Properties:
      Name: !Sub '\${Environment}.EcsTaskExecutionRole.App'
      Type: String
      Value: !GetAtt EcsTaskExecutionRole.Arn
      Description: SSM Parameter for EcsTaskExecutionRole
  
  EcsTaskRoleParameter:
    Type: AWS::SSM::Parameter
    Properties:
      Name: !Sub '\${Environment}.EcsTaskRole.App'
      Type: String
      Value: !GetAtt EcsTaskRole.Arn
      Description: SSM Parameter for EcsTaskRoleParameter

  EcsDBTaskRoleParameter:
    Type: AWS::SSM::Parameter
    Properties:
      Name: !Sub '\${Environment}.EcsDBTaskRole.App'
      Type: String
      Value: !GetAtt EcsDBTaskRole.Arn
      Description: SSM Parameter for EcsDBTaskRoleParameter
EOF

Frontend template

Run Bash script to create a CloudFormation template for running the CloudFront distribution using a private S3 bucket and creating Rout53 RecordSet for the domain.

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
#!/bin/bash

HZID="$1"
HZN="$2"
CERT="$3"

cat <<EOF >> frontend.yml
---
AWSTemplateFormatVersion : 2010-09-09
Description: Project CloudFront distributions Stack

### Set Parameters (values to pass to your template at runtime)
Parameters:
  Environment:
    Type: String
    Default: dev
    AllowedValues:
    - dev
    - prod
    Description: Choose environment to deploy
  DomainPrefix:
    Type: String
    Default: App-fe
    Description: Choose domain prefix for Construction Site Inventory app
  ProjectName:
    Type: String
    Default: App
    Description: This will be used for for resource names, keyname and tagging
  SiteBucket:
    Type: String
    Default: App-app
    Description: Prefix for Project website
  HostedZone:
    Type: String
    Default: $HZN
    Description: Hosted zone for project

Resources:
### Route53 record for CloudFront distributions
  DnsRecordCdnDistribution:
    Type: AWS::Route53::RecordSetGroup
    DependsOn: CdnDistribution
    Properties:
      HostedZoneId: $HZID
      Comment: !Sub \${ProjectName} frontend DNS records.
      RecordSets:
      - Name: !Sub \${DomainPrefix}.\${HostedZone}
        Type: A
        AliasTarget:
          HostedZoneId: Z2FDTNDATAQYW2
          DNSName: !GetAtt CdnDistribution.DomainName
  
### CloudFront distributions
  CdnDistribution:
    Type: AWS::CloudFront::Distribution
    Properties:
      DistributionConfig:
        Comment: Project App
        Aliases: 
          - !Sub '\${DomainPrefix}.\${HostedZone}'
        Enabled: true
        PriceClass: PriceClass_100
        HttpVersion: http2and3
        DefaultRootObject: index.html
        CustomErrorResponses:
        - ErrorCode: 403
          ResponsePagePath: '/index.html'
          ResponseCode: '200'
          ErrorCachingMinTTL: 300
        - ErrorCode: 404
          ResponsePagePath: '/index.html'
          ResponseCode: '200'
          ErrorCachingMinTTL: 300
        DefaultCacheBehavior:
          TargetOriginId: !Sub "\${SiteBucket}-\${Environment}"
          ViewerProtocolPolicy: redirect-to-https
          DefaultTTL: "0"
          AllowedMethods: [DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT]
          CachedMethods: [HEAD, GET]
          Compress: true
          ForwardedValues:
            QueryString: false
        Logging:
          Bucket: !Sub 'App-cf-logs-\${Environment}.s3.amazonaws.com'
          IncludeCookies: true
          Prefix: !Sub 'cloudfront-logs-App-\${DomainPrefix}/'
        Origins:
        - DomainName: !Sub '\${SiteBucket}-\${Environment}.s3.eu-west-1.amazonaws.com'
          Id: !Sub "\${SiteBucket}-\${Environment}"
          S3OriginConfig:
            OriginAccessIdentity: !Join ['', ['origin-access-identity/cloudfront/', !ImportValue AppCloudFrontOAI]]
        ViewerCertificate:
          AcmCertificateArn: $CERT
          SslSupportMethod: sni-only
          MinimumProtocolVersion: TLSv1.2_2021
      Tags:
      - {Key: Project, Value: !Ref ProjectName}
      - {Key: Environment, Value: !Ref Environment}
EOF
This post is licensed under CC BY 4.0 by the author.

Comments powered by Disqus.