-
Notifications
You must be signed in to change notification settings - Fork 173
/
cid-cfn.yml
1903 lines (1835 loc) · 83.7 KB
/
cid-cfn.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: Deployment of Cloud Intelligence Dashboards v4.0.6
Metadata:
AWS::CloudFormation::Interface:
ParameterGroups:
- Label:
default: 'Common Parameters'
Parameters:
- PrerequisitesQuickSight
- PrerequisitesQuickSightPermissions
- QuickSightUser
- LakeFormationEnabled
- Label:
default: CUDOS, Cost-Intelligence-Dashboard and KPI-Dashboard. Require deployment of CUR via CloudFormation (cur-aggregation.yaml) or manually (Dashboard data will appear within 24h after CUR creation).
Parameters:
- CURVersion
- DeployCUDOSv5
- DeployCostIntelligenceDashboard
- DeployKPIDashboard
- Label:
default: Trusted Advisor and Compute Optimizer Dashboards. To deploy these two dashboard, you must first deploy the Optimization Data Collection Lab (https://catalog.workshops.aws/awscid/en-US/data-collection/)
Parameters:
- OptimizationDataCollectionBucketPath
- DeployTAODashboard
- DeployComputeOptimizerDashboard
- PrimaryTagName
- SecondaryTagName
- Label:
default: 'Technical Parameters. Please do not change.'
Parameters:
- AthenaWorkgroup
- AthenaQueryResultsBucket
- DatabaseName
- GlueDataCatalog
- Suffix
- QuickSightDataSourceRoleName
- QuickSightDataSetRefreshSchedule
- LambdaLayerBucketPrefix
- DeployCUDOSDashboard
- DataBucketsKmsKeysArns
- ShareDashboard
- Label:
default: 'Legacy'
Parameters:
- KeepLegacyCURTable
- CURBucketPath
- CURTableName
ParameterLabels:
PrerequisitesQuickSight:
default: "I have enabled QuickSight Enterprise Edition AND I have a SPICE capacity in the current region."
PrerequisitesQuickSightPermissions:
default: "I understand that I need to manually give Permission to QuickSight to access CUR bucket and Query results bucket. Then manually refresh datasets after deploying this CFN."
LakeFormationEnabled:
default: "I have LakeFormation permission model in place for this account & my CFN deployment credentials have administrative rights on LakeFormation"
QuickSightUser:
default: "User name of QuickSight user (as displayed in QuickSight admin panel). Dashboards created by this template will be owned by this user."
CURBucketPath:
default: "Path to Legacy Cost and Usage Report (only if Legacy CUR used)"
DeployCUDOSDashboard:
default: "CUDOS Dashboard v4 - Deprecated [set 'no' to delete]"
DeployCUDOSv5:
default: "Deploy CUDOS v5 Dashboard"
DeployCostIntelligenceDashboard:
default: "Deploy CostIntelligenceDashboard"
DeployKPIDashboard:
default: "Deploy KPI Dashboard"
OptimizationDataCollectionBucketPath:
default: "Path to Optimization Data Collection S3 bucket"
DeployTAODashboard:
default: "Deploy TAO Dashboard"
DeployComputeOptimizerDashboard:
default: "Deploy Compute Optimizer Dashboard"
AthenaWorkgroup:
default: "Athena Workgroup - Please do not change"
AthenaQueryResultsBucket:
default: "Athena Query Results Bucket - Please do not change"
DatabaseName:
default: "Database Name - Please do not change"
CURTableName:
default: "CUR Table Name - Please do not change"
Suffix:
default: "Suffix - Please do not change"
QuickSightDataSourceRoleName:
default: "IAM Role Name for QuickSight Datasource"
QuickSightDataSetRefreshSchedule:
default: "QuickSight DataSet Refresh Schedule [DEPRECATED]"
ShareDashboard:
default: "Share Dashboards"
LambdaLayerBucketPrefix:
default: "LambdaLayerBucketPrefix - Please do not change"
GlueDataCatalog:
default: "Existing Glue Data Catalog"
DataBucketsKmsKeysArns:
default: "KMS Key ARNs"
PrimaryTagName:
default: "Primary Tag for Compute Optimizer dashboard"
SecondaryTagName:
default: "Secondary Tag for Compute Optimizer dashboard"
KeepLegacyCURTable:
default: "Keep Legacy CUR Table"
cfn-lint:
config:
ignore_checks:
- W2001
Parameters:
PrerequisitesQuickSight:
Type: String
Description: See https://quicksight.aws.amazon.com/sn/admin#capacity
ConstraintDescription: 'Please check in QuickSight that you have at least 10GB of SPICE capacity'
AllowedPattern: 'yes'
AllowedValues: ["yes", "no"]
PrerequisitesQuickSightPermissions:
Type: String
Description: See https://quicksight.aws.amazon.com/sn/admin#aws
ConstraintDescription: 'Please read prerequisites'
AllowedPattern: 'yes'
AllowedValues: ["yes", "no"]
QuickSightUser:
Type: String
MinLength: 1
Default: REPLACE WITH QuickSight USER
Description: See https://quicksight.aws.amazon.com/sn/admin#users
QuickSightDataSetRefreshSchedule:
Type: String
Default: ''
Description: 'Cron expression on when to refresh spice datasets via Lambda. Only needed if some difficulties with refresh scheduling via API.'
QuickSightDataSourceRoleName:
Type: String
Default: 'CidQuickSightDataSourceRole'
Description: "IAM Role Name to be used on QuickSight Datasource Creation. If empty - then the Default QuickSight Role will be used; if provided other existing role, will use that Role; if name equal to 'CidQuickSightDataSourceRole', then a role will be created by this CloudFromation)."
ShareDashboard:
Type: String
Default: 'yes'
Description: "Make Dashboards visible by all users who access this QuickSight account."
AllowedValues: ["yes", "no"]
CURVersion:
Type: String
Default: '2.0'
AllowedValues: ["1.0", "2.0"]
Description: "We support 2 options: CUR 2.0 from DataExports stack managed by CID or CUR 1(Legacy). When you switch to CUR2 consider KeepLegacyCURTable parameter to yes for keeping Legacy CUR table for migration period."
CURBucketPath:
Type: String
MinLength: 3
Default: 's3://cid-{account_id}-shared/cur/'
AllowedPattern: '^s3://[a-z0-9](.)+[a-zA-Z0-9/]$'
Description: "Leave as is if CUR was created with CloudFormation (cur-aggregation.yaml). If it was a manually created CUR, the path entered below must be for the directory that contains the years partition (s3://curbucketname/prefix/curname/curname/). If you're using the defaults, the variable {account_id} will be replaced by current account id automatically, you can leave it as {account_id}."
AthenaWorkgroup:
Type: String
Default: ''
Description: Leave Empty
AthenaQueryResultsBucket:
Type: String
Default: ''
Description: Leave Empty
DatabaseName:
Type: String
Description: Leave Empty
Default: ''
CURTableName:
Type: String
Default: ''
Description: Leave Empty
Suffix:
Type: String
Description: Leave Empty. Do not use this Suffix it is not fully supported. For testing purposes only.
Default: ""
DeployCUDOSDashboard:
Type: String
Description: Set to 'no' to remove deprecated (v4) version of CUDOS Dashboard
Default: "no"
AllowedValues: ["yes", "no"]
DeployCUDOSv5:
Type: String
Description: Deploy CUDOS v5 Dashboard
Default: "no"
AllowedValues: ["yes", "no"]
DeployCostIntelligenceDashboard:
Type: String
Description: Deploy Cost Intelligence Dashboard
Default: "no"
AllowedValues: ["yes", "no"]
DeployKPIDashboard:
Type: String
Description: Deploy KPI Dashboard
Default: "no"
AllowedValues: ["yes", "no"]
DeployTAODashboard:
Type: String
Description: Deploy Trusted Advisor Organizational Dashboard (TAO) - WARNING! Before deploying this dashboard, you need Optimization Data Collection Lab to be installed first https://catalog.workshops.aws/awscid/en-US/data-collection/
Default: "no"
AllowedValues: ["yes", "no"]
DeployComputeOptimizerDashboard:
Type: String
Description: Deploy Compute Optimizer Dashboard (COD) - WARNING! Before deploying this dashboard, you need Optimization Data Collection Lab to be installed first https://catalog.workshops.aws/awscid/en-US/data-collection/
Default: "no"
AllowedValues: ["yes", "no"]
OptimizationDataCollectionBucketPath:
Type: String
Description: The S3 path to the bucket created by the Cost Optimization Data Collection Lab. The path will need point to a folder containing /trusted-advisor and/or /compute-optimizer folders. You can leave the variable {account_id} in place, it will be replaced by current account ID automatically.
Default: "s3://cid-data-{account_id}"
AllowedPattern: '^s3://[a-zA-Z0-9-_{}/]*$'
LambdaLayerBucketPrefix:
Type: String
Description: An S3 bucket with a Lambda layer
Default: "aws-managed-cost-intelligence-dashboards"
GlueDataCatalog:
Type: String
Description: Existing Glue Data Catalog
Default: "AwsDataCatalog"
DataBucketsKmsKeysArns:
Type: String
Description: "ARNs of KMS Keys for data buckets and/or Glue Catalog. Comma separated list, no spaces. Keep empty if data Buckets and Glue Catalog are not Encrypted with KMS. You can also set it to '*' to grant decrypt permission for all the keys."
Default: ""
LakeFormationEnabled:
Type: String
Description: Choose 'yes' if Lake Formation permission model is in place for the account. If you are not sure, leave it as 'no'.
Default: "no"
AllowedValues: ["yes", "no"]
PrimaryTagName:
Type: String
Description: Choose a tag name for Primary Tag. Can be any Tag name (Owner, Environment, Finops_Exception). Currently used only in Compute Optimizer dashboard. Leave as is if not sure. This is a Tag, not CostAllocationTag (MyTag not resource_tags_my_tag).
Default: "owner"
MinLength: 1 # cid cmd do not accept empty parameters
AllowedPattern: "[a-zA-Z0-9_]*"
SecondaryTagName:
Type: String
Description: Choose a tag name for Secondary Tag. Can be any Tag name (Owner, Environment, Finops_Exception). Currently used only in Compute Optimizer dashboard. Leave as is if not sure. This is a Tag, not CostAllocationTag (MyTag not resource_tags_my_tag).
Default: "environment"
MinLength: 1 # cid cmd do not accept empty parameters
AllowedPattern: "[a-zA-Z0-9_]*"
PermissionsBoundary:
Type: String
Default: ''
Description: Define Permission Boundary for Roles if required by SCP
RolePath:
Type: String
Default: '/'
Description: Path for roles where PermissionBoundaries can limit location
KeepLegacyCURTable:
Type: String
Description: Choose 'yes' if you want to keep the Legacy CUR table
Default: "no"
AllowedValues: ["yes", "no"]
Conditions:
NeedCUDOSDashboard: !Equals [ !Ref DeployCUDOSDashboard, "yes" ]
NeedCUDOSv5: !Equals [ !Ref DeployCUDOSv5, "yes" ]
NeedCostIntelligenceDashboard: !Equals [ !Ref DeployCostIntelligenceDashboard, "yes" ]
NeedKPIDashboard: !Equals [ !Ref DeployKPIDashboard, "yes" ]
NeedTAODashboard: !Equals [ !Ref DeployTAODashboard, "yes" ]
NeedLegacyCUR: !Or
- !Equals [!Ref KeepLegacyCURTable, "yes"]
- !Equals [!Ref CURVersion, '1.0']
NeedComputeOptimizerDashboard: !Equals [ !Ref DeployComputeOptimizerDashboard, "yes" ]
UseCUR2:
Fn::And:
- !Equals [!Ref CURVersion, '2.0']
- Fn::Or:
- !Equals [ !Ref DeployCUDOSDashboard, "yes" ]
- !Equals [ !Ref DeployCUDOSv5, "yes" ]
- !Equals [ !Ref DeployCostIntelligenceDashboard, "yes" ]
- !Equals [ !Ref DeployKPIDashboard, "yes" ]
NeedAthenaWorkgroup: !Equals [ !Ref AthenaWorkgroup, "" ]
NeedAthenaQueryResultsBucket: !Equals [ !Ref AthenaQueryResultsBucket, "" ]
NeedDatabase: !Equals [ !Ref DatabaseName, "" ]
NeedCURTable:
Fn::And:
- !Equals [ !Ref CURTableName, "" ]
- !Condition NeedLegacyCUR
NeedRefreshDatasets: !Not [ !Equals [ !Ref QuickSightDataSetRefreshSchedule, ""] ]
NeedDataBucketsKms: !Not [ !Equals [ !Ref DataBucketsKmsKeysArns, "" ] ]
NeedDataBucketsKmsAndNeedCURTable:
Fn::And:
- !Condition NeedDataBucketsKms
- !Condition NeedCURTable
NeedLakeFormationEnabled:
Fn::And:
- !Equals [ !Ref LakeFormationEnabled, "yes" ]
- Fn::Or:
- !Equals [ !Ref DeployCUDOSDashboard, "yes" ]
- !Equals [ !Ref DeployCUDOSv5, "yes" ]
- !Equals [ !Ref DeployCostIntelligenceDashboard, "yes" ]
- !Equals [ !Ref DeployKPIDashboard, "yes" ]
NeedLakeFormationCrawlerPermissions:
Fn::And:
- !Equals [ !Ref LakeFormationEnabled, "yes" ]
- !Condition NeedCURTable
NeedLakeFormationEnabledQuickSightDataSourceRole:
Fn::And:
- !Equals [ !Ref LakeFormationEnabled, "yes" ]
- !Condition NeedQuickSightDataSourceRole
UseQuickSightDataSourceRole: !Not [!Equals [ !Ref QuickSightDataSourceRoleName, "" ]]
NeedQuickSightDataSourceRole: !Equals [ !Ref QuickSightDataSourceRoleName, "CidQuickSightDataSourceRole" ]
NeedQuickSightDataSourceRoleAndLegacyCUR:
Fn::And:
- !Condition NeedQuickSightDataSourceRole
- !Condition NeedLegacyCUR
NeedQuickSightDataSourceKMS:
Fn::And:
- !Condition NeedQuickSightDataSourceRole
- !Condition NeedDataBucketsKms
NeedPermissionsBoundary: !Not [!Equals [ !Ref PermissionsBoundary, "" ]]
IsChinaOrGovCloudRegion:
Fn::Or:
- !Equals [!Ref "AWS::Region", "cn-north-1"]
- !Equals [!Ref "AWS::Region", "cn-northwest-1"]
- !Equals [!Ref "AWS::Region", "us-gov-east-1"]
- !Equals [!Ref "AWS::Region", "us-gov-west-1"]
LambdaLayerBucketPrefixIsManaged: !Equals [!Ref LambdaLayerBucketPrefix, 'aws-managed-cost-intelligence-dashboards']
Mappings:
RegionMap: # CID has AWS managed buckets for deploy. Region must support QuickSight ( curl https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AmazonQuickSight/current/region_index.json -s | jq '.regions | keys' )
ap-northeast-1: {BucketName: aws-managed-cost-intelligence-dashboards-ap-northeast-1}
ap-northeast-2: {BucketName: aws-managed-cost-intelligence-dashboards-ap-northeast-2}
ap-south-1: {BucketName: aws-managed-cost-intelligence-dashboards-ap-south-1}
ap-southeast-1: {BucketName: aws-managed-cost-intelligence-dashboards-ap-southeast-1}
ap-southeast-2: {BucketName: aws-managed-cost-intelligence-dashboards-ap-southeast-2}
ca-central-1: {BucketName: aws-managed-cost-intelligence-dashboards-ca-central-1}
eu-central-1: {BucketName: aws-managed-cost-intelligence-dashboards-eu-central-1}
eu-north-1: {BucketName: aws-managed-cost-intelligence-dashboards-eu-north-1}
eu-west-1: {BucketName: aws-managed-cost-intelligence-dashboards-eu-west-1}
eu-west-2: {BucketName: aws-managed-cost-intelligence-dashboards-eu-west-2}
eu-west-3: {BucketName: aws-managed-cost-intelligence-dashboards-eu-west-3}
sa-east-1: {BucketName: aws-managed-cost-intelligence-dashboards-sa-east-1}
us-east-1: {BucketName: aws-managed-cost-intelligence-dashboards-us-east-1}
us-east-2: {BucketName: aws-managed-cost-intelligence-dashboards-us-east-2}
us-west-1: {BucketName: aws-managed-cost-intelligence-dashboards-us-west-1}
us-west-2: {BucketName: aws-managed-cost-intelligence-dashboards-us-west-2}
#todo: add af-south-1
#todo: add ap-southeast-3
#todo: add eu-south-1
#todo: add eu-central-2
Resources:
SpiceRefreshExecutionRole: #Role needed to schedule spice ingestion for the datasets not used by default
Type: AWS::IAM::Role
Condition: NeedRefreshDatasets
Properties:
Path: !Ref RolePath
RoleName: !Sub 'CidSpiceRefreshExecutionRole${Suffix}'
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
PermissionsBoundary: !If [NeedPermissionsBoundary, !Ref PermissionsBoundary, !Ref 'AWS::NoValue']
Policies:
- PolicyName: !Sub 'CidSpiceRefreshExecutionRole${Suffix}'
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action: quicksight:CreateIngestion
Resource:
- !Sub 'arn:${AWS::Partition}:quicksight:${AWS::Region}:${AWS::AccountId}:*'
- Effect: Allow
Action: quicksight:ListDatasets
Resource:
- !Sub 'arn:${AWS::Partition}:quicksight:${AWS::Region}:${AWS::AccountId}:dataset/*'
- Effect: Allow
Action: quicksight:ListIngestions
Resource:
- !Sub 'arn:${AWS::Partition}:quicksight:${AWS::Region}:${AWS::AccountId}:dataset/*/ingestion/*'
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource:
- !Sub 'arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/Cid*'
Metadata:
cfn_nag:
rules_to_suppress:
- id: 'W28'
reason: "Need explicit name to give permissions"
# Currently QS has no api for managing updates, so we need to set up a scheduled lambda.
# Once QS will provide the API for scheduling this will be removed.
SpiceRefreshLambda:
Type: AWS::Lambda::Function
Condition: NeedRefreshDatasets
Properties:
FunctionName: !Sub 'CidSpiceRefreshLambda${Suffix}'
Role: !GetAtt SpiceRefreshExecutionRole.Arn
Description: 'Refresh QuickSight DataSets for CID'
Runtime: python3.11
Architectures: [ x86_64 ] #Compatible with arm64 but it is not supported in all regions
MemorySize: 128
Timeout: 60
Environment:
Variables:
#SUFFIX: !Ref Suffix
SUFFIX: '' # CID CMD does not support suffixes yet
Handler: index.lambda_handler
Code:
ZipFile: |
import os
from datetime import datetime
from datetime import timedelta
from datetime import timezone
import boto3
## List of DataSets can be found in cid-cmd:
# from cid.common import Cid
# DATASETS = list(Cid().resources['datasets'].keys())
DATASETS = '''
summary_view
hourly_view
resource_view
ec2_running_cost
compute_savings_plan_eligible_spend
s3_view
kpi_ebs_snap
kpi_ebs_storage_all
kpi_instance_all
kpi_s3_storage_all
kpi_tracker
ta-organizational-view
daily-anomaly-detection
monthly-anomaly-detection
monthly-bill-by-account
compute_optimizer_all_options
'''.strip().split()
DATASETS_TO_REFRESH = [ name + os.environ.get('SUFFIX', '') for name in DATASETS]
def lambda_handler(event, context):
account_id = context.invoked_function_arn.split(":")[4]
quicksight = boto3.client('quicksight')
for page in quicksight.get_paginator('list_data_sets').paginate(AwsAccountId=account_id):
for dataset in page['DataSetSummaries']:
name = dataset['Name']
if dataset['ImportMode'] != 'SPICE' or name not in DATASETS_TO_REFRESH:
continue
scheduled_ingestion = None
stop_processing = False
for ingestions_page in quicksight.get_paginator('list_ingestions').paginate(AwsAccountId=account_id, DataSetId=dataset['DataSetId']):
for ingestion in ingestions_page['Ingestions']:
time_since_creation = datetime.now(timezone.utc) - ingestion['CreatedTime']
if time_since_creation <= timedelta(days = 1, hours = 1):
if ingestion['RequestSource'] == 'SCHEDULED':
scheduled_ingestion = ingestion
stop_processing = True
else:
stop_processing = True
if stop_processing:
break
if stop_processing:
break
if scheduled_ingestion is not None:
print(f"INFO: Dataset {name} has a scheduled ingestion within the last 24 hours. Skipping manual refresh.")
print('DEBUG: scheduled_ingestion=', scheduled_ingestion)
continue
print(f"INFO: Refreshing dataset {name}")
res = quicksight.create_ingestion(
AwsAccountId=account_id,
DataSetId=dataset['DataSetId'],
IngestionId=datetime.now().strftime("%d%m%y-%H%M%S-%f"),
)
print('DEBUG: response=', res)
Metadata:
cfn_nag:
rules_to_suppress:
- id: 'W89'
reason: "No need to access to VPC resources"
- id: 'W92'
reason: "No need for reserved concurrency"
SpiceRefreshRule:
Type: AWS::Events::Rule
Condition: NeedRefreshDatasets
Properties:
ScheduleExpression: !Ref QuickSightDataSetRefreshSchedule
Targets:
- Id: SpiceRefreshScheduler
Arn: !GetAtt SpiceRefreshLambda.Arn
SpiceRefreshInvokeLambdaPermission:
Type: AWS::Lambda::Permission
Condition: NeedRefreshDatasets
Properties:
FunctionName: !GetAtt SpiceRefreshLambda.Arn
Action: lambda:InvokeFunction
Principal: events.amazonaws.com
SourceArn: !GetAtt SpiceRefreshRule.Arn
MyAthenaQueryResultsBucket:
Type: AWS::S3::Bucket
Condition: NeedAthenaQueryResultsBucket
Properties:
BucketName: !Sub "${AWS::Partition}-athena-query-results-cid-${AWS::AccountId}-${AWS::Region}"
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: AES256
AccessControl: BucketOwnerFullControl
OwnershipControls:
Rules:
- ObjectOwnership: BucketOwnerEnforced
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
LifecycleConfiguration:
Rules:
- Id: DeleteContent
Status: 'Enabled'
ExpirationInDays: 7
Metadata:
cfn-lint:
config:
ignore_checks:
- W3045 #Consider using AWS::S3::BucketPolicy instead of AccessControl; standard Athena results setup
cfn_nag:
rules_to_suppress:
- id: 'W35'
reason: "Data buckets would generate too much logs"
- id: 'W51'
reason: "No policy needed"
MyAthenaWorkGroup:
Type: AWS::Athena::WorkGroup
Condition: NeedAthenaWorkgroup
Properties:
Name: !Sub 'CID${Suffix}'
Description: !Sub 'Used for CloudIntelligenceDashboards${Suffix}'
State: ENABLED
RecursiveDeleteOption: true
WorkGroupConfiguration:
EnforceWorkGroupConfiguration: true
ResultConfiguration:
EncryptionConfiguration:
EncryptionOption: SSE_S3
ExpectedBucketOwner: !Ref AWS::AccountId
OutputLocation: !If [ NeedAthenaQueryResultsBucket, !Sub 's3://${MyAthenaQueryResultsBucket}/', !Sub 's3://${AthenaQueryResultsBucket}/' ]
#Legacy version. Replaced by CustomResourceFunctionInit but we cannot remove it completely as it was removing workgroup on deletion of the custom resource.
CustomRessourceFunctionInit:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub CidInitialSetup-DoNotRun${Suffix}
Role: !GetAtt 'InitLambdaExecutionRole.Arn'
Description: "CID legacy setup"
Runtime: python3.11
Handler: 'index.lambda_handler'
Code:
ZipFile: |
# This is a legacy lambda. You can delete it. This was kept to disable delete workgroup functionality.
import json
import urllib3
def lambda_handler(event, context):
url = event.get('ResponseURL')
json_body = json.dumps({
'Status': 'SUCCESS',
'Reason': 'legacy',
'PhysicalResourceId': 'keep_it_constant',
'StackId': event.get('StackId'),
'RequestId': event.get('RequestId'),
'LogicalResourceId': event.get('LogicalResourceId'),
})
try:
http = urllib3.PoolManager()
response = http.request('PUT', url, body=json_body, headers={'content-type' : '', 'content-length' : str(len(json_body))}, retries=False)
print(f"Status code: {response}")
except Exception as exc:
print("Failed sending PUT to CFN: " + str(exc))
Metadata:
cfn_nag:
rules_to_suppress:
- id: 'W89'
reason: "No need to access to VPC resources"
- id: 'W92'
reason: "No need for reserved concurrency"
CustomResourceFunctionInit:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub "CidCustomResourceFunctionInit-DoNotRun${Suffix}"
Role: !GetAtt 'InitLambdaExecutionRole.Arn'
Description: "Do what CFN cannot: start crawler and delete bucket with objects"
Runtime: python3.11
Architectures: [ x86_64 ] #Compatible with arm64 but it is not supported in all regions
MemorySize: 128
Timeout: 600
Handler: 'index.lambda_handler'
Code:
ZipFile: |
import os
import uuid
import json
import time
import boto3
import botocore
import urllib3
from cid.helpers import QuickSight # from layer
from cid.utils import set_parameters
BUCKET = os.environ['BUCKET']
CRAWLER = os.environ['CRAWLER']
QUICKSIGHT_USER = os.environ['QUICKSIGHT_USER']
QUICKSIGHT_ROLE = os.environ.get('QUICKSIGHT_ROLE')
def lambda_handler(event, context):
print(event)
type_ = event.get('RequestType', 'Undef')
region = boto3.session.Session().region_name
res = (True, f"Un error on {type_}. Check logs")
identity_region = ''
try:
if type_ == 'Create': res = on_create()
elif type_ == 'Delete': res = on_delete()
else: res = (True, f"Not supported operation: {type_}")
set_parameters({'quicksight-user': QUICKSIGHT_USER})
identity_region = get_identity_region()
except Exception as exc:
res = False, str(exc)[:1000]
finally:
log_url = f"https://{region}.console.aws.amazon.com/cloudwatch/home?region={region}#logEvent:group={context.log_group_name};stream={context.log_stream_name}"
url = event.get('ResponseURL')
body = {}
body['Status'] = 'SUCCESS' if res[0] else 'FAILED'
body['Reason'] = res[1] + '\nLogs: ' + log_url
body['PhysicalResourceId'] = 'keep_it_constant'
body['StackId'] = event.get('StackId')
body['RequestId'] = event.get('RequestId')
body['LogicalResourceId'] = event.get('LogicalResourceId')
body['NoEcho'] = False
body['Data'] = {'Reason': res[1], 'uuid': str(uuid.uuid1()), 'IdentityRegion': identity_region}
print(body)
if not url: return
json_body=json.dumps(body)
try:
http = urllib3.PoolManager()
response = http.request('PUT', url, body=json_body, headers={'content-type' : '', 'content-length' : str(len(json_body))}, retries=False)
print(f"Status code: {response}")
except Exception as exc:
print("Failed sending PUT to CFN: " + str(exc))
def get_identity_region():
qs = QuickSight(boto3.session.Session())
return qs.identityRegion
def on_create():
if CRAWLER:
timeout_seconds = 300
glue = boto3.client('glue')
try:
glue.start_crawler(Name=CRAWLER)
except Exception as exc:
if 'CrawlerRunningException' in str(exc):
print ("crawler is running already")
else:
return (True, f'ERROR: error invoking crawler {CRAWLER} {exc}')
print('started crawler started. waiting for crawler to finish')
try:
start_time = time.time()
while time.time() - start_time < timeout_seconds:
time.sleep(1)
crawler_status = glue.get_crawler(Name=CRAWLER)['Crawler']['State']
print(f'status = {crawler_status}')
if crawler_status in ('READY', 'STOPPING'):
print("Stop waiting")
break
else:
return (True, f"Timeout exceeded. Crawler '{CRAWLER}' did not complete. This is not a fatal error and the rest of the deployment will continue.")
except Exception as exc:
return (True, f'ERROR: error waiting for crawler {CRAWLER} {exc}')
return (True, 'Crawler run completed.')
return (True, 'Ended create.')
def on_delete():
# Delete bucket (CF cannot delete if they are non-empty)
s3 = boto3.resource('s3')
log = []
if BUCKET:
try:
bucket = s3.Bucket(BUCKET)
res = bucket.object_versions.delete()
print(f'DEBUG: empty response = {res} ')
res = bucket.delete()
print(f'DEBUG: delete response = {res} ')
log.append(f'INFO: {BUCKET} deleted')
except botocore.exceptions.ClientError as exc:
status = exc.response["ResponseMetadata"]["HTTPStatusCode"]
errcode = exc.response["Error"]["Code"]
if status == 404:
log.append(f'INFO: {BUCKET} - {errcode}')
else:
log.append(f'ERROR: {BUCKET} - {errcode}')
except Exception as exc:
log.append(f'ERROR: {BUCKET} Error: {exc}')
if QUICKSIGHT_ROLE:
try:
role_name = QUICKSIGHT_ROLE.split('/')[-1]
iam = boto3.client('iam')
attached_policies = iam.list_attached_role_policies(RoleName=role_name)['AttachedPolicies']
for policy in attached_policies:
iam.detach_role_policy(
RoleName=role_name,
PolicyArn=policy['PolicyArn']
)
print(f"DEBUG: Detached managed policy: {policy['PolicyName']}")
log.append(f"DEBUG: Detached managed policy: {policy['PolicyName']}")
except Exception as exc:
log.append(f'ERROR: managed policy Error: {exc}')
print('\n'.join(log))
return (True, '\n'.join(log))
Layers:
- !Ref CidResourceLambdaLayer
Environment:
Variables:
BUCKET: !If [NeedAthenaQueryResultsBucket, !Ref MyAthenaQueryResultsBucket, '']
CRAWLER: !If [NeedCURTable, !Ref MyGlueCURCrawler, '']
QUICKSIGHT_USER: !Ref QuickSightUser
QUICKSIGHT_ROLE: !If [ NeedQuickSightDataSourceRole, !Ref QuickSightDataSourceRole, !Ref 'AWS::NoValue' ]
Metadata:
cfn_nag:
rules_to_suppress:
- id: 'W89'
reason: "No need to access to VPC resources"
- id: 'W92'
reason: "No need for reserved concurrency"
InitLambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
Path: !Ref RolePath
Policies:
- PolicyName: root
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action: quicksight:DescribeUser
Resource: !Sub 'arn:${AWS::Partition}:quicksight:*:${AWS::AccountId}:user/default/${QuickSightUser}' # region=* as at this moment we do not know the Identity region where QS stores users
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource:
- !Sub 'arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/Cid*'
- !If
- NeedQuickSightDataSourceRole
- Effect: Allow
Action:
- iam:GetRole
- iam:ListAttachedRolePolicies
- iam:DetachRolePolicy
Resource: !Sub "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/${QuickSightDataSourceRole}"
- !Ref 'AWS::NoValue'
PermissionsBoundary: !If [NeedPermissionsBoundary, !Ref PermissionsBoundary, !Ref 'AWS::NoValue']
InitLambdaExecutionRoleBucketPolicy:
Type: AWS::IAM::Policy
Condition: NeedAthenaQueryResultsBucket
Properties:
PolicyName: AthenaQueryResultsBucketDeletion
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- s3:DeleteObject
- s3:DeleteObjectVersion
Resource:
- !Sub 'arn:${AWS::Partition}:s3:::${MyAthenaQueryResultsBucket}/*'
- Effect: Allow
Action:
- s3:ListBucketVersions
- s3:DeleteBucket
Resource:
- !Sub 'arn:${AWS::Partition}:s3:::${MyAthenaQueryResultsBucket}'
Roles:
- !Ref InitLambdaExecutionRole
InitLambdaExecutionRoleStartCrawlerPolicy:
Type: AWS::IAM::Policy
Condition: NeedCURTable
Properties:
PolicyName: StartCrawler
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- glue:StartCrawler
- glue:GetCrawler
Resource:
- !Sub 'arn:${AWS::Partition}:glue:${AWS::Region}:${AWS::AccountId}:crawler/${MyGlueCURCrawler}'
Roles:
- !Ref InitLambdaExecutionRole
Setup:
Type: Custom::CustomResource
Properties:
ServiceToken: !GetAtt CustomResourceFunctionInit.Arn
Tags: # Hacky way to manage conditional dependencies
- Key: IgnoreConditionalDependsOnAthenaQueryResultsBucket
Value: !If [NeedAthenaQueryResultsBucket, !Ref MyAthenaQueryResultsBucket, '']
- Key: IgnoreConditionalDependsOnAthenaWorkgroup
Value: !If [NeedAthenaWorkgroup, !Ref MyAthenaWorkGroup, '']
- Key: IgnoreConditionalDependsOnDatabase
Value: !If [NeedCURTable, !Ref MyGlueCURCrawler, '']
- Key: IgnoreConditionalDependsOnPolicy2
Value: !If [NeedAthenaQueryResultsBucket, !Ref InitLambdaExecutionRoleBucketPolicy, '']
- Key: IgnoreConditionalDependsOnPolicy3
Value: !If [NeedCURTable, !Ref InitLambdaExecutionRoleStartCrawlerPolicy, '']
ProcessPathLambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
Path: !Ref RolePath
PermissionsBoundary: !If [NeedPermissionsBoundary, !Ref PermissionsBoundary, !Ref 'AWS::NoValue']
Policies:
- PolicyName: CloudWatch
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource:
- !Sub 'arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/Cid*'
CustomResourceProcessPath:
Type: AWS::Lambda::Function
Properties:
Role: !GetAtt 'ProcessPathLambdaExecutionRole.Arn'
FunctionName: !Sub "CidCustomResourceProcessPath-DoNotRun${Suffix}"
Description: "Do what CFN cannot: process string of path"
Runtime: python3.11
Architectures: [ x86_64 ] #Compatible with arm64 but it is not supported in all regions
MemorySize: 128
Timeout: 60
Handler: 'index.lambda_handler'
Code:
ZipFile: |
import uuid
import json
import urllib3
import botocore
import boto3
partitions = {
"managed_by_cfn": ["source_account_id", "cur_name_1", "cur_name_2", "year", "month"],
"manual": ["year", "month"],
}
def lambda_handler(event, context):
print(json.dumps(event))
account_id = context.invoked_function_arn.split(":")[4]
type_ = event.get('RequestType', 'Undef')
region = boto3.session.Session().region_name
properties = event.get('ResourceProperties', {})
status, reason = ('SUCCESS', "Undef")
data = {}
body = {}
try:
s3path = properties.get('s3path', '')
if s3path.startswith('s3://'):
s3path = s3path[len('s3://'):]
if s3path.endswith('/'):
s3path = s3path[:-1]
s3path = s3path.replace('{account_id}', account_id)
parts = s3path.split('/')
data['Bucket'] = parts[0]
if properties.get('type', '') == 'CUR':
if not bucket_exists(data['Bucket']) and type_.lower() != 'delete':
raise Exception(f'Bucket {parts[0]} does not exist. Please check prerequisites. Just creating a bucket is not enough.')
# detect Type of CUR and choose the right partitions structure
if len(parts[1:]) == 1: # most likely it is created by CFN or similar
data['Partitions'] = partitions['managed_by_cfn']
elif len(parts) > 3 and parts[-1] == parts[-2]: # most likely it is manual CUR
data['Partitions'] = partitions['manual']
elif type_.lower() == 'delete':
pass # Do not fail delete
else:
raise Exception(f'CUR BucketPath={parts[0]} format is not recognized. It must be s3://(bucket)/cur or s3://(bucket)/(curprefix)/(curname)/(curname) ')
data['Partitions'] = [{"Name": p, "Type": "string"} for p in data.get('Partitions', [])]
data['Path'] = '/'.join(parts[1:])
data['Folder'] = parts[-1] if len(parts) > 1 else ''
data['Folder'] = data['Folder'].replace('-', '_').lower() # this is used for a Glue table name that will be managed by crawler
status, reason = 'SUCCESS', ""
except Exception as exc:
status, reason = 'FAILED', str(exc)
finally:
log_url = f"https://{region}.console.aws.amazon.com/cloudwatch/home?region={region}#logEvent:group={context.log_group_name};stream={context.log_stream_name}"
url = event.get('ResponseURL')
body['Status'] = status
body['Reason'] = reason + '\nLogs: ' + log_url
body['PhysicalResourceId'] = s3path
body['StackId'] = event.get('StackId')
body['RequestId'] = event.get('RequestId')
body['LogicalResourceId'] = event.get('LogicalResourceId')
body['Data'] = data
json_body=json.dumps(body)
print(json_body)
if not url: return
try:
http = urllib3.PoolManager()
response = http.request('PUT', url, body=json_body, headers={'content-type' : '', 'content-length' : str(len(json_body))}, retries=False)
print(f"Status code: {response}")
except Exception as exc:
print("Failed sending PUT to CFN: " + str(exc))
def bucket_exists(name):
try:
boto3.resource('s3').meta.client.head_bucket(Bucket=name)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == '404':
return False
return True
Metadata:
cfn_nag:
rules_to_suppress:
- id: 'W89'
reason: "No need to access to VPC resources"
- id: 'W92'
reason: "No need for reserved concurrency"
CURPath:
Type: Custom::CustomResourceProcessPath
Condition: NeedLegacyCUR
Properties:
ServiceToken: !GetAtt CustomResourceProcessPath.Arn
s3path: !Ref CURBucketPath
type: 'CUR'
ODCPath:
Type: Custom::CustomResourceProcessPath
#Condition: NeedDataCollectionLab #Need to process ODC lab path regardless dashboards. CUR dashboards need ODC for account map
Properties:
ServiceToken: !GetAtt CustomResourceProcessPath.Arn
s3path: !Ref OptimizationDataCollectionBucketPath
CidDatabase:
Type: AWS::Glue::Database
Condition: NeedDatabase
Properties:
DatabaseInput:
Name: !Join [ '_', !Split [ '-', !Sub 'cid_cur${Suffix}' ] ] # replace '-' to '_'
CatalogId: !Sub '${AWS::AccountId}'
MyGlueCURCrawler:
Type: AWS::Glue::Crawler
Condition: NeedCURTable
Properties:
Name: !Sub 'CidCrawler${Suffix}'
Description: A recurring crawler that keeps your CUR table in Athena up-to-date.
Role:
Fn::GetAtt: CidCURCrawlerRole.Arn
DatabaseName: !If [NeedDatabase, !Ref CidDatabase, !Ref DatabaseName ]
Targets:
S3Targets:
- Path: !Sub 's3://${CURPath.Bucket}/${CURPath.Path}/'
Exclusions:
- '**.json'
- '**.yml'
- '**.sql'
- '**.csv'
- '**.csv.metadata'
- '**.gz'
- '**.zip'
- '**/cost_and_usage_data_status/*'
- 'aws-programmatic-access-test-object'
SchemaChangePolicy:
DeleteBehavior: LOG
RecrawlPolicy: