-
Notifications
You must be signed in to change notification settings - Fork 5
/
1-StackSet-Shared.yml
1004 lines (942 loc) · 36.3 KB
/
1-StackSet-Shared.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
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
AWSTemplateFormatVersion: "2010-09-09"
Description: Shared functions for both Base and VPN-Base
Parameters:
Environment:
Type: String
Description: Name of the environment to bring up.
GitBranch:
Type: String
Domain:
Type: String
LockdownDomain:
Type: String
LockdownNewDomain:
Type: String
PrivacyReviewDomain:
Type: String
Mappings:
RegionMapping:
us-east-1:
Subdomain: us-east
Cidr: 172.16.0.0/17
us-east-2:
Subdomain: us-east
Cidr: 172.16.128.0/17
us-west-1:
Subdomain: us-west
Cidr: 172.17.0.0/17
us-west-2:
Subdomain: us-west
Cidr: 172.17.128.0/17
ap-northeast-1:
Subdomain: ap-tokyo
Cidr: 172.18.0.0/17
ap-northeast-2:
Subdomain: ap-seoul
Cidr: 172.18.128.0/17
ap-south-1:
Subdomain: ap-mumbai
Cidr: 172.19.0.0/17
ap-southeast-1:
Subdomain: ap-singapore
Cidr: 172.19.128.0/17
ap-southeast-2:
Subdomain: ap-sydney
Cidr: 172.20.0.0/17
ca-central-1:
Subdomain: canada
Cidr: 172.20.128.0/17
eu-central-1:
Subdomain: eu-frankfurt
Cidr: 172.21.0.0/17
eu-west-1:
Subdomain: eu-ireland
Cidr: 172.21.128.0/17
eu-west-2:
Subdomain: eu-london
Cidr: 172.22.0.0/17
eu-west-3:
Subdomain: s1
Cidr: 172.22.128.0/17
sa-east-1:
Subdomain: sa
Cidr: 172.23.0.0/17
Resources:
# ==================================================
# =========== Shared SSM Managed Policy ============
# ==================================================
SSMManagedPolicy:
Type: AWS::IAM::ManagedPolicy
Properties:
Description: Trimmed version of AmazonEC2RoleforSSM
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- codecommit:GitPull
- codecommit:GetBranch
- codecommit:ListBranches
- codecommit:BatchGetCommits
- codecommit:GetCommit
- codecommit:GetCommitHistory
- codecommit:GetDifferences
- codecommit:GetObjectIdentifier
- codecommit:GetReferences
- codecommit:GetTree
- codecommit:BatchGetRepositories
- codecommit:GetRepository
- codecommit:GetBranch
- codecommit:GetCommit
Resource:
- !Sub arn:aws:codecommit:${AWS::Region}:${AWS::AccountId}:${Environment}-*
- Effect: Allow
Action:
- codecommit:ListRepositories
Resource: "*"
- Effect: Allow
Action:
- ssm:DescribeAssociation
- ssm:GetDeployablePatchSnapshotForInstance
- ssm:GetDocument
- ssm:GetManifest
# - ssm:GetParameters
- ssm:ListAssociations
- ssm:ListInstanceAssociations
- ssm:PutInventory
- ssm:PutComplianceItems
- ssm:PutConfigurePackageResult
- ssm:UpdateAssociationStatus
- ssm:UpdateInstanceAssociationStatus
- ssm:UpdateInstanceInformation
Resource: "*"
# - Effect: Allow # Don't Allow Session Manager
# Action:
# - ssmmessages:CreateControlChannel
# - ssmmessages:CreateDataChannel
# - ssmmessages:OpenControlChannel
# - ssmmessages:OpenDataChannel
# Resource: "*"
- Effect: Allow
Action:
- ec2messages:AcknowledgeMessage
- ec2messages:DeleteMessage
- ec2messages:FailMessage
- ec2messages:GetEndpoint
- ec2messages:GetMessages
- ec2messages:SendReply
Resource: "*"
- Effect: Allow
Action:
- cloudwatch:PutMetricData
Resource: "*"
- Effect: Allow
Action:
- ec2:DescribeInstanceStatus
- ec2:DescribeTags
Resource: "*"
# - Effect: Allow
# Action:
# - ds:CreateComputer
# - ds:DescribeDirectories
# Resource: "*"
- Effect: Allow
Action:
- logs:CreateLogGroup
# - logs:CreateLogStream
- logs:DescribeLogGroups
- logs:DescribeLogStreams
# - logs:PutLogEvents
Resource: "*"
# - Effect: Allow
# Action:
# - s3:PutObject
# - s3:GetObject
# - s3:GetEncryptionConfiguration
# - s3:AbortMultipartUpload
# - s3:ListMultipartUploadParts
# - s3:ListBucket
# - s3:ListBucketMultipartUploads
- Effect: Allow
Action:
- s3:Get*
- s3:List*
- kms:Decrypt
Resource:
- !Sub arn:aws:s3:::aws-ssm-${AWS::Region}/*
- !Sub arn:aws:s3:::${AWS::Region}-birdwatcher-prod/*
- !Join [ '', [ !GetAtt ArtifactBucket.Arn, "/*"] ]
- !Sub arn:aws:s3:::aws-codedeploy-${AWS::Region}/*
- !GetAtt CodePipelineKey.Arn
- Effect: Allow
Action:
- autoscaling:DescribeAutoScalingInstances
Resource: "*"
# ==================================================
# ================== S3 BUCKETS ====================
# ==================================================
ArtifactBucket:
Type: AWS::S3::Bucket
DeletionPolicy: Retain
Properties:
AccessControl: Private
VersioningConfiguration:
Status: Enabled
Tags:
- Key: Name
Value: Artifacts
- Key: Environment
Value: !Ref Environment
# ==================================================
# ================ PARAMETER STORE =================
# ==================================================
DomainParameter:
Type: AWS::SSM::Parameter
Properties:
Name: !Join [ '/', [ "", !Ref Environment, "COMMON", "DOMAIN" ] ]
Type: String
Value: !Ref Domain
DomainTestParameter:
Type: AWS::SSM::Parameter
Properties:
Name: !Join [ '/', [ "", !Ref Environment, "TEST", "COMMON", "DOMAIN" ] ]
Type: String
Value: !Ref Domain
LockdownDomainParameter:
Type: AWS::SSM::Parameter
Properties:
Name: !Join [ '/', [ "", !Ref Environment, "COMMON", "LD_DOMAIN" ] ]
Type: String
Value: !Ref LockdownDomain
LockdownDomainTestParameter:
Type: AWS::SSM::Parameter
Properties:
Name: !Join [ '/', [ "", !Ref Environment, "TEST", "COMMON", "LD_DOMAIN" ] ]
Type: String
Value: !Ref LockdownDomain
LockdownNewDomainParameter:
Type: AWS::SSM::Parameter
Properties:
Name: !Join ["/", ["", !Ref Environment, "COMMON", "LD_NEW_DOMAIN"]]
Type: String
Value: !Ref LockdownNewDomain
LockdownNewDomainTestParameter:
Type: AWS::SSM::Parameter
Properties:
Name:
!Join ["/", ["", !Ref Environment, "TEST", "COMMON", "LD_NEW_DOMAIN"]]
Type: String
Value: !Ref LockdownNewDomain
PrivacyReviewDomainParameter:
Type: AWS::SSM::Parameter
Properties:
Name: !Join [ '/', [ "", !Ref Environment, "COMMON", "PR_DOMAIN" ] ]
Type: String
Value: !Ref PrivacyReviewDomain
PrivacyReviewDomainTestParameter:
Type: AWS::SSM::Parameter
Properties:
Name: !Join [ '/', [ "", !Ref Environment, "TEST", "COMMON", "PR_DOMAIN" ] ]
Type: String
Value: !Ref PrivacyReviewDomain
# ==================================================
# ============ CODEPIPELINE ROLES ==================
# ==================================================
CodePipelineKey:
Type: AWS::KMS::Key
Properties:
Description: Used to encrypt/decrypt the artifacts on S3
Enabled: true
EnableKeyRotation: true
KeyPolicy:
Version: "2012-10-17"
Id: "codepipeline-key"
Statement:
- Sid: "Allow encryption, decryption using the key"
Effect: Allow
Principal:
AWS: "*" # We cannot limit to Group, so we allow anyone to use this key. Since it is only used to encrypt/decrypt already-public code, this is fine.
Action:
- kms:Encrypt
- kms:Decrypt
- kms:ReEncrypt*
- kms:GenerateDataKey*
- kms:DescribeKey
Resource:
- !Sub arn:aws:s3::${AWS::AccountId}:*-artifactbucket-*/*
- !Sub arn:aws:s3::${AWS::AccountId}:*-artifactbucket-*
- !Sub arn:aws:s3::${AWS::AccountId}:shared-adminauditbucket-*/*
- !Sub arn:aws:s3::${AWS::AccountId}:shared-adminauditbucket-*
- !Sub arn:aws:s3::${AWS::AccountId}:shared-artifactbucket-*/*
- !Sub arn:aws:s3::${AWS::AccountId}:shared-artifactbucket-*
Condition:
StringEquals:
kms:CallerAccount: !Ref AWS::AccountId
- Sid: "Allow administration of the key"
Effect: Allow
Principal:
AWS: !Sub "arn:aws:iam::${AWS::AccountId}:root"
Action:
- kms:*
Resource: "*"
CodeBuildRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- codebuild.amazonaws.com
Action:
- sts:AssumeRole
Path: /
Policies:
- PolicyName: AccessCodeCommit
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- codecommit:GitPull
- codecommit:GetBranch
- codecommit:ListBranches
- codecommit:BatchGetCommits
- codecommit:GetCommit
- codecommit:GetCommitHistory
- codecommit:GetDifferences
- codecommit:GetObjectIdentifier
- codecommit:GetReferences
- codecommit:GetTree
- codecommit:BatchGetRepositories
- codecommit:GetRepository
- codecommit:GetBranch
- codecommit:GetCommit
Resource:
- !Sub arn:aws:codecommit:${AWS::Region}:${AWS::AccountId}:${Environment}-*
- Effect: Allow
Action:
- codecommit:ListRepositories
Resource: "*"
- PolicyName: CreateVPCNetworkInterface
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- ec2:CreateNetworkInterface
- ec2:DescribeDhcpOptions
- ec2:DescribeNetworkInterfaces
- ec2:DeleteNetworkInterface
- ec2:DescribeSubnets
- ec2:DescribeSecurityGroups
- ec2:DescribeVpcs
Resource: "*"
- Effect: Allow
Action:
- ec2:CreateNetworkInterfacePermission
Resource: "*"
- PolicyName: GetSSMParameters
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- ssm:GetParametersByPath
Resource:
- !Sub arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter/${Environment}/TEST/COMMON
- !Sub arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter/${Environment}/TEST/ADMIN
- !Sub arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter/${Environment}/TEST/MAIN
- !Sub arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter/${Environment}/TEST/RENEWER
- !Sub arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter/${Environment}/TEST/SUPPORT
- !Sub arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter/${Environment}/TEST/PARTNER
- !Sub arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter/${Environment}/TEST/HELPER
- !Sub arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter/${Environment}/TEST/WEBHOOK
- !Sub arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter/${Environment}/TEST/DEBUG
- PolicyName: CodeBuild
PolicyDocument:
Version: '2012-10-17'
Statement:
- Sid: CloudWatchLogsPolicy
Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource:
- !Sub arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/codebuild/${Environment}-*
- !Sub arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/codebuild/${Environment}-*:log-stream:*
- Sid: CodeCommitPolicy
Effect: Allow
Action:
- codecommit:GitPull
Resource:
- "*"
- Sid: S3GetPutObjectPolicy
Effect: Allow
Action:
- s3:GetObject
- s3:GetObjectVersion
- s3:PutObject
Resource:
- !Join [ '', [ !GetAtt ArtifactBucket.Arn, "/*"] ]
- Sid: S3GetTestClients
Effect: Allow
Action:
- s3:Get*
- s3:List*
Resource:
- arn:aws:s3:::test-confirmedvpn-clients
- arn:aws:s3:::test-confirmedvpn-clients/*
- Action:
- kms:DescribeKey
- kms:GenerateDataKey*
- kms:Encrypt
- kms:ReEncrypt*
- kms:Decrypt
Resource: !GetAtt CodePipelineKey.Arn
Effect: Allow
CodeDeployRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- codedeploy.amazonaws.com
Action:
- sts:AssumeRole
Path: "/"
Policies:
- PolicyName: CodeDeploy
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- autoscaling:CompleteLifecycleAction
- autoscaling:DeleteLifecycleHook
- autoscaling:DescribeAutoScalingGroups
- autoscaling:DescribeLifecycleHooks
- autoscaling:PutLifecycleHook
- autoscaling:RecordLifecycleActionHeartbeat
- autoscaling:CreateAutoScalingGroup
- autoscaling:UpdateAutoScalingGroup
- autoscaling:EnableMetricsCollection
- autoscaling:DescribeAutoScalingGroups
- autoscaling:DescribePolicies
- autoscaling:DescribeScheduledActions
- autoscaling:DescribeNotificationConfigurations
- autoscaling:DescribeLifecycleHooks
- autoscaling:SuspendProcesses
- autoscaling:ResumeProcesses
- autoscaling:AttachLoadBalancers
- autoscaling:PutScalingPolicy
- autoscaling:PutScheduledUpdateGroupAction
- autoscaling:PutNotificationConfiguration
- autoscaling:PutLifecycleHook
- autoscaling:DescribeScalingActivities
- autoscaling:DeleteAutoScalingGroup
- ec2:DescribeInstances
- ec2:DescribeInstanceStatus
- ec2:TerminateInstances
- tag:GetTags
- tag:GetResources
- sns:Publish
- cloudwatch:DescribeAlarms
- cloudwatch:PutMetricAlarm
- elasticloadbalancing:DescribeLoadBalancers
- elasticloadbalancing:DescribeInstanceHealth
- elasticloadbalancing:RegisterInstancesWithLoadBalancer
- elasticloadbalancing:DeregisterInstancesFromLoadBalancer
- elasticloadbalancing:DescribeTargetGroups
- elasticloadbalancing:DescribeTargetHealth
- elasticloadbalancing:RegisterTargets
- elasticloadbalancing:DeregisterTargets
Resource: "*"
- Sid: S3GetObjectPolicy
Effect: Allow
Action:
- s3:GetObject
- s3:GetObjectVersion
Resource:
- !Join [ '', [ !GetAtt ArtifactBucket.Arn, "/*"] ]
CodePipelineRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- codepipeline.amazonaws.com
Action:
- sts:AssumeRole
Path: /
Policies:
- PolicyName: CodePipelineAccess
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- codecommit:GitPull
- codecommit:GetBranch
- codecommit:ListBranches
- codecommit:BatchGetCommits
- codecommit:GetCommit
- codecommit:GetCommitHistory
- codecommit:GetDifferences
- codecommit:GetObjectIdentifier
- codecommit:GetReferences
- codecommit:GetTree
- codecommit:BatchGetRepositories
- codecommit:GetRepository
- codecommit:GetBranch
- codecommit:GetCommit
Resource:
- !Sub arn:aws:codecommit:${AWS::Region}:${AWS::AccountId}:${Environment}-*
- Effect: Allow
Action:
- codecommit:ListRepositories
Resource: "*"
- Action:
- s3:List*
Effect: Allow
Resource:
- !Join [ '', [ !GetAtt ArtifactBucket.Arn] ]
- Action:
- s3:*
Effect: Allow
Resource:
- !Join [ '', [ !GetAtt ArtifactBucket.Arn, "/*"] ]
- Action:
- s3:PutObject
Effect: Allow
Resource:
- arn:aws:s3:::codepipeline*
- Action:
- codecommit:CancelUploadArchive
- codecommit:GetBranch
- codecommit:GetCommit
- codecommit:GetUploadArchiveStatus
- codecommit:UploadArchive
Effect: Allow
Resource: "*"
- Action:
- codedeploy:CreateDeployment
- codedeploy:GetApplicationRevision
- codedeploy:GetDeployment
- codedeploy:GetDeploymentConfig
- codedeploy:RegisterApplicationRevision
Effect: Allow
Resource: "*"
- Action:
- lambda:InvokeFunction
- lambda:ListFunctions
Effect: Allow
Resource: "*"
- Action:
- codebuild:BatchGetBuilds
- codebuild:StartBuild
Resource: "*"
Effect: Allow
- Action:
- kms:DescribeKey
- kms:GenerateDataKey*
- kms:Encrypt
- kms:ReEncrypt*
- kms:Decrypt
Resource: !GetAtt CodePipelineKey.Arn
Effect: Allow
# ==================================================
# ======== PARAMETER STORE SECRET FUNCTION =========
# ==================================================
ParameterStoreFunction:
Type: AWS::Lambda::Function
Properties:
Handler: index.handler
Role: !GetAtt ParameterStoreFunctionRole.Arn
Runtime: nodejs12.x
Timeout: 60
Tags:
- Key: Name
Value: !Ref Environment
Code:
ZipFile: >
var response = require('./cfn-response');
var aws = require('aws-sdk');
var crypto = require('crypto');
function generateRandomString(length) {
return crypto.randomBytes(Math.ceil(length / 2))
.toString('hex')
.slice(0, length);
};
exports.handler = function(event, context) {
var ssm = new aws.SSM();
var props = event.ResourceProperties;
var splitStackArn = event.StackId.split(':');
var region = splitStackArn[3];
var accountId = splitStackArn[4];
var stackName = splitStackArn[5].split("/")[1];
var paramName = props.Name;
var paramArn = "arn:aws:ssm:" + region + ":" + accountId + ":parameter" + paramName;
var paramValue = props.Value;
if (props.GenerateRandomString == "true") {
paramValue = generateRandomString(parseInt(props.RandomStringLength))
}
var cfnResponseData = {
Name: paramName,
Value: paramValue,
GenerateRandomString: props.GenerateRandomString,
RandomStringLength: props.RandomStringLength
}
var callback = function(err, resp) {
if (err) {
response.send(event, context, response.FAILED, cfnResponseData, paramArn, true);
}
else {
response.send(event, context, response.SUCCESS, cfnResponseData, paramArn, true);
}
};
if (event.RequestType == "Create") {
var params = {
Name: paramName,
Type: props.Type,
Value: paramValue,
Overwrite: false
}
if (props.Description) {
params.Description = props.Description;
}
if (props.KeyId) {
params.KeyId = props.KeyId;
}
ssm.putParameter(params, callback);
}
else if (event.RequestType == "Update") {
var params = {
Name: paramName,
Type: props.Type,
Value: paramValue,
Overwrite: true
}
if (props.Description) {
params.Description = props.Description;
}
if (props.KeyId) {
params.KeyId = props.KeyId;
}
ssm.putParameter(params, callback);
}
else if (event.RequestType == "Delete") {
ssm.deleteParameter({ Name: paramName }, callback);
}
};
ParameterStoreFunctionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
Path: "/"
Policies:
- PolicyName: ParameterStoreFunction
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource:
- !Sub arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/StackSet-${Environment}-*
- !Sub arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/StackSet-${Environment}-*:log-stream:*
- Effect: Allow
Action:
- ssm:PutParameter
- ssm:DeleteParameter
- kms:Encrypt
Resource:
- !Sub arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter/${Environment}/*
# ==================================================
# ============== CLOUDWATCH ALARM EMAIL ============
# ==================================================
CloudWatchAlarmEmailerTopic:
Type: AWS::SNS::Topic
Properties:
DisplayName: Admin Alerts
Subscription:
- Endpoint: !Sub admin@${Domain}
Protocol: email
AllowSnsTopicPublishPolicy:
Type: AWS::SNS::TopicPolicy
Properties:
PolicyDocument:
Id: AllowSnsTopicPublishPolicy
Version: '2012-10-17'
Statement:
- Sid: AllowCWEToPublishEventsToVpnEmailAlarmTopic
Effect: Allow
Principal:
Service: events.amazonaws.com
Action: sns:Publish
Resource: !Ref CloudWatchAlarmEmailerTopic
- Sid: AllowAllToPublishToEmailAlarmTopic
Effect: Allow
Principal:
AWS: "*"
Action:
- SNS:GetTopicAttributes
- SNS:SetTopicAttributes
- SNS:AddPermission
- SNS:RemovePermission
- SNS:DeleteTopic
- SNS:Subscribe
- SNS:ListSubscriptionsByTopic
- SNS:Publish
- SNS:Receive
Resource: !Ref CloudWatchAlarmEmailerTopic
Condition:
StringEquals:
AWS:SourceOwner: !Ref AWS::AccountId
Topics:
- !Ref CloudWatchAlarmEmailerTopic
# ==================================================
# ============ APPLICATION ERROR EMAILER ===========
# ==================================================
ErrorEmailerFunction:
Type: AWS::Lambda::Function
Properties:
Code:
ZipFile: !Sub >
var aws = require('aws-sdk');
var zlib = require('zlib');
exports.handler = function(event, context) {
var payload = new Buffer(event.awslogs.data, 'base64');
zlib.gunzip(payload, function(e, result) {
if (e) { context.fail(e); }
else {
result = JSON.parse(result.toString('ascii'));
var sns = new aws.SNS();
var params = {
Message: JSON.stringify(result, null, 2),
Subject: "[ERROR] Error Log Attached",
TopicArn: "${CloudWatchAlarmEmailerTopic}"
};
sns.publish(params, context.done);
}
});
};
Handler: index.handler
Role: !GetAtt ErrorEmailerFunctionRole.Arn
Runtime: nodejs12.x
Timeout: 10
ErrorEmailerFunctionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
Path: "/"
Policies:
- PolicyName: lambda-logs-SNS
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource:
- !Sub arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/StackSet-${Environment}-*
- !Sub arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/StackSet-${Environment}-*:log-stream:*
- Effect: Allow
Action:
- sns:Publish
Resource: !Ref CloudWatchAlarmEmailerTopic
ErrorEmailerCloudWatchPermission:
Type: AWS::Lambda::Permission
Properties:
FunctionName: !GetAtt ErrorEmailerFunction.Arn
Action: lambda:InvokeFunction
Principal: !Sub logs.${AWS::Region}.amazonaws.com
SourceAccount: !Ref 'AWS::AccountId'
# ==================================================
# ============ OS UPDATES/RESTART SCRIPT ===========
# ==================================================
OsUpdatesStatusUpdaterDocument:
Type: AWS::SSM::Document
Properties:
DocumentType: Command
Content:
schemaVersion: "2.2"
description: Updates the os_updates_status.sh script and runs it once. The script publishes OS update statuses to CloudWatch.
mainSteps:
- action: aws:runShellScript
name: runShellScript
inputs:
runCommand:
- !Sub |
set -ex
cat <<EOT > /home/ubuntu/os_updates_status.sh
printf "Setting environmental variables\n"
export AWS_DEFAULT_REGION=${AWS::Region}
printf "Getting instance ID and AutoScaling Group Name\n"
INSTANCE_ID=\$(ec2metadata --instance-id)
AUTOSCALING_GROUP_NAME=\$(aws autoscaling describe-auto-scaling-instances --instance-ids=\$INSTANCE_ID --query 'AutoScalingInstances[0]'.AutoScalingGroupName)
printf "Getting OS Updates Stats\n"
CURRENT_TIME=\$(date +%s)
LAST_UPGRADE_CHECK_TIME=\$(stat -c "%Y" /var/lib/apt/periodic/update-success-stamp)
SECONDS_SINCE_LAST_UPGRADE_CHECK=\$((\$CURRENT_TIME-\$LAST_UPGRADE_CHECK_TIME))
printf "Seconds since last upgrade check: \$SECONDS_SINCE_LAST_UPGRADE_CHECK\n"
UPGRADABLE_SECURITY_PACKAGES=\$(apt-get upgrade -s | grep -i xenial-security)
NUM_UPGRADABLE_SECURITY_PACKAGES=\$(printf "\$UPGRADABLE_SECURITY_PACKAGES" | wc -l)
printf "Upgradable Security Packages:\n \$UPGRADABLE_SECURITY_PACKAGES \n"
PACKAGES_REQUIRE_RESTART=\$(cat /var/run/reboot-required.pkgs)
NUM_PACKAGES_REQUIRE_RESTART=\$(printf "\$PACKAGES_REQUIRE_RESTART" | wc -l)
printf "Reboot-required packages:\n \$PACKAGES_REQUIRE_RESTART \n"
if test -e "/usr/local/bin/node";
then
CURRENT_NODE_VERSION=\$(/usr/local/bin/node --version | cut -d v -f2)
else
CURRENT_NODE_VERSION=\$(/usr/bin/node --version | cut -d v -f2)
fi
echo "\$CURRENT_NODE_VERSION" > /tmp/CURRENT_NODE_VERSION
NEXT_MAJOR_VERSION=13
LATEST_LTS_NODE_VERSION=\$(npm show node@">=\$CURRENT_NODE_VERSION <\$NEXT_MAJOR_VERSION" version)
echo "\$LATEST_LTS_NODE_VERSION" > /tmp/LATEST_LTS_NODE_VERSION
printf "Current Vs Latest LTS Node Version:\n \$CURRENT_NODE_VERSION vs \$LATEST_LTS_NODE_VERSION \n"
printf "Publishing to CloudWatch\n"
aws cloudwatch put-metric-data --metric-name "Last Upgrade Check Seconds" --namespace CVPN/Shared --unit Seconds --value \$SECONDS_SINCE_LAST_UPGRADE_CHECK --dimensions Environment=${Environment},InstanceId=\$INSTANCE_ID
aws cloudwatch put-metric-data --metric-name "# Security Packages Upgradable" --namespace CVPN/Shared --unit Count --value \$NUM_UPGRADABLE_SECURITY_PACKAGES --dimensions Environment=${Environment},InstanceId=\$INSTANCE_ID
aws cloudwatch put-metric-data --metric-name "# Packages Require Restart" --namespace CVPN/Shared --unit Count --value \$NUM_PACKAGES_REQUIRE_RESTART --dimensions Environment=${Environment},InstanceId=\$INSTANCE_ID
if [ "\$CURRENT_NODE_VERSION" = "\$LATEST_LTS_NODE_VERSION" ] || [ -z "\$LATEST_LTS_NODE_VERSION" ];
then
aws cloudwatch put-metric-data --metric-name "NodeJS Outdated" --namespace CVPN/Shared --unit Count --value 0 --dimensions Environment=${Environment},InstanceId=\$INSTANCE_ID
else
aws cloudwatch put-metric-data --metric-name "NodeJS Outdated" --namespace CVPN/Shared --unit Count --value 1 --dimensions Environment=${Environment},InstanceId=\$INSTANCE_ID
fi
if [ \$AUTOSCALING_GROUP_NAME != 'null' ];
then
aws cloudwatch put-metric-data --metric-name "Last Upgrade Check Seconds" --namespace CVPN/Shared --unit Seconds --value \$SECONDS_SINCE_LAST_UPGRADE_CHECK --dimensions Environment=${Environment},AutoScalingGroupName=\$AUTOSCALING_GROUP_NAME
aws cloudwatch put-metric-data --metric-name "# Security Packages Upgradable" --namespace CVPN/Shared --unit Count --value \$NUM_UPGRADABLE_SECURITY_PACKAGES --dimensions Environment=${Environment},AutoScalingGroupName=\$AUTOSCALING_GROUP_NAME
aws cloudwatch put-metric-data --metric-name "# Packages Require Restart" --namespace CVPN/Shared --unit Count --value \$NUM_PACKAGES_REQUIRE_RESTART --dimensions Environment=${Environment},AutoScalingGroupName=\$AUTOSCALING_GROUP_NAME
if [ "\$CURRENT_NODE_VERSION" = "\$LATEST_LTS_NODE_VERSION" ] || [ -z "\$LATEST_LTS_NODE_VERSION" ];
then
aws cloudwatch put-metric-data --metric-name "NodeJS Outdated" --namespace CVPN/Shared --unit Count --value 0 --dimensions Environment=${Environment},AutoScalingGroupName=\$AUTOSCALING_GROUP_NAME
else
aws cloudwatch put-metric-data --metric-name "NodeJS Outdated" --namespace CVPN/Shared --unit Count --value 1 --dimensions Environment=${Environment},AutoScalingGroupName=\$AUTOSCALING_GROUP_NAME
fi
fi
EOT
chmod +x /home/ubuntu/os_updates_status.sh
chown ubuntu:ubuntu /home/ubuntu/os_updates_status.sh
echo "0 */4 * * * root /home/ubuntu/os_updates_status.sh 2>&1 | /usr/bin/logger -t os_updates_status" > /etc/cron.d/os_updates_status
echo "@reboot root /home/ubuntu/os_updates_status.sh 2>&1 | /usr/bin/logger -t os_updates_status" >> /etc/cron.d/os_updates_status
chmod 0644 /etc/cron.d/os_updates_status
cd /home/ubuntu
./os_updates_status.sh 2>&1 | /usr/bin/logger -t os_updates_status
OsUpdatesStatusUpdaterAssociation:
Type: AWS::SSM::Association
Properties:
AssociationName: !Join [ '-', [ !Ref Environment, Os-Updates-Status-Updater ] ]
DocumentVersion: $LATEST
Name: !Ref OsUpdatesStatusUpdaterDocument
Targets:
- Key: tag:Environment
Values:
- !Ref Environment
# ==================================================
# =================== VPN VPC ====================
# ==================================================
VpnVPC:
Type: AWS::EC2::VPC
Properties:
CidrBlock: !FindInMap [ RegionMapping, !Ref "AWS::Region", Cidr ]
InstanceTenancy: default
EnableDnsSupport: true
EnableDnsHostnames: true
Tags:
- Key: Name
Value: !Join [ '-', [ !Ref Environment, VPN ] ]
Outputs:
GitBranch:
Value: !Ref GitBranch
Export:
Name: !Join [ '-', [ !Ref Environment, GitBranch ] ]
SSMManagedPolicy:
Value: !Ref SSMManagedPolicy
Export:
Name: !Join [ '-', [ !Ref Environment, SSMManagedPolicy ] ]
ArtifactBucket:
Value: !Ref ArtifactBucket
Export:
Name: !Join [ '-', [ !Ref Environment, ArtifactBucket ] ]
Domain:
Value: !Ref Domain
Export:
Name: !Join [ '-', [ !Ref Environment, Domain ] ]
LockdownDomain:
Value: !Ref LockdownDomain
Export:
Name: !Join [ '-', [ !Ref Environment, LD-Domain ] ]
LockdownNewDomain:
Value: !Ref LockdownNewDomain
Export:
Name: !Join [ '-', [ !Ref Environment, LD-New-Domain ] ]
PrivacyReviewDomain:
Value: !Ref PrivacyReviewDomain
Export:
Name: !Join [ '-', [ !Ref Environment, PR-Domain ] ]
ParameterStoreFunctionArn:
Value: !GetAtt ParameterStoreFunction.Arn
Export:
Name: !Join [ '-', [ !Ref Environment, ParameterStoreFunctionArn ] ]
CloudWatchAlarmEmailerTopic:
Value: !Ref CloudWatchAlarmEmailerTopic
Export:
Name: !Join [ '-', [ !Ref Environment, CloudWatchAlarmEmailerTopic ] ]
ErrorEmailerFunctionArn:
Value: !GetAtt ErrorEmailerFunction.Arn
Export:
Name: !Join [ '-', [ !Ref Environment, ErrorEmailerFunctionArn ] ]
CodePipelineKeyId:
Value: !Ref CodePipelineKey
Export:
Name: !Join [ '-', [ !Ref Environment, CodePipelineKeyId ] ]
CodeBuildRoleArn:
Value: !GetAtt CodeBuildRole.Arn
Export:
Name: !Join [ '-', [ !Ref Environment, CodeBuildRoleArn ] ]
CodePipelineRoleArn:
Value: !GetAtt CodePipelineRole.Arn
Export:
Name: !Join [ '-', [ !Ref Environment, CodePipelineRoleArn ] ]
CodeDeployRoleArn:
Value: !GetAtt CodeDeployRole.Arn
Export:
Name: !Join [ '-', [ !Ref Environment, CodeDeployRoleArn ] ]