forked from aws-samples/aws-cudos-framework-deployment
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cid-cfn.yml
1670 lines (1604 loc) · 73.6 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 v0.2.36
Metadata:
AWS::CloudFormation::Interface:
ParameterGroups:
- Label:
default: 'Common Parameters'
Parameters:
- PrerequisitesQuickSight
- PrerequisitesQuickSightPermissions
- QuickSightUser
- 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:
- CURBucketPath
- 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://wellarchitectedlabs.com/cost/300_labs/300_optimization_data_collection/)
Parameters:
- OptimizationDataCollectionBucketPath
- DeployTAODashboard
- DeployComputeOptimizerDashboard
- PrimaryTagName
- SecondaryTagName
- Label:
default: 'Technical Parameters. Please do not change.'
Parameters:
- LakeFormationEnabled
- AthenaWorkgroup
- AthenaQueryResultsBucket
- DatabaseName
- CURTableName
- GlueDataCatalog
- Suffix
- QuickSightDataSourceRoleName
- QuickSightDataSetRefreshSchedule
- LambdaLayerBucketPrefix
- DeployCUDOSDashboard
- DataBucketsKmsKeyArns
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 Cost and Usage report"
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 to be used on QuickSight Datasource Creation (if not provided, the default QuickSight Role will be used)."
QuickSightDataSetRefreshSchedule:
default: "QuickSight DataSet Refresh Schedule. Must be a valid cron or empty. If empty refresh will be disabled."
LambdaLayerBucketPrefix:
default: "LambdaLayerBucketPrefix - Please do not change"
GlueDataCatalog:
default: "Existing Glue Data Catalog"
DataBucketsKmsKeyArns:
default: "ARNs of KMS Keys for data bucket. Keep empty if data Buckets are not Encrypted with KMS. Also you can set it to '*'."
PrimaryTagName:
Default: "Choose a tag name. Currently used only in Compute Optimizer dashboard."
SecondaryTagName:
Default: "Choose a tag name. Currently used only in Compute Optimizer dashboard."
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)."
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://wellarchitectedlabs.com/cost/300_labs/300_optimization_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://wellarchitectedlabs.com/cost/300_labs/300_optimization_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://costoptimizationdata{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"
DataBucketsKmsKeyArns:
Type: String
Description: "ARNs of KMS Keys for data bucket. Keep empty if data Buckets are not Encrypted with KMS. Also you can set it to '*'."
Default: "*"
LakeFormationEnabled:
Type: String
Description: Choose 'yes' if Lake Formation permission model is in place for the account
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.
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. Leve as is if not sure.
Default: "environment"
MinLength: 1 # cid cmd do not accept empty parameters
AllowedPattern: "[a-zA-Z0-9_]*"
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" ]
NeedComputeOptimizerDashboard: !Equals [ !Ref DeployComputeOptimizerDashboard, "yes" ]
NeedCUR:
Fn::Or:
- !Equals [ !Ref DeployCUDOSDashboard, "yes" ]
- !Equals [ !Ref DeployCUDOSv5, "yes" ]
- !Equals [ !Ref DeployCostIntelligenceDashboard, "yes" ]
- !Equals [ !Ref DeployKPIDashboard, "yes" ]
NeedDataCollectionLab:
Fn::Or:
- !Equals [ !Ref DeployTAODashboard, "yes" ]
- !Equals [ !Ref DeployComputeOptimizerDashboard, "yes" ]
NeedAthenaWorkgroup: !Equals [ !Ref AthenaWorkgroup, "" ]
NeedAthenaQueryResultsBucket: !Equals [ !Ref AthenaQueryResultsBucket, "" ]
NeedDatabase:
Fn::And:
- !Equals [ !Ref DatabaseName, "" ]
- Fn::Or:
- !Condition NeedDataCollectionLab
- !Condition NeedCUR
NeedCURTable:
Fn::And:
- !Equals [ !Ref CURTableName, "" ]
- !Condition NeedCUR
NeedRefreshDatasets: !Not [ !Equals [ !Ref QuickSightDataSetRefreshSchedule, ""] ]
NeedDataBucketsKms: !Equals [ !Ref DataBucketsKmsKeyArns, "" ]
NeedDataBucketsKmsAndNeedCURTable:
Fn::And:
- !Condition NeedDataBucketsKms
- !Condition NeedCURTable
NeedDatasource: !Not [ !Equals [ !Ref "AWS::Region", "eu-west-3" ] ] # In eu-west-3 CFN QS Dataset resource is not available yet.
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
UseQuickSightDataSourceRole:
Fn::And:
- !Condition NeedDatasource
- !Not [!Equals [ !Ref QuickSightDataSourceRoleName, "" ]]
NeedQuickSightDataSourceRole:
Fn::And:
- !Condition NeedDatasource
- !Equals [ !Ref QuickSightDataSourceRoleName, "CidQuickSightDataSourceRole" ]
NeedQuickSightDataSourceRoleAndCUR:
Fn::And:
- !Condition NeedQuickSightDataSourceRole
- !Condition NeedCUR
Resources:
SpiceRefreshExecutionRole: #Role needed to schedule spice ingestion for the datasets
Type: AWS::IAM::Role
Condition: NeedRefreshDatasets
Properties:
Path: /
RoleName: !Sub 'CidSpiceRefreshExecutionRole${Suffix}'
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
ManagedPolicyArns:
- !Sub arn:${AWS::Partition}:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
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/*'
# 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.10
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
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)
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
MyAthenaWorkGroup:
Type: AWS::Athena::WorkGroup
Condition: NeedAthenaWorkgroup
Properties:
Name: !Sub 'CID${Suffix}'
Description: !Sub 'Used for CloudIntelligenceDashboards${Suffix}'
WorkGroupConfiguration:
EnforceWorkGroupConfiguration: true
ResultConfiguration:
EncryptionConfiguration:
EncryptionOption: SSE_S3
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.10
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))
CustomResourceFunctionInit:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub "CidCustomResourceFunctionInit-DoNotRun${Suffix}"
Role: !GetAtt 'InitLambdaExecutionRole.Arn'
Description: "Do what CFN cannot: start crawler, delete bucket with objects and delete an non empty workgroup"
Runtime: python3.10
Architectures: [ x86_64 ] #Compatible with arm64 but it is not supported in all regions
MemorySize: 128
Timeout: 300
Handler: 'index.lambda_handler'
Code:
ZipFile: |
import os
import uuid
import json
import boto3
import botocore
import urllib3
from cid.helpers import QuickSight # from layer
from cid.utils import set_parameters
BUCKET = os.environ['BUCKET']
WORKGROUP = os.environ['WORKGROUP']
CRAWLER = os.environ['CRAWLER']
QUICKSIGHT_USER = os.environ['QUICKSIGHT_USER']
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()
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:
try:
boto3.client('glue').start_crawler(Name=CRAWLER)
except Exception as exc:
return (True, f'ERROR: error invoking crawler {CRAWLER} {exc}')
return (True, 'INFO: crawler started. Takes 1 min to update the table.')
return (True, 'INFO: No actions on create')
def on_delete():
# Delete bucket (CF cannot delete if they are non-empty)
# and delete WorkGroup (CF cannot do that)
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 WORKGROUP:
try:
response = boto3.client('athena').delete_work_group(
WorkGroup=WORKGROUP,
RecursiveDeleteOption=True
)
print(f'DEBUG: WorkGroup {WORKGROUP} deleted. {response}')
log.append(f'INFO: WorkGroup {WORKGROUP} deleted.')
except botocore.exceptions.ClientError as exc:
status = exc.response["ResponseMetadata"]["HTTPStatusCode"]
errcode = exc.response["Error"]["Code"]
if status == 404:
log.append(f'INFO: WorkGroup {WORKGROUP} - {errcode}')
else:
log.append(f'ERROR: WorkGroup {WORKGROUP} - {errcode}')
except Exception as exc:
log.append(f'ERROR: WorkGroup {WORKGROUP} Error: {exc}')
print('\n'.join(log))
return (True, '\n'.join(log))
Layers:
- !Ref CidResourceLambdaLayer
Environment:
Variables:
BUCKET: !If [NeedAthenaQueryResultsBucket, !Ref MyAthenaQueryResultsBucket, '']
WORKGROUP: !If [NeedAthenaWorkgroup, !Ref MyAthenaWorkGroup, '']
CRAWLER: !If [NeedCURTable, !Ref MyGlueCURCrawler, '']
QUICKSIGHT_USER: !Ref QuickSightUser
InitLambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
Path: /
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
ManagedPolicyArns:
- !Sub arn:${AWS::Partition}:iam::aws:policy/AWSLambdaExecute
InitLambdaExecutionRoleWorkGroupPolicy:
Type: AWS::IAM::Policy
Condition: NeedAthenaWorkgroup
Properties:
PolicyName: AthenaWorkGroupDeletion
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action: athena:DeleteWorkGroup
Resource: !Sub 'arn:${AWS::Partition}:athena:${AWS::Region}:${AWS::AccountId}:workgroup/${MyAthenaWorkGroup}'
Roles:
- !Ref InitLambdaExecutionRole
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
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: IgnoreConditionalDependsOnPolicy1
Value: !If [NeedAthenaWorkgroup, !Ref InitLambdaExecutionRoleWorkGroupPolicy, '']
- 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: /
ManagedPolicyArns:
- !Sub arn:${AWS::Partition}:iam::aws:policy/AWSLambdaExecute
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.10
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['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
CURPath:
Type: Custom::CustomResourceProcessPath
Condition: NeedCUR
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:
RecrawlBehavior: CRAWL_EVERYTHING
Schedule:
ScheduleExpression: cron(0 2 * * ? *)
Configuration: |
{
"Version":1.0,
"Grouping": {
"TableGroupingPolicy": "CombineCompatibleSchemas"
},
"CrawlerOutput":{
"Tables":{
"AddOrUpdateBehavior":"MergeNewColumns"
}
}
}
MyCURTable: # Initial creation of table. it will be updated by crawler later
Type: AWS::Glue::Table
Condition: NeedCURTable
Properties:
CatalogId: !Ref "AWS::AccountId"
DatabaseName: !If [NeedDatabase, !Ref CidDatabase, !Ref DatabaseName ]
TableInput:
Name: !GetAtt CURPath.Folder
Owner: owner
Retention: 0
TableType: EXTERNAL_TABLE
Parameters:
compressionType: none
classification: parquet
UPDATED_BY_CRAWLER: !Ref MyGlueCURCrawler
StorageDescriptor:
BucketColumns: []
Compressed: false
Location: !Sub 's3://${CURPath.Bucket}/${CURPath.Path}/'
NumberOfBuckets: -1
InputFormat: org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat
OutputFormat: org.apache.hadoop.hive.ql.io.parquet.MapredParquetOutputFormat
SerdeInfo:
Parameters:
serialization.format: '1'
SerializationLibrary: org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe
StoredAsSubDirectories: false
Columns: # All fields required for CID
- {"Name": "bill_bill_type", "Type": "string" }
- {"Name": "bill_billing_entity", "Type": "string" }
- {"Name": "bill_billing_period_end_date", "Type": "timestamp" }
- {"Name": "bill_billing_period_start_date", "Type": "timestamp" }
- {"Name": "bill_invoice_id", "Type": "string" }
- {"Name": "bill_payer_account_id", "Type": "string" }
- {"Name": "identity_line_item_id", "Type": "string" }
- {"Name": "identity_time_interval", "Type": "string" }
- {"Name": "line_item_availability_zone", "Type": "string" }
- {"Name": "line_item_legal_entity", "Type": "string" }
- {"Name": "line_item_line_item_description", "Type": "string" }
- {"Name": "line_item_line_item_type", "Type": "string" }
- {"Name": "line_item_operation", "Type": "string" }
- {"Name": "line_item_product_code", "Type": "string" }
- {"Name": "line_item_resource_id", "Type": "string" }
- {"Name": "line_item_unblended_cost", "Type": "double" }
- {"Name": "line_item_usage_account_id", "Type": "string" }
- {"Name": "line_item_usage_amount", "Type": "double" }
- {"Name": "line_item_usage_end_date", "Type": "timestamp" }
- {"Name": "line_item_usage_start_date", "Type": "timestamp" }
- {"Name": "line_item_usage_type", "Type": "string" }
- {"Name": "pricing_lease_contract_length", "Type": "string" }
- {"Name": "pricing_offering_class", "Type": "string" }
- {"Name": "pricing_public_on_demand_cost", "Type": "double" }
- {"Name": "pricing_purchase_option", "Type": "string" }
- {"Name": "pricing_term", "Type": "string" }
- {"Name": "pricing_unit", "Type": "string" }
- {"Name": "product_cache_engine", "Type": "string" }
- {"Name": "product_current_generation", "Type": "string" }
- {"Name": "product_database_engine", "Type": "string" }
- {"Name": "product_deployment_option", "Type": "string" }
- {"Name": "product_from_location", "Type": "string" }
- {"Name": "product_group", "Type": "string" }
- {"Name": "product_instance_type", "Type": "string" }
- {"Name": "product_instance_type_family", "Type": "string" }
- {"Name": "product_license_model", "Type": "string" }
- {"Name": "product_operating_system", "Type": "string" }
- {"Name": "product_physical_processor", "Type": "string" }
- {"Name": "product_processor_features", "Type": "string" }
- {"Name": "product_product_family", "Type": "string" }
- {"Name": "product_product_name", "Type": "string" }
- {"Name": "product_region", "Type": "string" }
- {"Name": "product_servicecode", "Type": "string" }
- {"Name": "product_storage", "Type": "string" }
- {"Name": "product_tenancy", "Type": "string" }
- {"Name": "product_to_location", "Type": "string" }
- {"Name": "product_volume_api_name", "Type": "string" }
- {"Name": "product_volume_type", "Type": "string" }
- {"Name": "reservation_amortized_upfront_fee_for_billing_period", "Type": "double" }
- {"Name": "reservation_effective_cost", "Type": "double" }
- {"Name": "reservation_end_time", "Type": "string" }
- {"Name": "reservation_reservation_a_r_n", "Type": "string" }
- {"Name": "reservation_start_time", "Type": "string" }
- {"Name": "reservation_unused_amortized_upfront_fee_for_billing_period", "Type": "double" }
- {"Name": "reservation_unused_recurring_fee", "Type": "double" }
- {"Name": "savings_plan_amortized_upfront_commitment_for_billing_period", "Type": "double" }
- {"Name": "savings_plan_end_time", "Type": "string" }
- {"Name": "savings_plan_offering_type", "Type": "string" }
- {"Name": "savings_plan_payment_option", "Type": "string" }
- {"Name": "savings_plan_purchase_term", "Type": "string" }
- {"Name": "savings_plan_savings_plan_a_r_n", "Type": "string" }
- {"Name": "savings_plan_savings_plan_effective_cost", "Type": "double" }
- {"Name": "savings_plan_start_time", "Type": "string" }
- {"Name": "savings_plan_total_commitment_to_date", "Type": "double" }
- {"Name": "savings_plan_used_commitment", "Type": "double" }
PartitionKeys: !GetAtt CURPath.Partitions
CidCURCrawlerRole:
Type: AWS::IAM::Role
Condition: NeedCURTable
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- glue.amazonaws.com
Action:
- 'sts:AssumeRole'
Path: /
ManagedPolicyArns:
- Fn::Sub: 'arn:${AWS::Partition}:iam::aws:policy/service-role/AWSGlueServiceRole'
Policies:
- PolicyName: AWSCURCrawlerComponentFunction
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- 'glue:UpdateDatabase'
- 'glue:UpdatePartition'
- 'glue:CreateTable'
- 'glue:UpdateTable'
- 'glue:ImportCatalogToGlue'
Resource:
- !Sub arn:${AWS::Partition}:glue:${AWS::Region}:${AWS::AccountId}:catalog
- Fn::If: